repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list | possible_versions
list |
---|---|---|---|---|---|
keshav47/pytorch-metric-learning
|
[
"501e4cb5e56c56d09413c98a93039669abc2232b",
"1fb343124d15fd2f63d535df26aa1463daf4ceee"
] |
[
"src/pytorch_metric_learning/losses/ntxent_loss.py",
"src/pytorch_metric_learning/utils/inference.py"
] |
[
"import torch\n\nfrom ..distances import CosineSimilarity\nfrom ..utils import common_functions as c_f\nfrom .generic_pair_loss import GenericPairLoss\n\n\nclass NTXentLoss(GenericPairLoss):\n def __init__(self, temperature=0.07, **kwargs):\n super().__init__(mat_based_loss=False, **kwargs)\n self.temperature = temperature\n self.add_to_recordable_attributes(list_of_names=[\"temperature\"], is_stat=False)\n\n def _compute_loss(self, pos_pairs, neg_pairs, indices_tuple):\n a1, p, a2, _ = indices_tuple\n\n if len(a1) > 0 and len(a2) > 0:\n dtype = neg_pairs.dtype\n # if dealing with actual distances, use negative distances\n if not self.distance.is_inverted:\n pos_pairs = -pos_pairs\n neg_pairs = -neg_pairs\n\n pos_pairs = pos_pairs.unsqueeze(1) / self.temperature\n neg_pairs = neg_pairs / self.temperature\n n_per_p = c_f.to_dtype(a2.unsqueeze(0) == a1.unsqueeze(1), dtype=dtype)\n neg_pairs = neg_pairs * n_per_p\n neg_pairs[n_per_p == 0] = c_f.neg_inf(dtype)\n\n max_val = torch.max(pos_pairs, torch.max(neg_pairs, dim=1, keepdim=True)[0])\n numerator = torch.exp(pos_pairs - max_val).squeeze(1)\n denominator = torch.sum(torch.exp(neg_pairs - max_val), dim=1) + numerator\n log_exp = torch.log((numerator / denominator) + c_f.small_val(dtype))\n return {\n \"loss\": {\n \"losses\": -log_exp,\n \"indices\": (a1, p),\n \"reduction_type\": \"pos_pair\",\n }\n }\n return self.zero_losses()\n\n def get_default_distance(self):\n return CosineSimilarity()\n",
"import copy\n\nimport numpy as np\nimport torch\n\nfrom ..distances import CosineSimilarity\nfrom . import common_functions as c_f\n\n\nclass MatchFinder:\n def __init__(self, distance, threshold=None):\n self.distance = distance\n self.threshold = threshold\n\n def operate_on_emb(self, input_func, query_emb, ref_emb=None, *args, **kwargs):\n if ref_emb is None:\n ref_emb = query_emb\n return input_func(query_emb, ref_emb, *args, **kwargs)\n\n # for a batch of queries\n def get_matching_pairs(\n self, query_emb, ref_emb=None, threshold=None, return_tuples=False\n ):\n with torch.no_grad():\n threshold = threshold if self.threshold is None else self.threshold\n return self.operate_on_emb(\n self._get_matching_pairs, query_emb, ref_emb, threshold, return_tuples\n )\n\n def _get_matching_pairs(self, query_emb, ref_emb, threshold, return_tuples):\n mat = self.distance(query_emb, ref_emb)\n matches = mat >= threshold if self.distance.is_inverted else mat <= threshold\n matches = matches.cpu().numpy()\n if return_tuples:\n return list(zip(*np.where(matches)))\n return matches\n\n # where x and y are already matched pairs\n def is_match(self, x, y, threshold=None):\n threshold = threshold if self.threshold is None else self.threshold\n with torch.no_grad():\n dist = self.distance.pairwise_distance(x, y)\n output = (\n dist >= threshold if self.distance.is_inverted else dist <= threshold\n )\n if output.nelement() == 1:\n return output.detach().item()\n return output.cpu().numpy()\n\n\nclass FaissIndexer:\n def __init__(self, index=None, emb_dim=None):\n import faiss as faiss_module\n\n self.faiss_module = faiss_module\n self.index = index\n self.emb_dim = emb_dim\n\n def train_index(self, vectors):\n self.emb_dim = len(vectors[0])\n self.index = self.faiss_module.IndexFlatL2(self.emb_dim)\n self.index.add(vectors)\n\n def search_nn(self, query_batch, k):\n D, I = self.index.search(query_batch, k)\n return I, D\n\n\nclass InferenceModel:\n def __init__(\n self,\n trunk,\n embedder=None,\n match_finder=None,\n normalize_embeddings=True,\n indexer=None,\n batch_size=64,\n ):\n self.trunk = trunk\n self.embedder = c_f.Identity() if embedder is None else embedder\n self.match_finder = (\n MatchFinder(distance=CosineSimilarity(), threshold=0.9)\n if match_finder is None\n else match_finder\n )\n self.indexer = FaissIndexer() if indexer is None else indexer\n self.normalize_embeddings = normalize_embeddings\n self.batch_size = batch_size\n\n def train_indexer(self, tensors, emb_dim):\n if isinstance(tensors, list):\n tensors = torch.stack(tensors)\n\n embeddings = torch.Tensor(len(tensors), emb_dim)\n for i in range(0, len(tensors), self.batch_size):\n embeddings[i : i + self.batch_size] = self.get_embeddings(\n tensors[i : i + self.batch_size], None\n )[0]\n\n self.indexer.train_index(embeddings.cpu().numpy())\n\n def get_nearest_neighbors(self, query, k):\n if not self.indexer.index or not self.indexer.index.is_trained:\n raise RuntimeError(\"Index must be trained by running `train_indexer`\")\n\n query_emb, _ = self.get_embeddings(query, None)\n\n indices, distances = self.indexer.search_nn(query_emb.cpu().numpy(), k)\n return indices, distances\n\n def get_embeddings(self, query, ref):\n if isinstance(query, list):\n query = torch.stack(query)\n\n self.trunk.eval()\n self.embedder.eval()\n with torch.no_grad():\n query_emb = self.embedder(self.trunk(query))\n ref_emb = query_emb if ref is None else self.embedder(self.trunk(ref))\n if self.normalize_embeddings:\n query_emb = torch.nn.functional.normalize(query_emb, p=2, dim=1)\n ref_emb = torch.nn.functional.normalize(ref_emb, p=2, dim=1)\n return query_emb, ref_emb\n\n # for a batch of queries\n def get_matches(self, query, ref=None, threshold=None, return_tuples=False):\n query_emb, ref_emb = self.get_embeddings(query, ref)\n return self.match_finder.get_matching_pairs(\n query_emb, ref_emb, threshold, return_tuples\n )\n\n # where x and y are already matched pairs\n def is_match(self, x, y, threshold=None):\n x, y = self.get_embeddings(x, y)\n return self.match_finder.is_match(x, y, threshold)\n\n\nclass LogitGetter(torch.nn.Module):\n possible_layer_names = [\"fc\", \"proxies\", \"W\"]\n\n def __init__(\n self,\n classifier,\n layer_name=None,\n transpose=None,\n distance=None,\n copy_weights=True,\n ):\n super().__init__()\n self.copy_weights = copy_weights\n ### set layer weights ###\n if layer_name is not None:\n self.set_weights(getattr(classifier, layer_name))\n else:\n for x in self.possible_layer_names:\n layer = getattr(classifier, x, None)\n if layer is not None:\n self.set_weights(layer)\n break\n\n ### set distance measure ###\n self.distance = classifier.distance if distance is None else distance\n self.transpose = transpose\n\n def forward(self, embeddings):\n w = self.weights\n if self.transpose is True:\n w = w.t()\n elif self.transpose is None:\n if w.size(0) == embeddings.size(1):\n w = w.t()\n return self.distance(embeddings, w)\n\n def set_weights(self, layer):\n self.weights = copy.deepcopy(layer) if self.copy_weights else layer\n"
] |
[
[
"torch.exp",
"torch.max"
],
[
"torch.stack",
"torch.no_grad",
"numpy.where",
"torch.nn.functional.normalize"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mortbopet/NetCracker
|
[
"8b5c1dbe1780c111d1f6810d3ef13400f26f9cb0"
] |
[
"src/analysis/adjacencyAnalysis.py"
] |
[
"import argparse\nimport json\nimport re\nimport pprint\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom src.sbhelper import *\nfrom src.analysis.IOAnalysis import *\nfrom src.analysis.analysispass import *\nfrom src.logger import *\n\n\n# ============================== Analysis results ==============================\n\"\"\"type:\n {\n 'rowKeys' : [string],\n 'colKeys' : [string],\n 'matrix' : [[int]]\n }\n\"\"\"\nADJACENCY_ANALYSIS_RES = \"Adjacency analysis result\"\nADJACENCY_ANALYSIS_RES_ROWKEYS = 'rowkeys'\nADJACENCY_ANALYSIS_RES_COLKEYS = 'colkeys'\nADJACENCY_ANALYSIS_RES_MATRIX = 'matrix'\n\n# ==============================================================================\n\nADJACENCY_ANALYSIS_RESULT_FILE = \"adjacency_analysis\"\n\ndef plotAdjacencyMatrix(adjm, xkeys, ykeys):\n fig, ax = plt.subplots()\n im = ax.imshow(adjm)\n ax.set_xticks(np.arange(len(xkeys)))\n ax.set_yticks(np.arange(len(ykeys)))\n ax.set_xticklabels(xkeys)\n ax.set_yticklabels(ykeys)\n\n # Rotate the tick labels and set their alignment.\n plt.setp(ax.get_xticklabels(), rotation=90, ha=\"right\",\n rotation_mode=\"anchor\")\n plt.show()\n\n\ndef adjMatrixFromXYLists(vx, vy, adjListAccessFunctor):\n disregardedConns = set()\n disregardedConnsCnt = 0\n matrix = []\n for k in vy:\n innerMatrix = [0] * len(vx)\n for adjKey in vy[k]:\n try:\n i = list(vx.keys()).index(adjKey)\n innerMatrix[i] += 1\n except ValueError:\n # adjacent key was not considered for this analysis.\n # In the context of PJs, may happen if ie. we are doing adjacency\n # internally in the switchbox using forward PJs, but the given PJ\n # has a forward PJ externally to the switchbox (drives the global\n # routing network).\n disregardedConns.add(adjKey)\n disregardedConnsCnt += 1\n continue\n\n matrix.append(innerMatrix)\n\n logHeader(\"Disregarded %s connections to PJs:\" %\n (str(disregardedConnsCnt)), level=1)\n for c in disregardedConns:\n log(c, end=', ')\n log()\n\n return matrix\n\ndef singleToList(obj):\n return obj if type(obj) is list else [obj]\n\nclass AdjacencyAnalysis(AnalysisPass):\n def __init__(self, description, key):\n super().__init__(\n description=description,\n key=key,\n depends=[INOUT_ANALYSIS_RES],\n produces=[ADJACENCY_ANALYSIS_RES]\n )\n\n self.sb = None\n\n \"\"\"\n self.clusterFunction is a lambda for specifying the clustering specific\n to this adjacency analysis pass. Should be set by the implementing analysis.\n Args:\n pj ([PIPJunction]): PIP junction to cluster\n Args [optional]: All optional arguments provided as **kwarg dict\n isInput ([Boolean]): true if the PIP junction is an input to this switchbox\n \"\"\" \n self.clusterFunction = None\n\n def doSpecializationFiltering(self):\n raise Exception(\"Adjacency analysis specialization must implement this\")\n\n def dumpAdjacencyMatrix(self, adjm, xkeys, ykeys):\n fn = ADJACENCY_ANALYSIS_RESULT_FILE + \"_\" + self.key\n # Write column labels\n for k in xkeys:\n logResult(self.sb.name, fn, \"\\t\" + k, end = '')\n logResult(self.sb.name, fn)\n # Write rows\n for i, row in enumerate(adjm):\n logResult(self.sb.name, fn, ykeys[i], end = '')\n for v in row:\n logResult(self.sb.name, fn, '\\t' + str(v), end = '')\n logResult(self.sb.name, fn)\n logResult(self.sb.name, fn)\n\n\n def run(self, sb, doPlot=False):\n \"\"\" This analysis will generate the adjacency between inputs to the switchbox\n and outputs of the switchbox. Y labels are inputs, X labels are outputs\n \"\"\"\n self.sb = sb\n self.ins = sb.getAnalysisResult(INOUT_ANALYSIS_RES)[INOUT_ANALYSIS_INS]\n self.ints = sb.getAnalysisResult(INOUT_ANALYSIS_RES)[INOUT_ANALYSIS_INTS]\n self.outs = sb.getAnalysisResult(INOUT_ANALYSIS_RES)[INOUT_ANALYSIS_OUTS]\n self.bidirs = sb.getAnalysisResult(INOUT_ANALYSIS_RES)[INOUT_ANALYSIS_BIDIRS]\n self.bounces = sb.getAnalysisResult(INOUT_ANALYSIS_RES)[INOUT_ANALYSIS_BOUNCES]\n\n # Assert that the specialization has provided any required functions\n if self.clusterFunction == None:\n raise Exception(\"No cluster function set\")\n if self.filterFunction == None:\n raise Exception(\"No filter function set\")\n\n # Call specialization defined filtering/PJ list merging\n self.doSpecializationFiltering()\n\n def applyClustering(pjs, isInput = False):\n clustering = {}\n clustersize = {}\n # Applies the clustering function to the PJ itself and all of its forward\n # PJs\n\n clusteredPJsRev = {}\n for _pj in pjs:\n if self.filterFunction and self.filterFunction(_pj):\n continue\n\n clusteredPJs = singleToList(self.clusterFunction(_pj, isInput=isInput))\n \n clusteredForwardsLists = [singleToList(self.clusterFunction(\n fpj)) for fpj in _pj.forward_pjs]\n\n for clusteredPJ in clusteredPJs:\n if clusteredPJ not in clustering:\n clustering[clusteredPJ] = []\n\n if clusteredPJ not in clustersize:\n clustersize[clusteredPJ] = 0\n\n for clusteredForwards in clusteredForwardsLists:\n clustering[clusteredPJ] += clusteredForwards\n clustersize[clusteredPJ] += 1\n\n # Add to debug map\n if clusteredPJ not in clusteredPJsRev:\n clusteredPJsRev[clusteredPJ] = []\n clusteredPJsRev[clusteredPJ].append(_pj)\n\n return clustering, clustersize, clusteredPJsRev\n\n # Transform in's and out's based on the requested clustering\n ins, insclustersize, insDebugMap = applyClustering(self.ins, isInput=True)\n outs, outsclustersize, outsDebugMap = applyClustering(self.outs)\n\n for name, m in [(\"ins\", insDebugMap), (\"outs\", outsDebugMap)]:\n log(\"Group contents: \" + name)\n for k, v in m.items():\n log(str(k)+\": \", end = '')\n for pj in v:\n log(pj.name + \", \", end='')\n log()\n log()\n\n\n inkeys = ['[' + str(insclustersize[k] if k in insclustersize else 1) + ']-' + str(k) for k in list(ins.keys())]\n outkeys = ['[' + str(outsclustersize[k] if k in outsclustersize else 1) + ']-' + str(k) for k in list(outs.keys())]\n\n # Adjacency matrix of forward PJs\n adjmatrix = adjMatrixFromXYLists(outs, ins, lambda v: ins[v])\n\n self.dumpAdjacencyMatrix(adjmatrix, outkeys, inkeys)\n\n if doPlot:\n plotAdjacencyMatrix(adjmatrix, outkeys, inkeys)\n\n sb.results[ADJACENCY_ANALYSIS_RES] = {\n ADJACENCY_ANALYSIS_RES_ROWKEYS : inkeys,\n ADJACENCY_ANALYSIS_RES_COLKEYS : outkeys,\n ADJACENCY_ANALYSIS_RES_MATRIX : adjmatrix\n }\n"
] |
[
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MarvinStuede/copa-map
|
[
"f477d1254d99988b2d997e69316d4ffbec721fff",
"f477d1254d99988b2d997e69316d4ffbec721fff"
] |
[
"src/copa_map/model/model_utils.py",
"src/copa_map/plots/plot_domain_allocation.py"
] |
[
"\"\"\"Utilities for optimization of a model\"\"\"\nimport gpflow\nimport tensorflow as tf\nfrom tensorflow_probability import bijectors as tfb\nfrom termcolor import colored\n\n\ndef get_kernel_instance(kern, name):\n \"\"\"\n Returns requested kernel instance of a combined kernel\n\n Args:\n kern: Combined kernel\n name: Instance name\n\n Returns:\n kernel instance\n \"\"\"\n\n def search_submodules(kern_, name_):\n for sub_module in kern_.kernels:\n if sub_module.name == name_:\n return sub_module\n elif sub_module.name in [\"sum\", \"product\"]:\n result = search_submodules(sub_module, name_)\n if result is not None:\n return result\n return None\n\n instance = search_submodules(kern, name)\n if instance is None:\n print(colored(\"Kernel instance \\\"{}\\\" was not found\", \"red\").format(name))\n return instance\n\n\ndef bounded_hyperparameter(low, high, parameter):\n \"\"\"\n To constrain hyper-parameters\n\n Args:\n low: Minimum value\n high: Maximum value\n parameter: Initial value\n\n Returns:\n Bounded hyper-parameter\n \"\"\"\n # Compute Y = g(X; shift, scale) = scale * X + shift.\n affine = tfb.AffineScalar(shift=tf.cast(low, tf.float64),\n scale=tf.cast(high - low, tf.float64))\n # Transformation-bijector combining affine and sigmoid\n logistic = tfb.Chain([affine, tfb.Sigmoid()])\n # Apply the transformation to the parameter\n param = gpflow.Parameter(parameter, transform=logistic, dtype=tf.float64)\n return param\n",
"\"\"\"Plot the domain numbers\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass PlotDomains:\n \"\"\"Class for plotting local GP information\"\"\"\n def __init__(self, domain_sz, occ_map, ll, lr, ul, ur):\n \"\"\"Constructor\n\n Args:\n domain_sz: Edge length of domain in meters\n occ_map: Occupancy grid map to represent the environment\n ll: Lower left coordinates\n ur: Upper right coordinates\n lr: Lower right coordinates\n ul: Upper left coordinates\n\n \"\"\"\n self.domain_sz = domain_sz\n self.occ_map = occ_map\n self.ll = ll\n self.lr = lr\n self.ul = ul\n self.ur = ur\n\n def _get_rectangle(self, x1, x2, y1, y2):\n \"\"\"Returns: Corner coordinates of a local GP\"\"\"\n return np.array([[x1, y1], [x1, y2], [x2, y2], [x2, y1], [x1, y1]])\n\n def get_rec_center(self, rect):\n \"\"\"Returns: Center coordinate of a local GP\"\"\"\n p1 = rect[0]\n p2 = rect[2]\n return np.array([(p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2])\n\n def plot_map(self):\n \"\"\"Plot the map\"\"\"\n # Plot map\n fig, axs = plt.subplots(1, 1, figsize=(8, 8))\n self.occ_map.plot(fig.axes[0], transparent=False, zorder=1)\n\n # Plot boundary around the entire map\n # bx1, by1 = self.occ_map.orig[:2]\n # bx2, by2 = self.occ_map.orig[:2] + np.array([self.occ_map.width, self.occ_map.height])\n # rect = self._get_rectangle(bx1, bx2, by1, by2)\n # fig.axes[0].plot(rect[:, 0], rect[:, 1], 'g', zorder=2)\n ll = self.occ_map.tf_from(np.array([0, 0]))\n lr = self.occ_map.tf_from(np.array([self.occ_map.width, 0]))\n ul = self.occ_map.tf_from(np.array([0, self.occ_map.height]))\n ur = self.occ_map.tf_from(np.array([self.occ_map.width, self.occ_map.height]))\n xmin = np.min(np.array([ll[0], lr[0], ul[0], ur[0]]))\n xmax = np.max(np.array([ll[0], lr[0], ul[0], ur[0]]))\n ymin = np.min(np.array([ll[1], lr[1], ul[1], ur[1]]))\n ymax = np.max(np.array([ll[1], lr[1], ul[1], ur[1]]))\n fig.axes[0].set_xlim(np.array([xmin, xmax]))\n fig.axes[0].set_ylim(np.array([ymin, ymax]))\n plt.pause(0.1)\n return fig\n\n def get_local_domain(self, number):\n \"\"\"Returns: Lower left and upper right coordinate\"\"\"\n ll_rec = self.ll[number]\n lr_rec = self.lr[number]\n ul_rec = self.ul[number]\n ur_rec = self.ur[number]\n return np.array([ll_rec, ul_rec, ur_rec, lr_rec, ll_rec])\n\n def plot_local_domains(self):\n \"\"\"Plot all local domains\"\"\"\n self.fig = self.plot_map()\n\n # Plot boundaries of the local domains\n for rec in range(self.ll.shape[0]):\n rect = self.get_local_domain(rec)\n self.fig.axes[0].plot(rect[:, 0], rect[:, 1], 'b', zorder=2)\n\n x, y = self.get_rec_center(rect)\n self.fig.axes[0].text(x, y, str(rec), color='b', fontsize=20,\n verticalalignment='center', horizontalalignment='center', zorder=3)\n plt.pause(0.1)\n\n def set_status(self, number, status):\n \"\"\"To change color and information texts while optimization\"\"\"\n if status == 0:\n color = \"y\"\n text = \"Optimize...\"\n elif status == 1:\n color = \"g\"\n text = \"Optimized\"\n else:\n raise ValueError\n\n rect = self.get_local_domain(number)\n pos = self.get_rec_center(rect)\n\n # Change color of the number\n self.fig.axes[0].text(pos[0], pos[1], str(number), color=color, fontsize=20, verticalalignment='center',\n horizontalalignment='center', zorder=4)\n\n # Replace information text\n pos = pos + np.array([0, -self.domain_sz / 5])\n for old_text in self.fig.axes[0].texts:\n if np.array_equal(np.array(old_text.get_position()), pos):\n old_text.remove()\n self.fig.axes[0].text(pos[0], pos[1], text, color=color, fontsize=10, verticalalignment='center',\n horizontalalignment='center', zorder=4)\n plt.pause(0.1)\n\n\n# if __name__ == \"__main__\":\n# # Edge length of local domains in m\n# domain_sz = 20\n# project_path = \"data_io\"\n#\n# # Read data\n# if project_path == \"data_io\":\n# occ_map = mongo_utils.get_stored_occ_map()\n# elif project_path == \"data\":\n# r = dh.DataSim()\n# r.read_occ_map(Path(__file__).parents[1] / \"data/simu_new/Map_HG.yaml\")\n# occ_map = r.occ_map\n# else:\n# raise ValueError\n#\n# # # Divide the map into local GP\n# # gp = PeopleGP.PeopleGP(occ_map=occ_map)\n# # gp.domain_sz = domain_sz\n# # gp.divide_map()\n#\n# # Create instance\n# local_domains = PlotDomains(domain_sz=domain_sz, occ_map=occ_map, ll=gp.ll, ur=gp.ur)\n# local_domains.plot_local_domains()\n#\n# # test animation:\n# # for i in range(5):\n# # local_domains.set_status(i, 0)\n# # plt.pause(1)\n# # local_domains.set_status(i, 1)\n#\n# plt.show()\n"
] |
[
[
"tensorflow.cast"
],
[
"numpy.array",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.pause"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"1.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
msdrigg/RayTracing
|
[
"700ce020c6faa93757100edae4543a1a59c4f3c8",
"700ce020c6faa93757100edae4543a1a59c4f3c8"
] |
[
"atmospheres/base.py",
"magnetic_fields/implementations.py"
] |
[
"from abc import ABC, abstractmethod\nfrom typing import Optional, Tuple\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom numpy.typing import ArrayLike\nfrom scipy.spatial.transform.rotation import Rotation\n\nfrom utilities import Vector\nfrom utilities import Constants\n\n\nclass BaseAtmosphere(ABC):\n def visualize(\n self, initial_point: np.ndarray,\n final_point: np.ndarray,\n fig: plt.Figure = None,\n ax: plt.Axes = None,\n show: bool = False, **kwargs\n ) -> Optional[Tuple[plt.Figure, plt.Axes]]:\n \"\"\"\n Given an initial and final point (and some formatting parameters), visualize the\n atmosphere on a matplotlib graph\n :param initial_point : np.ndarray, shape (3, )\n 3-vec corresponding to the starting coordinate of the path in\n cartesian coordinates. Used to determine the interval in which\n to calculate the atmosphere\n :param final_point : np.ndarray, shape (3, )\n 3-vec corresponding to the starting coordinate of the path in\n cartesian coordinates. Used to determine the interval in which\n to calculate the atmosphere\n :param fig : Figure, optional\n If fig and ax are both provided,\n display the atmosphere colormap on top of the old axes\n otherwise, create a new figure and axes to work with\n :param ax : Axes, optional\n If fig and ax are both provided,\n display the atmosphere colormap on top of the old axes\n otherwise, create a new figure and axes to work with\n :param show : boolean, optional\n If show is true, display the plotted atmosphere immediately and return nothing.\n Otherwise, don't display and instead return the computed figure and axes\n :param kwargs : dict, optional\n Any additional kwargs are passed to the imshow function\n :returns : (Figure, Axes), optional\n If show is False, return the computed figure and axes, otherwise return nothing.\n \"\"\"\n total_angle = Vector.angle_between(initial_point, final_point)\n normal_vec = Vector.unit_vector(np.cross(initial_point, final_point))\n point_number = 500\n\n if ax is None or fig is None:\n fig, ax = plt.subplots(1, 1, figsize=(6, 4.5))\n radii = np.linspace(Constants.EARTH_RADIUS, Constants.EARTH_RADIUS + 400E3, point_number)\n alpha = np.linspace(0, total_angle, point_number)\n r_1 = Rotation.from_rotvec(normal_vec * alpha.reshape(-1, 1))\n v_1 = r_1.apply(initial_point)\n v_1 = Vector.cartesian_to_spherical(v_1)\n frequency_grid = np.zeros((point_number, point_number))\n for i in range(point_number):\n plotted_vecs = np.repeat(v_1[i].reshape(-1, 1), point_number, axis=1).T\n plotted_vecs[:, 0] = radii\n frequency_grid[:, i] = self.plasma_frequency(\n Vector.spherical_to_cartesian(plotted_vecs)\n )/1E6\n image = ax.imshow(frequency_grid, cmap='gist_rainbow', interpolation='bilinear', origin='lower',\n alpha=1, aspect='auto', extent=[0, total_angle * Constants.EARTH_RADIUS / 1000, 0, 400],\n **kwargs)\n ax.yaxis.set_ticks_position('both')\n color_bar = fig.colorbar(image, ax=ax)\n color_bar.set_label(\"Plasma Frequency (MHz)\")\n\n if show:\n ax.set_title(\"Chapman Layers Atmosphere\")\n plt.show()\n else:\n return fig, ax\n\n gradient = None\n\n @abstractmethod\n def plasma_frequency(self, coordinate: ArrayLike) -> ArrayLike:\n \"\"\"\n This function returns the plasma frequency given a position in space\n :param coordinate : np.ndarray, shape (N, 3) or (3, )\n 3-vec or array of 3-vecs in a cartesian coordinate system\n :returns The plasma frequency corresponding to the input position vector. Its shape should match\n the incoming position vector's shape. If position is of shape (N, 3), the output should be\n of shape (N, ). If the position is of shape (3, ), the output should be a scalar.\n \"\"\"\n raise NotImplementedError(\"Inheriting classes must override the plasma_frequency method\")\n",
"import numpy as np\n\nfrom utilities.Constants import B_FIELD, EARTH_RADIUS\nfrom utilities.Vector import cartesian_to_spherical, unit_radius, unit_theta, unit_vector, spherical_to_cartesian\nfrom magnetic_fields import BaseField\n\n\nclass DipoleField(BaseField):\n \"\"\"\n Implementation of BaseField that follows the dipole model of earth's magnetic field\n \"\"\"\n def __init__(self):\n self.b_max = B_FIELD\n self.re3 = np.power(EARTH_RADIUS, 3) # E_Radius^3\n\n def field_vec(self, position):\n position = cartesian_to_spherical(position).reshape(-1, 3)\n\n # radii cubed is 1/r^3 for all r\n radii_cubed = np.power(position[:, 0], -3)\n cos_thetas = np.cos(position[:, 1])\n b_vec = -2*self.b_max*radii_cubed.reshape(-1, 1)*self.re3*cos_thetas.reshape(-1, 1)*unit_radius(position) - \\\n self.b_max*self.re3*radii_cubed.reshape(-1, 1)*np.sin(position[:, 1]).reshape(-1, 1)*unit_theta(position)\n b_vec = unit_vector(b_vec)\n\n if len(b_vec) == 1:\n return b_vec[0]\n else:\n return b_vec\n\n def field_mag(self, position):\n position = cartesian_to_spherical(position).reshape(-1, 3)\n # radii cubed is 1/r^3 for all r\n radii_cubed = np.power(position[:, 0], -3)\n cos_thetas = np.cos(position[:, 1])\n b_mags = self.b_max * self.re3 * radii_cubed * np.sqrt(1 + 3 * np.square(cos_thetas))\n if len(b_mags) == 1:\n return b_mags[0]\n else:\n return b_mags\n\n\nclass ZeroField(BaseField):\n \"\"\"\n Implementation of Base field that always returns 0\n \"\"\"\n def field_vec(self, position):\n # Field vector is normalized, so we return 1, 0, 0 as normal vector\n return spherical_to_cartesian(np.array([1, 0, 0]))\n\n def field_mag(self, position):\n return np.repeat(0, len(position))\n\n def gyro_frequency(self, position):\n return np.repeat(0, len(position))\n"
] |
[
[
"numpy.linspace",
"matplotlib.pyplot.subplots",
"numpy.cross",
"matplotlib.pyplot.show",
"numpy.zeros"
],
[
"numpy.square",
"numpy.power",
"numpy.cos",
"numpy.sin",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
valohai/valohai-sagemaker-adapter
|
[
"c945a691c7dfef136f66c19ae79a67d981a64cfa"
] |
[
"examples/jupyter-example/train.py"
] |
[
"import torch\nimport imblearn\nimport os, sys\n\n\ndef list_files(startpath):\n for root, dirs, files in os.walk(startpath):\n level = root.replace(startpath, '').count(os.sep)\n indent = ' ' * 4 * (level)\n print('{}{}/'.format(indent, os.path.basename(root)))\n subindent = ' ' * 4 * (level + 1)\n for f in files:\n fp = os.path.join(root, f)\n print('{}{}:{}'.format(subindent, os.path.getsize(fp), f))\n\nprint(\"Hello from valohai\")\nprint(torch.cuda.is_available())\nprint(\"bye\")\nprint(\"other log again...\")\n\nprint(\"size\", os.path.getsize(\"/valohai/inputs/training/train.csv\"))\n\nwith open(\"/valohai/outputs/somefile_output_example.txt\", \"w\") as f:\n f.write(\"hey hey\\n\")\n"
] |
[
[
"torch.cuda.is_available"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
OOXXXXOO/UnitNet
|
[
"304c58a7ac6e4d78c8bf2ef528f817eed3ff7c7a"
] |
[
"Src/Model/BackBone/efficientnet/model.py"
] |
[
"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom Src.Nets.BackBone.efficientnet.utils import (\n relu_fn,\n round_filters,\n round_repeats,\n drop_connect,\n get_same_padding_conv2d,\n get_model_params,\n efficientnet_params,\n load_pretrained_weights,\n)\n\nclass MBConvBlock(nn.Module):\n \"\"\"\n Mobile Inverted Residual Bottleneck Block\n\n Args:\n block_args (namedtuple): BlockArgs, see above\n global_params (namedtuple): GlobalParam, see above\n\n Attributes:\n has_se (bool): Whether the block contains a Squeeze and Excitation layer.\n \"\"\"\n\n def __init__(self, block_args, global_params):\n super().__init__()\n self._block_args = block_args\n self._bn_mom = 1 - global_params.batch_norm_momentum\n self._bn_eps = global_params.batch_norm_epsilon\n self.has_se = (self._block_args.se_ratio is not None) and (0 < self._block_args.se_ratio <= 1)\n self.id_skip = block_args.id_skip # skip connection and drop connect\n\n # Get static or dynamic convolution depending on image size\n Conv2d = get_same_padding_conv2d(image_size=global_params.image_size)\n\n # Expansion phase\n inp = self._block_args.input_filters # number of input channels\n oup = self._block_args.input_filters * self._block_args.expand_ratio # number of output channels\n if self._block_args.expand_ratio != 1:\n self._expand_conv = Conv2d(in_channels=inp, out_channels=oup, kernel_size=1, bias=False)\n self._bn0 = nn.BatchNorm2d(num_features=oup, momentum=self._bn_mom, eps=self._bn_eps)\n\n # Depthwise convolution phase\n k = self._block_args.kernel_size\n s = self._block_args.stride\n self._depthwise_conv = Conv2d(\n in_channels=oup, out_channels=oup, groups=oup, # groups makes it depthwise\n kernel_size=k, stride=s, bias=False)\n self._bn1 = nn.BatchNorm2d(num_features=oup, momentum=self._bn_mom, eps=self._bn_eps)\n\n # Squeeze and Excitation layer, if desired\n if self.has_se:\n num_squeezed_channels = max(1, int(self._block_args.input_filters * self._block_args.se_ratio))\n self._se_reduce = Conv2d(in_channels=oup, out_channels=num_squeezed_channels, kernel_size=1)\n self._se_expand = Conv2d(in_channels=num_squeezed_channels, out_channels=oup, kernel_size=1)\n\n # Output phase\n final_oup = self._block_args.output_filters\n self._project_conv = Conv2d(in_channels=oup, out_channels=final_oup, kernel_size=1, bias=False)\n self._bn2 = nn.BatchNorm2d(num_features=final_oup, momentum=self._bn_mom, eps=self._bn_eps)\n\n def forward(self, inputs, drop_connect_rate=None):\n \"\"\"\n :param inputs: input tensor\n :param drop_connect_rate: drop connect rate (float, between 0 and 1)\n :return: output of block\n \"\"\"\n\n # Expansion and Depthwise Convolution\n x = inputs\n if self._block_args.expand_ratio != 1:\n x = relu_fn(self._bn0(self._expand_conv(inputs)))\n x = relu_fn(self._bn1(self._depthwise_conv(x)))\n\n # Squeeze and Excitation\n if self.has_se:\n x_squeezed = F.adaptive_avg_pool2d(x, 1)\n x_squeezed = self._se_expand(relu_fn(self._se_reduce(x_squeezed)))\n x = torch.sigmoid(x_squeezed) * x\n\n x = self._bn2(self._project_conv(x))\n\n # Skip connection and drop connect\n input_filters, output_filters = self._block_args.input_filters, self._block_args.output_filters\n if self.id_skip and self._block_args.stride == 1 and input_filters == output_filters:\n if drop_connect_rate:\n x = drop_connect(x, p=drop_connect_rate, training=self.training)\n x = x + inputs # skip connection\n return x\n\n\nclass EfficientNet(nn.Module):\n \"\"\"\n An EfficientNet model. Most easily loaded with the .from_name or .from_pretrained methods\n\n Args:\n blocks_args (list): A list of BlockArgs to construct blocks\n global_params (namedtuple): A set of GlobalParams shared between blocks\n\n Example:\n model = EfficientNet.from_pretrained('efficientnet-b0')\n\n \"\"\"\n\n def __init__(self, blocks_args=None, global_params=None):\n super().__init__()\n assert isinstance(blocks_args, list), 'blocks_args should be a list'\n assert len(blocks_args) > 0, 'block args must be greater than 0'\n self._global_params = global_params\n self._blocks_args = blocks_args\n\n # Get static or dynamic convolution depending on image size\n Conv2d = get_same_padding_conv2d(image_size=global_params.image_size)\n\n # Batch norm parameters\n bn_mom = 1 - self._global_params.batch_norm_momentum\n bn_eps = self._global_params.batch_norm_epsilon\n\n # Stem\n in_channels = 3 # rgb\n out_channels = round_filters(32, self._global_params) # number of output channels\n self._conv_stem = Conv2d(in_channels, out_channels, kernel_size=3, stride=2, bias=False)\n self._bn0 = nn.BatchNorm2d(num_features=out_channels, momentum=bn_mom, eps=bn_eps)\n\n # Build blocks\n self._blocks = nn.ModuleList([])\n for block_args in self._blocks_args:\n\n # Update block input and output filters based on depth multiplier.\n block_args = block_args._replace(\n input_filters=round_filters(block_args.input_filters, self._global_params),\n output_filters=round_filters(block_args.output_filters, self._global_params),\n num_repeat=round_repeats(block_args.num_repeat, self._global_params)\n )\n\n # The first block needs to take care of stride and filter size increase.\n self._blocks.append(MBConvBlock(block_args, self._global_params))\n if block_args.num_repeat > 1:\n block_args = block_args._replace(input_filters=block_args.output_filters, stride=1)\n for _ in range(block_args.num_repeat - 1):\n self._blocks.append(MBConvBlock(block_args, self._global_params))\n\n # Head\n in_channels = block_args.output_filters # output of final block\n out_channels = round_filters(1280, self._global_params)\n self._conv_head = Conv2d(in_channels, out_channels, kernel_size=1, bias=False)\n self._bn1 = nn.BatchNorm2d(num_features=out_channels, momentum=bn_mom, eps=bn_eps)\n\n # Final linear layer\n self._dropout = self._global_params.dropout_rate\n self._fc = nn.Linear(out_channels, self._global_params.num_classes)\n\n def extract_features(self, inputs):\n \"\"\" Returns output of the final convolution layer \"\"\"\n\n # Stem\n x = relu_fn(self._bn0(self._conv_stem(inputs)))\n\n # Blocks\n for idx, block in enumerate(self._blocks):\n drop_connect_rate = self._global_params.drop_connect_rate\n if drop_connect_rate:\n drop_connect_rate *= float(idx) / len(self._blocks)\n x = block(x, drop_connect_rate=drop_connect_rate)\n\n # Head\n x = relu_fn(self._bn1(self._conv_head(x)))\n\n return x\n\n def forward(self, inputs):\n \"\"\" Calls extract_features to extract features, applies final linear layer, and returns logits. \"\"\"\n\n # Convolution layers\n x = self.extract_features(inputs)\n\n # Pooling and final linear layer\n x = F.adaptive_avg_pool2d(x, 1).squeeze(-1).squeeze(-1)\n if self._dropout:\n x = F.dropout(x, p=self._dropout, training=self.training)\n x = self._fc(x)\n return x\n\n @classmethod\n def from_name(cls, model_name, override_params=None):\n cls._check_model_name_is_valid(model_name)\n blocks_args, global_params = get_model_params(model_name, override_params)\n return EfficientNet(blocks_args, global_params)\n\n @classmethod\n def from_pretrained(cls, model_name, num_classes=1000):\n print('start with :',model_name)\n model = EfficientNet.from_name(model_name, override_params={'num_classes': num_classes})\n load_pretrained_weights(model, model_name, load_fc=(num_classes == 1000))\n return model\n\n @classmethod\n def get_image_size(cls, model_name):\n cls._check_model_name_is_valid(model_name)\n _, _, res, _ = efficientnet_params(model_name)\n return res\n\n @classmethod\n def _check_model_name_is_valid(cls, model_name, also_need_pretrained_weights=False):\n \"\"\" Validates model name. None that pretrained weights are only available for\n the first four models (efficientnet-b{i} for i in 0,1,2,3) at the moment. \"\"\"\n num_models = 4 if also_need_pretrained_weights else 8\n valid_models = ['efficientnet_b'+str(i) for i in range(num_models)]\n if model_name.replace('-','_') not in valid_models:\n raise ValueError('model_name should be one of: ' + ', '.join(valid_models))\n\n\n\n"
] |
[
[
"torch.sigmoid",
"torch.nn.functional.dropout",
"torch.nn.ModuleList",
"torch.nn.functional.adaptive_avg_pool2d",
"torch.nn.Linear",
"torch.nn.BatchNorm2d"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jlosey513/Binomial
|
[
"64dbe493132d27b01342911a079d09d59cbc6f6b"
] |
[
"binomial_option_model.py"
] |
[
"import numpy as np\n\n\ndef binomial_model(N, S0, u, r, K):\n \"\"\"\n N = number of binomial iterations\n S0 = initial stock price\n u = factor change of upstate\n r = risk free interest rate per annum\n K = strike price\n \"\"\"\n d = 1 / u\n p = (1 + r - d) / (u - d)\n q = 1 - p\n\n # make stock price tree\n stock = np.zeros([N + 1, N + 1])\n for i in range(N + 1):\n for j in range(i + 1):\n stock[j, i] = S0 * (u ** (i - j)) * (d ** j)\n\n # Generate option prices recursively\n option = np.zeros([N + 1, N + 1])\n option[:, N] = np.maximum(np.zeros(N + 1), (stock[:, N] - K))\n for i in range(N - 1, -1, -1):\n for j in range(0, i + 1):\n option[j, i] = (\n 1 / (1 + r) * (p * option[j, i + 1] + q * option[j + 1, i + 1])\n )\n return option\n\n\nif __name__ == \"__main__\":\n print(\"Calculating example option price:\")\n op_price = binomial_model(5, 4, 2, 0.25, 8)\n print(op_price)\n"
] |
[
[
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
oi-analytics/argentina-transport
|
[
"f1583b077844e6b20b2c81144dec0872c88bdb80",
"f1583b077844e6b20b2c81144dec0872c88bdb80",
"f1583b077844e6b20b2c81144dec0872c88bdb80",
"f1583b077844e6b20b2c81144dec0872c88bdb80"
] |
[
"src/atra/plot/air_network_flows.py",
"src/atra/preprocess/convert_hazard_data.py",
"src/atra/plot/od_commodities_charts.py",
"src/atra/preprocess/road_network_creation.py"
] |
[
"\"\"\"air network flows map\n\"\"\"\nimport os\nimport sys\nfrom collections import OrderedDict\n\nimport pandas as pd\nimport geopandas as gpd\nimport cartopy.crs as ccrs\nimport cartopy.io.shapereader as shpreader\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom shapely.geometry import LineString\nfrom atra.utils import *\n\n\ndef main():\n config = load_config()\n data_path = config['paths']['data']\n air_edge_file_path = os.path.join(\n config['paths']['data'], 'network', 'air_edges.shp')\n air_flow_file_path = os.path.join(config['paths']['output'], 'flow_mapping_combined',\n 'air_passenger.csv')\n\n\n mode_file = gpd.read_file(air_edge_file_path,encoding='utf-8')\n flow_file = pd.read_csv(air_flow_file_path,encoding='utf-8-sig')\n mode_file = pd.merge(mode_file,flow_file,how='left', on=['edge_id']).fillna(0)\n\n mode_file['passengers_2016'] = 1.0*mode_file['passengers_2016']/365\n color = '#252525'\n color_by_type = {'air Line': color}\n\n plot_sets = [\n {\n 'file_tag': 'passenger',\n 'legend_label': \"AADF (passenger/day)\",\n 'divisor': 1,\n 'columns': ['passengers_2016'],\n 'title_cols': ['Total passengers'],\n 'significance':0\n },\n ]\n for plot_set in plot_sets:\n for c in range(len(plot_set['columns'])):\n # basemap\n proj_lat_lon = ccrs.PlateCarree()\n ax = get_axes()\n plot_basemap(ax, data_path)\n scale_bar(ax, location=(0.8, 0.05))\n plot_basemap_labels(ax, data_path, include_regions=True)\n\n column = plot_set['columns'][c]\n weights = [\n record[column]\n for iter_, record in mode_file.iterrows()\n ]\n max_weight = max(weights)\n width_by_range = generate_weight_bins(weights, n_steps=7, width_step=0.02)\n\n geoms_by_range = {}\n for value_range in width_by_range:\n geoms_by_range[value_range] = []\n\n for iter_, record in mode_file.iterrows():\n val = record[column]\n geom = record.geometry\n for nmin, nmax in geoms_by_range:\n if nmin <= val and val < nmax:\n geoms_by_range[(nmin, nmax)].append(geom)\n\n # plot\n for range_, width in width_by_range.items():\n ax.add_geometries(\n [geom.buffer(width) for geom in geoms_by_range[range_]],\n crs=proj_lat_lon,\n edgecolor='none',\n facecolor=color,\n zorder=2)\n\n x_l = -58.4\n x_r = x_l + 0.4\n base_y = -45.1\n y_step = 0.8\n y_text_nudge = 0.2\n x_text_nudge = 0.2\n\n ax.text(\n x_l,\n base_y + y_step - y_text_nudge,\n plot_set['legend_label'],\n horizontalalignment='left',\n transform=proj_lat_lon,\n size=10)\n\n divisor = plot_set['divisor']\n significance_ndigits = plot_set['significance']\n max_sig = []\n for (i, ((nmin, nmax), line_style)) in enumerate(width_by_range.items()):\n if round(nmin/divisor, significance_ndigits) < round(nmax/divisor, significance_ndigits):\n max_sig.append(significance_ndigits)\n elif round(nmin/divisor, significance_ndigits+1) < round(nmax/divisor, significance_ndigits+1):\n max_sig.append(significance_ndigits+1)\n elif round(nmin/divisor, significance_ndigits+2) < round(nmax/divisor, significance_ndigits+2):\n max_sig.append(significance_ndigits+2)\n else:\n max_sig.append(significance_ndigits+3)\n\n significance_ndigits = max(max_sig)\n\n for (i, ((nmin, nmax), width)) in enumerate(width_by_range.items()):\n y = base_y - (i*y_step)\n line = LineString([(x_l, y), (x_r, y)])\n ax.add_geometries(\n [line.buffer(width)],\n crs=proj_lat_lon,\n linewidth=0,\n edgecolor=color,\n facecolor=color,\n zorder=2)\n if nmin == max_weight:\n value_template = '>{:.' + str(significance_ndigits) + 'f}'\n label = value_template.format(\n round(max_weight/divisor, significance_ndigits))\n else:\n value_template = '{:.' + str(significance_ndigits) + \\\n 'f}-{:.' + str(significance_ndigits) + 'f}'\n label = value_template.format(\n round(nmin/divisor, significance_ndigits), round(nmax/divisor, significance_ndigits))\n ax.text(\n x_r + x_text_nudge,\n y - y_text_nudge,\n label,\n horizontalalignment='left',\n transform=proj_lat_lon,\n size=10)\n\n plt.title('AADF - {}'.format(plot_set['title_cols'][c]), fontsize=10)\n output_file = os.path.join(config['paths']['figures'],\n 'air_flow-map-{}-max-scale.png'.format(column))\n save_fig(output_file)\n plt.close()\n\n\nif __name__ == '__main__':\n main()\n",
"\"\"\"Pre-process hazard data\n\nPurpose\n-------\n\nConvert GeoTiff raster hazard datasets to shapefiles based on masking and selecting values from\n - Single-band raster files\n\nInput data requirements\n-----------------------\n\n1. Correct paths to all hazard datasets\n2. Single-band GeoTiff hazard raster files with:\n - values - between 0 and 1000\n - raster grid geometry\n - projection systems: Default assumed = EPSG:4326\n\nResults\n-------\n\n1. Shapefiles whose names show the hazard models and their selected range of values\n - ID - equal to 1\n - geometry - Shapely Polygon outline of selected hazard\n\n\"\"\"\n\nimport os\nimport subprocess\nimport json\nimport sys\n\n\nfrom atra.utils import load_config\n\nimport fiona\nimport fiona.crs\nimport rasterio\nimport numpy as np\nimport pandas as pd\n\ndef glofris_data_details(file_name,root_dir):\n\t\"\"\"Read names of GLOFRIS files and create attributes\n\n Parameters\n - file_name - String name of GeoTff file\n - root_dir - String path to directory of file\n\n Outputs\n df - Pandas DataFrame written to csv file with columns:\n - file_name - String\n - hazard_type - String\n - year - Integer: 2016 or 2030\n - climate_scenario - String: RCP4.5 or RCP8.5 or none\n - probability - Float: 1/(return period)\n - banded - Boolean: True or False\n - bands - Integer\n \"\"\"\n\tfor root, dirs, files in os.walk(root_dir):\n\t\tfor file in files:\n\t\t\tif file.endswith(\".tif\") or file.endswith(\".tiff\"):\n\t\t\t\tfname = file.split('.tif')\n\t\t\t\tfname = fname[0]\n\t\t\t\tprint (fname)\n\t\t\t\tif '2030' in fname:\n\t\t\t\t\tyear = 2030\n\t\t\t\telse:\n\t\t\t\t\tyear = 2016\n\n\t\t\t\tif 'rcp4p5' in fname:\n\t\t\t\t\tsc = 'rcp 4.5'\n\t\t\t\telif 'rcp8p5' in fname:\n\t\t\t\t\tsc = 'rcp 8.5'\n\t\t\t\telse:\n\t\t\t\t\tsc = 'none'\n\n\t\t\t\tf_all.append((fname,'flooding',year,sc,1.0/float(fname[-5:]),'FALSE','none'))\n\n\tdf = pd.DataFrame(f_all,columns = ['file_name',\t'hazard_type',\t'year',\t'climate_scenario',\t'probability','banded',\t'bands'])\n\tdf.to_csv(os.path.join(root_dir,'glofris_files.csv'),index = False)\n\n\n\ndef raster_rewrite(in_raster,out_raster,nodata):\n\t\"\"\"Rewrite a raster to reproject and change no data value\n\n Parameters\n - in_raster - String name of input GeoTff file path\n - out_raster - String name of output GeoTff file path\n - nodata - Float value of data that is treated as no data\n\n Outputs\n Reproject and replace raster with nodata = -1\n \"\"\"\n\twith rasterio.open(in_raster) as dataset:\n\t\tdata_array = dataset.read()\n\t\tdata_array[np.where(np.isnan(data_array))] = nodata\n\n\t\twith rasterio.open(out_raster, 'w', driver='GTIff',\n\t\t\t\t\theight=data_array.shape[1], # numpy of rows\n\t\t\t\t\twidth=data_array.shape[2], # number of columns\n\t\t\t\t\tcount=dataset.count, # number of bands\n\t\t\t\t\tdtype=data_array.dtype, # this must match the dtype of our array\n\t\t\t\t\tcrs=dataset.crs,\n\t\t\t\t\ttransform=dataset.transform) as out_data:\n\t\t\tout_data.write(data_array) # optional second parameter is the band number to write to\n\t\t\tout_data.nodata = -1 # set the raster's nodata value\n\n\n\tos.remove(in_raster)\n\tos.rename(out_raster,in_raster)\n\n\ndef raster_projections_and_databands(file_path):\n\t\"\"\"Extract projection, data bands numbers and valuees from raster\n\n Parameters\n - file_path - String name of input GeoTff file path\n\n Outputs\n - counts - Number of bans in raster\n - crs - Projection system of raster\n - data_vals - Numpy array of raster values\n \"\"\"\n\twith rasterio.open(file_path) as dataset:\n\t\tcounts = dataset.count\n\t\tif dataset.crs:\n\t\t\tcrs = dataset.crs.to_string()\n\t\telse:\n\t\t\tcrs = 'invalid/unknown'\n\t\t# data_array = dataset.read()\n\t\t# if dataset.count > 1:\n\t\t# \tdata_list = []\n\t\t# \tfor i in range(0,dataset.count):\n\t\t# \t\tdata_list.append(data_array[i].reshape(dataset.height*dataset.width).tolist())\n\t\t# \tdata_vals = list(set(list(zip(*data_list))))\n\t\t# else:\n\t\t# \tdata_vals = list(set(data_array.reshape(dataset.count*dataset.height*dataset.width).tolist()))\n\t\t# \tif all(isinstance(x, int) for x in data_vals) is False:\n\t\t# \t\tdata_vals = []\n\n\treturn counts,crs\n\ndef convert_geotiff_to_vector_with_threshold(from_threshold,to_threshold, infile, infile_epsg,tmpfile_1, tmpfile_2, outfile):\n\t\"\"\"Convert GeoTiff raster file to Shapefile with geometries based on raster threshold ranges\n\n Parameters\n - from_threshold - Float value of lower bound of GeoTiff threshold value to be selected\n - to_threshold - Float value of upper bound of GeoTiff threshold value to be selected\n - infile - String name of input GeoTff file path\n - infile_epsg - Integer value of EPSG Projection number of raster\n - tmpfile_1 - Stirng name of tmp file 1\n - tmpfile_2 - Stirng name of tmp file 2\n - outfile - Stirng name of output shapefile\n\n Outputs\n Shapefile with Polygon geometries of rasters based on raster threshold ranges\n \"\"\"\n\targs = [\n\t\t\"gdal_calc.py\",\n\t\t'-A', infile,\n\t\t'--outfile={}'.format(tmpfile_1),\n\t\t'--calc=logical_and(A>={0}, A<{1})'.format(from_threshold,to_threshold),\n\t\t'--type=Byte', '--NoDataValue=0',\n\t\t'--co=SPARSE_OK=YES',\n\t\t'--co=NBITS=1',\n\t\t'--quiet',\n\t\t'--co=COMPRESS=LZW'\n\t]\n\tsubprocess.run(args)\n\n\tsubprocess.run([\n\t\t\"gdal_edit.py\",\n\t\t'-a_srs', 'EPSG:{}'.format(infile_epsg),\n\t\ttmpfile_1\n\t])\n\n\tsubprocess.run([\n\t\t\"gdal_polygonize.py\",\n\t\ttmpfile_1,\n\t\t'-q',\n\t\t'-f', 'ESRI Shapefile',\n\t\ttmpfile_2\n\t])\n\n\tsubprocess.run([\n\t\t\"ogr2ogr\",\n\t\t'-a_srs', 'EPSG:{}'.format(infile_epsg),\n\t\t'-t_srs', 'EPSG:4326',\n\t\toutfile,\n\t\ttmpfile_2\n\t])\n\n\tsubprocess.run([\"rm\", tmpfile_1])\n\tsubprocess.run([\"rm\", tmpfile_2])\n\tsubprocess.run([\"rm\", tmpfile_2.replace('shp', 'shx')])\n\tsubprocess.run([\"rm\", tmpfile_2.replace('shp', 'dbf')])\n\tsubprocess.run([\"rm\", tmpfile_2.replace('shp', 'prj')])\n\ndef convert_geotiff_to_vector_with_multibands(band_colors, infile, infile_epsg,tmpfile_1, tmpfile_2, outfile):\n\t\"\"\"Convert multi-band GeoTiff raster file to Shapefile with geometries based on raster band color values\n\n Parameters\n - band_colors - Tuple with 3-values each corresponding to the values in raster bands\n - infile - String name of input GeoTff file path\n - infile_epsg - Integer value of EPSG Projection number of raster\n - tmpfile_1 - Stirng name of tmp file 1\n - tmpfile_2 - Stirng name of tmp file 2\n - outfile - Stirng name of output shapefile\n\n Outputs\n Shapefile with Polygon geometries of rasters based on raster band values\n \"\"\"\n\targs = [\n\t\t\"gdal_calc.py\",\n\t\t'-A', infile,\n\t\t'--A_band=1',\n\t\t'-B', infile,\n\t\t'--B_band=2',\n\t\t'-C', infile,\n\t\t'--C_band=3',\n\t\t'--outfile={}'.format(tmpfile_1),\n\t\t'--type=Byte', '--NoDataValue=0',\n\t\t'--calc=logical_and(A=={0}, B=={1},C=={2})'.format(band_colors[0],band_colors[1],band_colors[2]),\n\t\t'--co=SPARSE_OK=YES',\n\t\t'--co=NBITS=1',\n\t\t'--quiet',\n\t\t'--co=COMPRESS=LZW'\n\t]\n\tsubprocess.run(args)\n\n\tsubprocess.run([\n\t\t\"gdal_edit.py\",\n\t\t'-a_srs', 'EPSG:{}'.format(infile_epsg),\n\t\ttmpfile_1\n\t])\n\n\n\tsubprocess.run([\n\t\t\"gdal_polygonize.py\",\n\t\ttmpfile_1,\n\t\t'-q',\n\t\t'-f', 'ESRI Shapefile',\n\t\ttmpfile_2\n\t])\n\n\tsubprocess.run([\n\t\t\"ogr2ogr\",\n\t\t'-a_srs', 'EPSG:{}'.format(infile_epsg),\n\t\t'-t_srs', 'EPSG:4326',\n\t\toutfile,\n\t\ttmpfile_2\n\t])\n\n\tsubprocess.run([\"rm\", tmpfile_1])\n\tsubprocess.run([\"rm\", tmpfile_2])\n\tsubprocess.run([\"rm\", tmpfile_2.replace('shp', 'shx')])\n\tsubprocess.run([\"rm\", tmpfile_2.replace('shp', 'dbf')])\n\tsubprocess.run([\"rm\", tmpfile_2.replace('shp', 'prj')])\n\ndef convert(threshold, infile, tmpfile_1, outfile):\n\t\"\"\"Convert GeoTiff raster file to Shapefile with geometries based on raster threshold less that 999\n\n Parameters\n - threshold - Float value of lower bound of GeoTiff threshold value to be selected\n - infile - String name of input GeoTff file path\n - tmpfile_1 - Stirng name of tmp file 1\n - outfile - Stirng name of output shapefile\n\n Outputs\n Shapefile with Polygon geometries of rasters based on raster values above a threshold\n \"\"\"\n\targs = [\n\t\t\"gdal_calc.py\",\n\t\t'-A', infile,\n\t\t'--outfile={}'.format(tmpfile_1),\n\t\t'--calc=logical_and(A>={}, A<999)'.format(threshold),\n\t\t'--type=Byte', '--NoDataValue=0',\n\t\t'--co=SPARSE_OK=YES',\n\t\t'--co=NBITS=1',\n\t\t'--co=COMPRESS=LZW'\n\t]\n\tsubprocess.run(args)\n\n\tsubprocess.run([\n\t\t\"gdal_polygonize.py\",\n\t\ttmpfile_1,\n\t\t'-q',\n\t\t'-f', 'ESRI Shapefile',\n\t\toutfile\n\t])\n\ndef main():\n\t\"\"\"Process hazard data\n\n 1. Specify the paths from where to read and write:\n - Input data\n - Hazard data\n\n 2. Supply input data and parameters\n - Thresholds of flood hazards\n - Values of bands to be selected\n - Color code of multi-band rasters\n - Specific file names that might require some specific operations\n \"\"\"\n\tdata_path = load_config()['paths']['data']\n\troot_dir = os.path.join(data_path,'flood_data','FATHOM')\n\n\tthresholds = [1,2,3,4,999]\n\tthresholds_label = ['50cm','1m','2m','3m','4m','999m']\n\tf_all = []\n\tfor root, dirs, files in os.walk(root_dir):\n\t\tfor file in files:\n\t\t\tif file.endswith(\".tif\") or file.endswith(\".tiff\"):\n\t\t\t\tband_nums, crs = raster_projections_and_databands(os.path.join(root, file))\n\t\t\t\tprint (file,band_nums,crs)\n\t\t\t\tif 'epsg' in crs:\n\t\t\t\t\tcrs_split = crs.split(':')\n\t\t\t\t\ts_crs = [int(c) for c in crs_split if c.isdigit() is True][0]\n\t\t\t\telse:\n\t\t\t\t\ts_crs = 4326\n\n\n\t\t\t\t# threshold based datasets\n\t\t\t\tfor t in range(len(thresholds)-1):\n\t\t\t\t\tthr_1 = thresholds[t]\n\t\t\t\t\tthr_2 = thresholds[t+1]\n\t\t\t\t\tin_file = os.path.join(root,file)\n\t\t\t\t\ttmp_1 = os.path.join(root,file.split(\".tif\")[0] + '_mask.tiff')\n\t\t\t\t\ttmp_2 = os.path.join(root,file.split(\".tif\")[0] + '_mask.shp')\n\t\t\t\t\tout_file = os.path.join(root,file.split(\".tif\")[0] + \\\n\t\t\t\t\t\t\t\t'_{0}-{1}_threshold.shp'.format(thresholds_label[t],thresholds_label[t+1]))\n\t\t\t\t\tconvert_geotiff_to_vector_with_threshold(thr_1,thr_2,in_file,s_crs,tmp_1, tmp_2, out_file)\n\n\nif __name__ == \"__main__\":\n\tmain()\n",
"\"\"\"Plot commodities matrices\n\"\"\"\nimport os\n\nimport cartopy.crs as ccrs\nimport pandas\n\nfrom atra.utils import load_config\n\n\ndef main(config):\n \"\"\"Read data, plot charts\n \"\"\"\n data_path = config['paths']['data']\n od_file = os.path.join(data_path, 'usage', 'economic_od.csv')\n od = pandas.read_csv(od_file)\n\n # TODO extend from notes to proof of concept\n\n # integer zone ids\n od.from_zone = od.from_zone.apply(lambda z: int(z.replace(\"econ_\", \"\")))\n od.to_zone = od.to_zone.apply(lambda z: int(z.replace(\"econ_\", \"\")))\n\n # pivot and plot\n mat = od[od.sector == 'meat'].drop('sector', axis=1).pivot(\"from_zone\", \"to_zone\", \"value\")\n ax = seaborn.heatmap(mat, square=True, cmap='magma_r')\n\n\nif __name__ == '__main__':\n CONFIG = load_config()\n main(CONFIG)\n",
"\"\"\"Create the road network for Argentina by combining properties \n For roads based on different road inputs and model assumptions \n\"\"\"\nimport csv\nimport os\nimport types\nimport fiona\nimport numpy as np\nimport igraph as ig\nimport copy\nimport unidecode\nfrom scipy.spatial import Voronoi\nfrom shapely.geometry import Point, LineString\nfrom atra.utils import *\nimport datetime\nfrom tqdm import tqdm\nimport pandas as pd\nimport geopandas as gpd\n\ndef assign_road_name(x):\n \"\"\"Assign road conditions as paved or unpaved to Province roads\n\n Parameters\n x - Pandas DataFrame of values\n - code - Numeric code for type of asset\n - level - Numeric code for level of asset\n\n Returns\n String value as paved or unpaved\n \"\"\"\n asset_type = str(x.road_type).lower().strip()\n\n if str(x.road_name) != '0':\n return x.road_name\n else:\n return 'no number'\n\n\ndef assign_road_surface(x):\n \"\"\"Assign road surface to roads\n\n Parameters\n x - Pandas DataFrame of values\n - road_type - String name for type of road: national, province or rural\n - material_code - String code for road materials: \n [('A','Asfalto'),('H','Hormigon'), ('R','Ripio'), ('T','Tierra'), ('B','Tratamiento')]\n - surface - String name of already assigned road surface \n\n Returns\n String value of road surface as one or more of: \n ['Asfalto','Hormigon', 'Ripio', 'Tierra','Tratamiento']\n \"\"\"\n asset_type = str(x.road_type).lower().strip()\n\n\n # This is an national and provincial roads with paved surfaces\n '''A - Asphalt, H - Hormigon, R - Ripio, T - Tierra, B - Tratamiento\n '''\n matrerial_surfaces = [('A','Asfalto'),('H','Hormigon'), ('R','Ripio'), ('T','Tierra'), ('B','Tratamiento')]\n if asset_type == 'national':\n if str(x.material_code) != '0':\n ml = x.material_code.split(',')\n s = []\n for ms in matrerial_surfaces:\n if ms[0] in ml:\n s.append(ms[1])\n\n return ','.join(s)\n else:\n return 'Asfalto'\n elif str(x.surface).lower().strip() != '0':\n # Anything else not included above\n return x.surface.title()\n else:\n return 'Tierra'\n\ndef assign_road_conditions(x):\n \"\"\"Assign road conditions as paved or unpaved to Province roads\n\n Parameters\n x - Pandas DataFrame of values\n - road_type - String name for type of road: national, province or rural\n - material_code - String code for road materials: \n [('A','Asfalto'),('H','Hormigon'), ('R','Ripio'), ('T','Tierra'), ('B','Tratamiento')]\n\n Returns\n String value as paved or unpaved\n \"\"\"\n asset_type = str(x.road_type).lower().strip()\n\n if asset_type == 'national':\n if ('A' in str(x.material_code)) or ('B' in str(x.material_code)) or ('H' in str(x.material_code)):\n return 'paved'\n elif ('R' in str(x.material_code)) or ('T' in str(x.material_code)):\n return 'unpaved'\n else:\n return 'paved'\n elif str(x.surface).lower().strip() in ('pavimentado, pavimento en construcc'):\n # Anything else not included above\n return 'paved'\n else:\n return 'unpaved'\n\n\ndef assign_road_terrain_and_width(x,width_terrain_list):\n \"\"\"Assign width and terrain to roads\n\n Parameters\n x - Pandas DataFrame of values\n - road_name - String value of road name\n\n Returns\n Numeric value of road width\n String value of terrain as flat or mountain\n \"\"\"\n road_names = str(x.road_name).split(',')\n road_no = []\n for rn in road_names:\n if str(rn).isdigit():\n road_no.append(int(rn))\n else:\n road_no.append(rn)\n\n terrain = 'flat'\n assumed_width = 0\n if x.road_type == 'national':\n for vals in width_terrain_list:\n rn = vals.road_no\n if str(vals.road_no).isdigit():\n rn = int(rn)\n if rn in road_no and x.prog_min >= vals.inital_km and x.prog_max <= vals.final_km:\n assumed_width = vals.left_width + vals.right_width\n terrain = vals.terrain\n break\n\n if assumed_width == 0 and x.road_type in ('national','province'):\n assumed_width = 7.30\n elif assumed_width == 0 and x.road_type == 'rural':\n assumed_width = 3.65\n\n if unidecode.unidecode(str(terrain).lower().strip()) in ('llano','ondulado'):\n terrain = 'flat'\n elif unidecode.unidecode(str(terrain).lower().strip()) == 'montana':\n terrain = 'mountain'\n else:\n terrain = 'flat'\n\n return assumed_width, terrain\n\ndef assign_min_max_speeds_to_roads(x,speeds_list):\n \"\"\"Assign speeds to roads\n\n Parameters\n x - Pandas DataFrame of values\n - road_name - String value of road name\n\n Returns\n Numeric values of roads min-max speeds\n \"\"\"\n road_names = str(x.road_name).split(',')\n road_no = []\n for rn in road_names:\n if str(rn).isdigit():\n road_no.append(int(rn))\n else:\n road_no.append(rn)\n\n min_speed = 0\n max_speed = 0\n if x.road_type == 'national':\n for vals in speeds_list:\n rn = vals.ruta\n if str(rn).isdigit():\n rn = int(rn)\n\n if rn in road_no and x.prog_min >= vals.inicio and x.prog_max <= vals.fin:\n min_speed = vals.vmpes\n max_speed = vals.percentilpes\n break\n\n if (min_speed == 0 or isinstance(min_speed,str)) and x.road_type == 'national':\n if (0 < x.road_service <= 1) or (0 < x.road_quality <= 3):\n min_speed = 50\n max_speed = 80\n elif (1 < x.road_service <= 2) or (3 < x.road_quality <= 6):\n min_speed = 60\n max_speed = 90\n else:\n min_speed = 70\n max_speed = 100\n\n elif (min_speed == 0 or isinstance(min_speed,str)) and x.road_type == 'province':\n min_speed = 40\n max_speed = 60\n elif (min_speed == 0 or isinstance(min_speed,str)):\n min_speed = 20\n max_speed = 40\n\n return min_speed, max_speed\n\ndef assign_minmax_time_costs_roads(x, road_costs,exchange_rate):\n \"\"\"Assign time costs to roads\n These are the Vehicle Operating Costs (VOC)\n Based on DNV data\n\n Parameters\n x - Pandas DataFrame of values\n - min_speed - Numeric minimum speed of roads\n - min_speed - NUmeric maximum speed of roads\n - surface - String surface of road\n road_costs - Pandas DataFrame of cost values\n exchange_rate - Numeric exchange rate of ARG to USD\n\n Returns\n Numeric values of roads min-max time costs\n \"\"\"\n design_speeds = road_costs['speed'].values.tolist()\n if x.min_speed == 0 and x.max_speed == 0:\n min_cost = 0\n max_cost = 0\n elif x.min_speed in design_speeds and x.max_speed in design_speeds:\n min_speed = x.min_speed\n max_speed = x.max_speed\n else:\n min_speed = [design_speeds[d] for d in range(len(design_speeds)-1) if design_speeds[d] <= x.min_speed < design_speeds[d+1]][0]\n max_speed = [design_speeds[d] for d in range(len(design_speeds)-1) if design_speeds[d] <= x.max_speed < design_speeds[d+1]][0]\n\n if x.surface.lower().strip() in ('tierra','de tierra'):\n min_cost = road_costs.loc[road_costs['speed'] == min_speed,'tierra_cost_total'].values[0]\n max_cost = road_costs.loc[road_costs['speed'] == max_speed,'tierra_cost_total'].values[0]\n elif x.surface.lower().strip() in ('ripio','consolidado'):\n min_cost = road_costs.loc[road_costs['speed'] == min_speed,'ripio_cost_total'].values[0]\n max_cost = road_costs.loc[road_costs['speed'] == max_speed,'ripio_cost_total'].values[0]\n else:\n min_cost = road_costs.loc[road_costs['speed'] == min_speed,'paved_cost_total'].values[0]\n max_cost = road_costs.loc[road_costs['speed'] == max_speed,'paved_cost_total'].values[0]\n\n\n return exchange_rate*min_cost*x.length, exchange_rate*max_cost*x.length\n\ndef assign_minmax_tariff_costs_roads_apply(x,tariff_costs_dataframe,exchange_rate):\n \"\"\"Assign tariff costs to roads\n\n Parameters\n x - Pandas DataFrame of values\n tariff_costs_dataframe - Pandas DataFrame of cost values\n exchange_rate - Numeric exchange rate of ARG to USD\n\n Returns\n Numeric values of roads min-max tariff costs\n \"\"\"\n min_cost = tariff_costs_dataframe['min_tariff_cost'].values[0]*x.length*exchange_rate\n max_cost = tariff_costs_dataframe['max_tariff_cost'].values[0]*x.length*exchange_rate\n\n return min_cost,max_cost\n\ndef add_roads_generalised_costs(G):\n \"\"\"Assign Generailsed costs to roads\n The costs are assigned for a unit tonnage of an assumed prototype truck\n Generalised Cost = VOC per vehicle ton + Tariff Costs\n\n Paramters\n G - Pandas dataframe of roads containing time and tariff costs\n vehicle_tonnage - Assumed unit weight of a truck in tons\n\n Returns\n Numeric values of roads min-max generalised costs\n \"\"\"\n vehicle_tonnage = 15.0\n G['max_gcost'] = list(\n\n (1.0/vehicle_tonnage) * np.array(G['max_time_cost'])\n + 1.0 * np.array(G['max_tariff_cost'])\n )\n G['min_gcost'] = list(\n (1.0/vehicle_tonnage) * np.array(G['min_time_cost'])\n + 1.0 * np.array(G['min_tariff_cost'])\n )\n\n return G\n\ndef road_shapefile_to_dataframe(edges,road_properties_dataframe,\n road_speeds_dataframe,time_costs_dataframe,tariff_costs_dataframe,exchange_rate):\n \"\"\"Create national network dataframe from inputs\n\n Parameters\n - edges_in - String path to edges file/network Shapefile\n - road_properties_file - String path to Excel file with road attributes\n - usage_factor - Tuple of 2-float values between 0 and 1\n\n Returns\n edges: Geopandas DataFrame with network edge topology and attributes\n \"\"\"\n tqdm.pandas()\n\n # assign road name\n edges['road_name'] = edges.progress_apply(assign_road_name, axis=1)\n\n # assgin asset terrain\n road_properties_dataframe = list(road_properties_dataframe.itertuples(index=False))\n edges['width_terrain'] = edges.progress_apply(lambda x: assign_road_terrain_and_width(x,road_properties_dataframe), axis=1)\n edges[['width', 'terrain']] = edges['width_terrain'].apply(pd.Series)\n edges.drop('width_terrain', axis=1, inplace=True)\n\n # assign road surface\n edges['surface'] = edges.progress_apply(assign_road_surface, axis=1)\n\n # assign road conditon\n edges['road_cond'] = edges.progress_apply(assign_road_conditions, axis=1)\n\n # assign minimum and maximum speed to network\n road_speeds_dataframe = list(road_speeds_dataframe.itertuples(index=False))\n edges['speed'] = edges.progress_apply(lambda x: assign_min_max_speeds_to_roads(\n x, road_speeds_dataframe), axis=1)\n edges[['min_speed', 'max_speed']] = edges['speed'].apply(pd.Series)\n edges.drop('speed', axis=1, inplace=True)\n\n # assign minimum and maximum travel time to network\n edges['min_time'] = edges['length']/edges['max_speed']\n edges['max_time'] = edges['length']/edges['min_speed']\n\n # assign minimum and maximum cost of time in USD to the network\n # the costs of time = (unit vehicle operating cost depending upon speed in USD/km)*(length of road)\n edges['time_cost'] = edges.progress_apply(\n lambda x: assign_minmax_time_costs_roads(x, time_costs_dataframe,exchange_rate), axis=1)\n edges[['min_time_cost', 'max_time_cost']] = edges['time_cost'].apply(pd.Series)\n edges.drop('time_cost', axis=1, inplace=True)\n\n # assign minimum and maximum cost of tonnage in USD/ton to the network\n # the costs of time = (unit cost of tariff in USD/ton-km)*(length in km)\n edges['tariff_cost'] = edges.progress_apply(\n lambda x: assign_minmax_tariff_costs_roads_apply(x, tariff_costs_dataframe,exchange_rate), axis=1)\n edges[['min_tariff_cost', 'max_tariff_cost']] = edges['tariff_cost'].apply(pd.Series)\n edges.drop('tariff_cost', axis=1, inplace=True)\n\n edges = add_roads_generalised_costs(edges)\n\n add_columns = [c for c in edges.columns.values.tolist() if c not in ['edge_id','from_node','to_node','geometry']]\n # make sure that From and To node are the first two columns of the dataframe\n # to make sure the conversion from dataframe to igraph network goes smooth\n edges = edges[['edge_id','from_node','to_node'] + add_columns + ['geometry']]\n edges = edges.reindex(list(edges.columns)[1:]+list(edges.columns)[:1], axis=1)\n\n return edges\n\ndef find_km_markers(road_dataframe,marker_dataframe):\n epsg_utm_20s = 32720\n road_dataframe = road_dataframe.to_crs(epsg=epsg_utm_20s)\n marker_dataframe = marker_dataframe.to_crs(epsg=epsg_utm_20s)\n marker_dataframe['poly_geometry'] = marker_dataframe.geometry.progress_apply(lambda x: x.buffer(0.04))\n poly_df = marker_dataframe[['id','progresiva','distancia','poly_geometry']]\n poly_df.rename(columns={'poly_geometry':'geometry'},inplace=True)\n road_matches = gpd.sjoin(road_dataframe,poly_df, how=\"inner\", op='intersects').reset_index()\n marker_dataframe.drop('poly_geometry',axis=1,inplace=True)\n del poly_df\n road_matches = road_matches[['edge_id','id','progresiva','distancia']].set_index(['edge_id'])\n marker_dataframe = marker_dataframe.set_index(['id'])\n edge_ids = list(set(road_matches.index.values.tolist()))\n edge_markers = []\n for e_id in edge_ids:\n marker_ids = road_matches.loc[[e_id],'id'].values.tolist()\n marker_prog = road_matches.loc[[e_id],'progresiva'].values.tolist()\n marker_dist = road_matches.loc[[e_id],'distancia'].values.tolist()\n marker_geom = marker_dataframe.loc[marker_ids,'geometry'].values.tolist()\n\n points_list = list(zip(marker_ids,marker_prog,marker_dist,marker_geom))\n pt_tup_list = []\n for pts in points_list:\n line = road_dataframe.loc[road_dataframe['edge_id']==e_id,'geometry'].values[0]\n point = line.interpolate(line.project(pts[-1]))\n pt_tup_list.append(tuple(list(pts[:-1]) + [line.project(point)]))\n\n length_km = 0.001*(road_dataframe.loc[road_dataframe['edge_id']==e_id,'length'].values[0])\n pt_tup_list = [(p,w,x,y) for (p,w,x,y) in sorted(pt_tup_list, key=lambda pair: pair[-1])]\n if pt_tup_list[0][-1] > 0:\n prog_min = pt_tup_list[0][1] - 0.001*pt_tup_list[0][-1]\n dist_min = pt_tup_list[0][2] - 0.001*pt_tup_list[0][-1]\n else:\n prog_min = pt_tup_list[0][1]\n dist_min = pt_tup_list[0][2]\n\n if pt_tup_list[-1][-1] < 1:\n prog_max = pt_tup_list[-1][1] + (length_km - 0.001*pt_tup_list[-1][-1])\n dist_max = pt_tup_list[-1][2] + (length_km - 0.001*pt_tup_list[-1][-1])\n else:\n prog_max = pt_tup_list[-1][1]\n dist_max = pt_tup_list[-1][2]\n\n if prog_min < 1e-3:\n prog_min = 0\n if dist_min < 1e-3:\n dist_min = 0\n edge_markers.append((e_id,prog_min,prog_max,dist_min,dist_max))\n\n edge_markers = pd.DataFrame(edge_markers,columns = ['edge_id','prog_min','prog_max','dist_min','dist_max'])\n\n del marker_dataframe, road_matches, edge_ids\n\n return edge_markers\n\ndef get_numeric_attributes(road_gpd,attribute_gpd,attribute_id_column,attribute_value_column,road_column_name):\n epsg_utm_20s = 32720\n road_gpd = road_gpd.to_crs(epsg=epsg_utm_20s)\n attribute_gpd = attribute_gpd.to_crs(epsg=epsg_utm_20s)\n attribute_gpd['geometry'] = attribute_gpd.geometry.progress_apply(lambda x: x.buffer(0.04))\n road_matches = gpd.sjoin(road_gpd,attribute_gpd, how=\"inner\", op='intersects').reset_index()\n road_matches = road_matches[['edge_id',attribute_id_column,attribute_value_column]].set_index(['edge_id'])\n attribute_gpd = attribute_gpd.set_index([attribute_id_column])\n edge_ids = list(set(road_matches.index.values.tolist()))\n edge_vals = []\n for e_id in edge_ids:\n line = road_gpd.loc[road_gpd['edge_id']==e_id,'geometry'].values[0]\n attr_ids = road_matches.loc[[e_id],attribute_id_column].values.tolist()\n attr_vals = road_matches.loc[[e_id],attribute_value_column].values.tolist()\n attr_geom = attribute_gpd.loc[attr_ids,'geometry'].values.tolist()\n\n poly_list = list(zip(attr_vals,attr_geom))\n attr_tot = 0\n length_tot = 0\n for poly in poly_list:\n length_m = line.intersection(poly[1]).length\n attr_tot += poly[0]*length_m\n length_tot += length_m\n\n if length_tot > 0:\n attr_tot = 1.0*attr_tot/length_tot\n else:\n attr_tot = 0\n\n edge_vals.append((e_id,attr_tot))\n\n print ('Done with attribute {} for edge {}'.format(road_column_name,e_id))\n\n edge_vals = pd.DataFrame(edge_vals,columns=['edge_id',road_column_name])\n\n del attribute_gpd\n return edge_vals\n\ndef get_string_attributes(road_gpd,attribute_gpd,attribute_value_column,road_column_name):\n epsg_utm_20s = 32720\n road_gpd = road_gpd.to_crs(epsg=epsg_utm_20s)\n attribute_gpd = attribute_gpd.to_crs(epsg=epsg_utm_20s)\n attribute_gpd['geometry'] = attribute_gpd.geometry.progress_apply(lambda x: x.buffer(0.04))\n road_matches = gpd.sjoin(road_gpd,attribute_gpd, how=\"inner\", op='intersects').reset_index()\n road_matches = road_matches[['edge_id',attribute_value_column]].set_index(['edge_id'])\n edge_ids = list(set(road_matches.index.values.tolist()))\n edge_vals = []\n for e_id in edge_ids:\n attr_vals = ','.join(list(set(road_matches.loc[[e_id],attribute_value_column].values.tolist())))\n edge_vals.append((e_id,attr_vals))\n\n print ('Done with attribute {} for edge {}'.format(road_column_name,e_id))\n\n edge_vals = pd.DataFrame(edge_vals,columns=['edge_id',road_column_name])\n\n del attribute_gpd\n return edge_vals\n\ndef main(config):\n tqdm.pandas()\n incoming_data_path = config['paths']['incoming_data']\n data_path = config['paths']['data']\n exchange_rate = 0.026\n\n '''Provide different data inputs to the code\n '''\n\n '''Describe the inputs for the datasets used to assign:\n Road quality, service, materials and TMDA on nationa roads\n These are datasets in the path /incoming_data/roads/nationa_roads/\n '''\n\n attributes_desc = [\n {\n 'folder_name':'indice_de_estado',\n 'file_name':'vistagis_selLine.shp',\n 'id_column':'nro_regist',\n 'attribute':'valor',\n 'attribute_rename':'road_quality'\n },\n {\n 'folder_name':'indice_de_serviciabilidad',\n 'file_name':'vistagis_selLine.shp',\n 'id_column':'nro_regist',\n 'attribute':'valor',\n 'attribute_rename':'road_service'\n },\n {\n 'folder_name':'materialcarril_sel',\n 'file_name':'materialcarril_selLine.shp',\n 'id_column':'id_materia',\n 'attribute':'grupo',\n 'attribute_rename':'material_code'\n },\n {\n 'folder_name':'tmda',\n 'file_name':'vistagis_selLine.shp',\n 'id_column':'nro_regist',\n 'attribute':'valor',\n 'attribute_rename':'tmda_count'\n },\n ]\n\n '''Read the data on the kilometer markers\n '''\n marker_df = gpd.read_file(os.path.join(incoming_data_path,\n 'pre_processed_network_data',\n 'roads',\n 'national_roads',\n 'v_mojon',\n 'v_mojonPoint.shp'),encoding='utf-8').fillna(0)\n \n '''Get the input data on road widths of some national roads and general costs for roads\n '''\n road_properties_df = pd.read_excel(os.path.join(incoming_data_path,\n 'road_properties',\n 'Tramos por Rutas.xls'),\n sheet_name='Hoja1',\n skiprows=4,\n encoding='utf-8-sig').fillna(0)\n road_properties_df.columns = ['road_no','location','inital_km','final_km',\n 'purpose','description','length_km','left_surface',\n 'left_width','right_surface','right_width','lanes','terrain']\n\n\n road_speeds_df = pd.read_excel(os.path.join(incoming_data_path,\n 'road_properties',\n 'TMDA y Clasificación 2016.xlsx'),\n sheet_name='Clasificación 2016',\n skiprows=14,encoding='utf-8-sig').fillna(0)\n road_speeds_df.columns = map(str.lower, road_speeds_df.columns)\n\n time_costs_df = pd.read_excel(os.path.join(incoming_data_path,\n 'costs',\n 'road',\n 'Costos de Operación de Vehículos.xlsx'),\n sheet_name='Camión Pesado',\n skiprows=15,encoding='utf-8-sig').fillna(0)\n time_costs_df.columns = ['speed','tierra_cost_A','tierra_cost_B','tierra_cost_total',\n 'ripio_cost_A','ripio_cost_B','ripio_cost_total',\n 'paved_cost_A','paved_cost_B','paved_cost_total','speed_copy']\n\n \n time_costs_df = time_costs_df[time_costs_df['speed'] > 0]\n\n tariff_costs_df = pd.read_excel(os.path.join(incoming_data_path,\n 'costs',\n 'road',\n 'tariff_costs.xlsx'),sheet_name='road',encoding='utf-8')\n\n '''Read the road edge and node network Shapefiles\n '''\n road_edges_path = os.path.join(incoming_data_path,\n 'pre_processed_network_data',\n 'roads',\n 'combined_roads',\n 'combined_roads_edges.shp')\n road_nodes_path = os.path.join(incoming_data_path,\n 'pre_processed_network_data',\n 'roads',\n 'combined_roads',\n 'combined_roads_nodes.shp')\n\n nodes = gpd.read_file(road_nodes_path,encoding='utf-8').fillna(0)\n nodes.columns = map(str.lower, nodes.columns)\n nodes.rename(columns={'id':'node_id'},inplace=True)\n\n edges_in = road_edges_path\n edges = gpd.read_file(edges_in,encoding='utf-8').fillna(0)\n edges.columns = map(str.lower, edges.columns)\n\n edges.rename(columns={'id':'edge_id','from_id':'from_node','to_id':'to_node'},inplace=True)\n\n '''Done with reading input data\n '''\n\n '''Start calculations from here\n '''\n # get the right linelength\n edges['length'] = edges.geometry.progress_apply(line_length)\n\n '''Add properties to the national roads\n '''\n km_markers= find_km_markers(edges[edges['road_type']=='national'][['edge_id','length','geometry']],marker_df)\n edges = pd.merge(edges,km_markers,how='left',on=['edge_id']).fillna(0)\n del km_markers\n '''Add the quality and service\n '''\n for a in attributes_desc:\n road_attr = gpd.read_file(os.path.join(incoming_data_path,\n 'pre_processed_network_data','roads','national_roads',\n a['folder_name'],a['file_name']),encoding='utf-8').fillna(0)\n if a['folder_name'] == 'materialcarril_sel':\n edge_attr = get_string_attributes(edges[edges['road_type']=='national'][['edge_id','length','geometry']],road_attr,a['attribute'],a['attribute_rename'])\n else:\n road_attr = road_attr[(road_attr['sentido'] == 'A') & (road_attr[a['attribute']] != -1)]\n edge_attr = get_numeric_attributes(edges[edges['road_type']=='national'][['edge_id','length','geometry']],road_attr,a['id_column'],a['attribute'],a['attribute_rename'])\n\n edges = pd.merge(edges,edge_attr,how='left',on=['edge_id']).fillna(0)\n del edge_attr, road_attr\n\n edges = road_shapefile_to_dataframe(edges,road_properties_df,road_speeds_df,time_costs_df,tariff_costs_df,exchange_rate)\n\n edges.to_file(os.path.join(data_path,'network','road_edges.shp'),encoding = 'utf-8')\n edges.drop('geometry', axis=1, inplace=True)\n edges.to_csv(os.path.join(data_path,'network','road_edges.csv'),encoding='utf-8-sig',index=False)\n\n nodes.to_file(os.path.join(data_path,'network', 'road_nodes.shp'),encoding = 'utf-8')\n nodes.drop('geometry', axis=1, inplace=True)\n nodes.to_csv(os.path.join(data_path,'network','road_nodes.csv'),encoding='utf-8-sig',index=False)\n\nif __name__ == '__main__':\n CONFIG = load_config()\n main(CONFIG)\n"
] |
[
[
"pandas.merge",
"pandas.read_csv",
"matplotlib.pyplot.close"
],
[
"numpy.isnan",
"pandas.DataFrame"
],
[
"pandas.read_csv"
],
[
"pandas.merge",
"numpy.array",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
hero9968/scikit-neuralnetwork
|
[
"b7fd0c089bd7c721c4d9cf9ca71eed74c6bafc5e"
] |
[
"sknn/backend/lasagne/mlp.py"
] |
[
"# -*- coding: utf-8 -*-\nfrom __future__ import (absolute_import, division, unicode_literals, print_function)\n\n__all__ = ['MultiLayerPerceptronBackend']\n\nimport os\nimport sys\nimport math\nimport time\nimport types\nimport logging\nimport itertools\n\nlog = logging.getLogger('sknn')\n\n\nimport numpy\nimport theano\nimport sklearn.base\nimport sklearn.pipeline\nimport sklearn.preprocessing\nimport sklearn.cross_validation\n\nimport theano.tensor as T\nimport lasagne.layers\nimport lasagne.nonlinearities as nl\n\nfrom ..base import BaseBackend\nfrom ...nn import Layer, Convolution, Native, ansi\n\n\ndef explin(x):\n return x * (x>=0) + (x<0) * (T.exp(x) - 1)\n\n\nclass MultiLayerPerceptronBackend(BaseBackend):\n \"\"\"\n Abstract base class for wrapping the multi-layer perceptron functionality\n from Lasagne.\n \"\"\"\n\n def __init__(self, spec):\n super(MultiLayerPerceptronBackend, self).__init__(spec)\n self.mlp = None\n self.f = None\n self.trainer = None\n self.validator = None\n self.regularizer = None\n\n def _create_mlp_trainer(self, params):\n # Aggregate all regularization parameters into common dictionaries.\n layer_decay = {}\n if self.regularize in ('L1', 'L2') or any(l.weight_decay for l in self.layers):\n wd = self.weight_decay or 0.0001\n for l in self.layers:\n layer_decay[l.name] = l.weight_decay or wd\n assert len(layer_decay) == 0 or self.regularize in ('L1', 'L2', None)\n\n if len(layer_decay) > 0:\n if self.regularize is None:\n self.auto_enabled['regularize'] = 'L2'\n regularize = self.regularize or 'L2'\n penalty = getattr(lasagne.regularization, regularize.lower())\n apply_regularize = lasagne.regularization.apply_penalty\n self.regularizer = sum(layer_decay[s.name] * apply_regularize(l.get_params(regularizable=True), penalty)\n for s, l in zip(self.layers, self.mlp))\n\n if self.normalize is None and any([l.normalize != None for l in self.layers]):\n self.auto_enabled['normalize'] = 'batch'\n\n cost_functions = {'mse': 'squared_error', 'mcc': 'categorical_crossentropy'}\n loss_type = self.loss_type or ('mcc' if self.is_classifier else 'mse')\n assert loss_type in cost_functions,\\\n \"Loss type `%s` not supported by Lasagne backend.\" % loss_type\n self.cost_function = getattr(lasagne.objectives, cost_functions[loss_type])\n cost_symbol = self.cost_function(self.trainer_output, self.data_output)\n cost_symbol = lasagne.objectives.aggregate(cost_symbol.T, self.data_mask, mode='mean')\n\n if self.regularizer is not None:\n cost_symbol = cost_symbol + self.regularizer\n return self._create_trainer_function(params, cost_symbol)\n\n def _create_trainer_function(self, params, cost):\n if self.learning_rule in ('sgd', 'adagrad', 'adadelta', 'rmsprop', 'adam'):\n lr = getattr(lasagne.updates, self.learning_rule)\n self._learning_rule = lr(cost, params, learning_rate=self.learning_rate)\n elif self.learning_rule in ('momentum', 'nesterov'):\n lasagne.updates.nesterov = lasagne.updates.nesterov_momentum\n lr = getattr(lasagne.updates, self.learning_rule)\n self._learning_rule = lr(cost, params, learning_rate=self.learning_rate, momentum=self.learning_momentum)\n else:\n raise NotImplementedError(\n \"Learning rule type `%s` is not supported.\" % self.learning_rule)\n\n trainer = theano.function([self.data_input, self.data_output, self.data_mask], cost,\n updates=self._learning_rule,\n on_unused_input='ignore',\n allow_input_downcast=True)\n\n compare = self.cost_function(self.network_output, self.data_correct).mean()\n validator = theano.function([self.data_input, self.data_correct], compare,\n allow_input_downcast=True)\n return trainer, validator\n\n def _get_activation(self, l):\n nonlinearities = {'Rectifier': nl.rectify,\n 'Sigmoid': nl.sigmoid,\n 'Tanh': nl.tanh,\n 'Softmax': nl.softmax,\n 'Linear': nl.linear,\n 'ExpLin': explin}\n\n assert l.type in nonlinearities,\\\n \"Layer type `%s` is not supported for `%s`.\" % (l.type, l.name)\n return nonlinearities[l.type]\n\n def _create_convolution_layer(self, name, layer, network):\n self._check_layer(layer,\n required=['channels', 'kernel_shape'],\n optional=['units', 'kernel_stride', 'border_mode',\n 'pool_shape', 'pool_type', 'scale_factor'])\n\n if layer.scale_factor != (1, 1):\n network = lasagne.layers.Upscale2DLayer(\n network,\n scale_factor=layer.scale_factor)\n\n network = lasagne.layers.Conv2DLayer(\n network,\n num_filters=layer.channels,\n filter_size=layer.kernel_shape,\n stride=layer.kernel_stride,\n pad=layer.border_mode,\n nonlinearity=self._get_activation(layer))\n\n normalize = layer.normalize or self.normalize\n if normalize == 'batch':\n network = lasagne.layers.batch_norm(network)\n\n if layer.pool_shape != (1, 1):\n network = lasagne.layers.Pool2DLayer(\n network,\n pool_size=layer.pool_shape,\n stride=layer.pool_shape)\n\n return network\n\n def _create_native_layer(self, name, layer, network):\n if layer.units and 'num_units' not in layer.keywords:\n layer.keywords['num_units'] = layer.units\n return layer.type(network, *layer.args, **layer.keywords)\n\n def _create_layer(self, name, layer, network):\n if isinstance(layer, Native):\n return self._create_native_layer(name, layer, network)\n\n dropout = layer.dropout or self.dropout_rate\n if dropout is not None:\n network = lasagne.layers.dropout(network, dropout)\n\n if isinstance(layer, Convolution):\n return self._create_convolution_layer(name, layer, network)\n\n self._check_layer(layer, required=['units'])\n network = lasagne.layers.DenseLayer(network,\n num_units=layer.units,\n nonlinearity=self._get_activation(layer))\n\n normalize = layer.normalize or self.normalize\n if normalize == 'batch':\n network = lasagne.layers.batch_norm(network)\n return network\n\n def _create_mlp(self, X, w=None):\n self.data_input = T.tensor4('X') if self.is_convolution(input=True) else T.matrix('X')\n self.data_output = T.tensor4('y') if self.is_convolution(output=True) else T.matrix('y')\n self.data_mask = T.vector('m') if w is not None else T.scalar('m')\n self.data_correct = T.matrix('yp')\n\n lasagne.random.get_rng().seed(self.random_state)\n\n shape = list(X.shape)\n network = lasagne.layers.InputLayer([None]+shape[1:], self.data_input)\n\n # Create the layers one by one, connecting to previous.\n self.mlp = []\n for i, layer in enumerate(self.layers):\n network = self._create_layer(layer.name, layer, network)\n network.name = layer.name\n self.mlp.append(network)\n\n log.info(\n \"Initializing neural network with %i layers, %i inputs and %i outputs.\",\n len(self.layers), self.unit_counts[0], self.layers[-1].units)\n\n for l, p, count in zip(self.layers, self.mlp, self.unit_counts[1:]):\n space = p.output_shape\n if isinstance(l, Convolution):\n log.debug(\" - Convl: {}{: <10}{} Output: {}{: <10}{} Channels: {}{}{}\".format(\n ansi.BOLD, l.type, ansi.ENDC,\n ansi.BOLD, repr(space[2:]), ansi.ENDC,\n ansi.BOLD, space[1], ansi.ENDC))\n\n # NOTE: Numbers don't match up exactly for pooling; one off. The logic is convoluted!\n # assert count == numpy.product(space.shape) * space.num_channels,\\\n # \"Mismatch in the calculated number of convolution layer outputs.\"\n elif isinstance(l, Native):\n log.debug(\" - Nativ: {}{: <10}{} Output: {}{: <10}{} Channels: {}{}{}\".format(\n ansi.BOLD, l.type.__name__, ansi.ENDC,\n ansi.BOLD, repr(space[2:]), ansi.ENDC,\n ansi.BOLD, space[1], ansi.ENDC))\n else:\n log.debug(\" - Dense: {}{: <10}{} Units: {}{: <4}{}\".format(\n ansi.BOLD, l.type, ansi.ENDC, ansi.BOLD, l.units, ansi.ENDC))\n assert count == space[1],\\\n \"Mismatch in the calculated number of dense layer outputs. {} != {}\".format(count, space[1])\n\n if self.weights is not None:\n l = min(len(self.weights), len(self.mlp))\n log.info(\"Reloading parameters for %i layer weights and biases.\" % (l,))\n self._array_to_mlp(self.weights, self.mlp)\n self.weights = None\n\n log.debug(\"\")\n\n self.network_output = lasagne.layers.get_output(network, deterministic=True)\n self.trainer_output = lasagne.layers.get_output(network, deterministic=False)\n self.f = theano.function([self.data_input], self.network_output, allow_input_downcast=True)\n\n def _conv_transpose(self, arr):\n ok = arr.shape[-1] not in (1,3) and arr.shape[1] in (1,3)\n return arr if ok else numpy.transpose(arr, (0, 3, 1, 2))\n\n def _initialize_impl(self, X, y=None, w=None):\n if self.is_convolution(input=True):\n X = self._conv_transpose(X)\n if y is not None and self.is_convolution(output=True):\n y = self._conv_transpose(y)\n\n if self.mlp is None:\n self._create_mlp(X, w)\n\n # Can do partial initialization when predicting, no trainer needed.\n if y is None:\n return\n\n if self.valid_size > 0.0:\n assert self.valid_set is None, \"Can't specify valid_size and valid_set together.\"\n X, X_v, y, y_v = sklearn.cross_validation.train_test_split(\n X, y,\n test_size=self.valid_size,\n random_state=self.random_state)\n self.valid_set = X_v, y_v\n\n if self.valid_set and self.is_convolution():\n X_v, y_v = self.valid_set\n if X_v.shape[-2:] != X.shape[-2:]:\n self.valid_set = numpy.transpose(X_v, (0, 3, 1, 2)), y_v\n\n params = []\n for spec, mlp_layer in zip(self.layers, self.mlp):\n if spec.frozen: continue\n params.extend(mlp_layer.get_params())\n\n self.trainer, self.validator = self._create_mlp_trainer(params)\n return X, y\n\n def _predict_impl(self, X):\n if self.is_convolution():\n X = numpy.transpose(X, (0, 3, 1, 2))\n\n y = None\n for Xb, _, _, idx in self._iterate_data(self.batch_size, X, y, shuffle=False):\n yb = self.f(Xb)\n if y is None:\n if X.shape[0] <= self.batch_size:\n y = yb\n break\n else:\n y = numpy.zeros(X.shape[:1] + yb.shape[1:], dtype=theano.config.floatX)\n y[idx] = yb\n return y\n\n def _iterate_data(self, batch_size, X, y=None, w=None, shuffle=False):\n def cast(array, indices):\n if array is None:\n return None\n\n # Support for pandas.DataFrame, requires custom indexing.\n if type(array).__name__ == 'DataFrame':\n array = array.loc[indices]\n else:\n array = array[indices]\n\n # Support for scipy.sparse; convert after slicing.\n if hasattr(array, 'todense'):\n array = array.todense()\n\n return array.astype(theano.config.floatX)\n\n total_size = X.shape[0]\n indices = numpy.arange(total_size)\n if shuffle:\n numpy.random.shuffle(indices)\n\n for index in range(0, total_size, batch_size):\n excerpt = indices[index:index + batch_size]\n Xb, yb, wb = cast(X, excerpt), cast(y, excerpt), cast(w, excerpt)\n yield Xb, yb, wb, excerpt\n\n def _print(self, text):\n if self.verbose:\n sys.stdout.write(text)\n sys.stdout.flush()\n\n def _batch_impl(self, X, y, w, processor, mode, output, shuffle):\n progress, batches = 0, X.shape[0] / self.batch_size\n loss, count = 0.0, 0\n for Xb, yb, wb, _ in self._iterate_data(self.batch_size, X, y, w, shuffle):\n self._do_callback('on_batch_start', locals())\n\n if mode == 'train':\n loss += processor(Xb, yb, wb if wb is not None else 1.0)\n else:\n loss += processor(Xb, yb)\n count += 1\n\n while count / batches > progress / 60:\n self._print(output)\n progress += 1\n\n self._do_callback('on_batch_finish', locals())\n\n self._print('\\r')\n return loss / count\n\n def _train_impl(self, X, y, w=None):\n return self._batch_impl(X, y, w, self.trainer, mode='train', output='.', shuffle=True)\n\n def _valid_impl(self, X, y, w=None):\n return self._batch_impl(X, y, w, self.validator, mode='valid', output=' ', shuffle=False)\n\n @property\n def is_initialized(self):\n \"\"\"Check if the neural network was setup already.\n \"\"\"\n return not (self.f is None)\n\n def _mlp_get_layer_params(self, layer):\n \"\"\"Traverse the Lasagne network accumulating parameters until\n reaching the next \"major\" layer specified and named by the user.\n \"\"\"\n assert layer.name is not None, \"Expecting this layer to have a name.\"\n\n params = []\n while hasattr(layer, 'input_layer'):\n params.extend(layer.get_params())\n layer = layer.input_layer\n if layer.name is not None:\n break\n return params\n\n def _mlp_to_array(self):\n return [[p.get_value() for p in self._mlp_get_layer_params(l)] for l in self.mlp]\n\n def _array_to_mlp(self, array, nn):\n for layer, data in zip(nn, array):\n if data is None:\n continue\n\n # Handle namedtuple format returned by get_parameters() as special case.\n # Must remove the last `name` item in the tuple since it's not a parameter.\n string_types = getattr(types, 'StringTypes', tuple([str]))\n data = tuple([d for d in data if not isinstance(d, string_types)])\n\n params = self._mlp_get_layer_params(layer)\n assert len(data) == len(params),\\\n \"Mismatch in data size for layer `%s`. %i != %i\"\\\n % (layer.name, len(data), len(params))\n\n for p, d in zip(params, data):\n ps = tuple(p.shape.eval())\n assert ps == d.shape, \"Layer parameter shape mismatch: %r != %r\" % (ps, d.shape)\n p.set_value(d.astype(theano.config.floatX))\n"
] |
[
[
"numpy.arange",
"numpy.zeros",
"numpy.random.shuffle",
"numpy.transpose"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gangigammo/deep-learning-1
|
[
"3fe803514c3733d8715cf1211a82ffd8ea660af2"
] |
[
"common/gradient.py"
] |
[
"# coding: utf-8\nimport numpy as np\n\ndef _numerical_gradient_1d(f, x):\n h = 1e-4 # 0.0001\n grad = np.zeros_like(x)\n \n for idx in range(x.size):\n tmp_val = x[idx]\n x[idx] = float(tmp_val) + h\n fxh1 = f(x) # f(x+h)\n \n x[idx] = tmp_val - h \n fxh2 = f(x) # f(x-h)\n grad[idx] = (fxh1 - fxh2) / (2*h)\n \n x[idx] = tmp_val # 値を元に戻す\n \n return grad\n\n\ndef numerical_gradient_2d(f, X):\n if X.ndim == 1:\n return _numerical_gradient_1d(f, X)\n else:\n grad = np.zeros_like(X)\n \n for idx, x in enumerate(X):\n grad[idx] = _numerical_gradient_1d(f, x)\n \n return grad\n\n\ndef numerical_gradient(f, x):\n h = 1e-4 # 0.0001\n grad = np.zeros_like(x)\n \n it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])\n while not it.finished:\n idx = it.multi_index\n tmp_val = x[idx]\n x[idx] = float(tmp_val) + h\n fxh1 = f(x) # f(x+h)\n \n x[idx] = tmp_val - h \n fxh2 = f(x) # f(x-h)\n grad[idx] = (fxh1 - fxh2) / (2*h)\n \n x[idx] = tmp_val # 値を元に戻す\n it.iternext() \n \n return grad\n\n"
] |
[
[
"numpy.zeros_like",
"numpy.nditer"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sonata-nfv/tng-sdk-validation
|
[
"e20bfa2247c95a82db42a0dd586f76a0c42d059b"
] |
[
"non-functional-tests/stat-graph-generation.py"
] |
[
"#!/usr/bin/python3\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport pandas as pd\n\nresults = pd.read_csv('integrity_2019-07-16_00-20-47_21_iteraciones.csv')\nresults.head()\nresults['Max memory (mb)'] = results['Max memory (kb)'] / 1024\nresults = results.drop('Max memory (kb)', axis=1)\n\nresults['VNFs']=[ i for j in range(24) for i in range(1,101)]\nresults_part1 = results[900:1300]\nresults_part1.plot(kind='scatter',x='VNFs', y='Max memory (mb)', color='red')\nplt.show()"
] |
[
[
"pandas.read_csv",
"matplotlib.pyplot.show"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
atztogo/niggli
|
[
"157e3474fc63ef415584e8b5db4483c65c6abf01"
] |
[
"python/niggli/niggli.py"
] |
[
"# Copyright (C) 2016 Atsushi Togo\n# All rights reserved.\n#\n# This file is part of niggli\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n#\n# * Neither the name of the niggli project nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nfrom . import _niggli as niggli\nimport numpy as np\n\ndef get_version():\n return tuple(niggli.version())\n\ndef niggli_reduce(lattice, eps=1e-5):\n \"\"\"Run Niggli reduction\n\n Args:\n lattice: Lattice parameters\n [a_x, b_x, c_x, a_y, b_y, c_y, a_z, b_z, c_z] or\n [[a_x, b_x, c_x], [a_y, b_y, c_y], [a_z, b_z, c_z]]\n eps: Tolerance.\n \n Returns:\n Reduced lattice parameters\n [[a_x, b_x, c_x], [a_y, b_y, c_y], [a_z, b_z, c_z]]\n \"\"\"\n reduced_lattice = np.array(np.ravel(lattice), dtype='double')\n result = niggli.niggli_reduce(reduced_lattice, float(eps))\n if result == 0:\n return None\n else:\n return np.reshape(reduced_lattice, (3, 3), order='C')\n\n"
] |
[
[
"numpy.reshape",
"numpy.ravel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
irec-org/irec
|
[
"a7ec8a53dcb6489c31f64d7192720baca50e0049"
] |
[
"irec/offline_experiments/evaluation_policies/limited_interaction.py"
] |
[
"from .base import EvaluationPolicy\nfrom threadpoolctl import threadpool_limits\nfrom collections import defaultdict\nimport scipy.sparse\nimport numpy as np\nimport random\n\nclass LimitedInteraction(EvaluationPolicy):\n\n \"\"\"LimitedInteraction\n\n In this evaluation policy, the system will perform new actions until it\n reaches all items registered in the user's history. The idea is to do an\n exhaustive experiment to observe which algorithm takes the longest to reach\n all the items previously evaluated by each user. Each user is randomly selected and\n each action will not be performed more than once for him/her. \n \n \"\"\"\n\n def __init__(\n self, interaction_size, recommend_test_data_rate_limit, *args, **kwargs\n ):\n super().__init__(*args, **kwargs)\n self.interaction_size = interaction_size\n self.recommend_test_data_rate_limit = recommend_test_data_rate_limit\n\n def evaluate(self, model, train_dataset, test_dataset):\n with threadpool_limits(limits=1, user_api=\"blas\"):\n test_users = np.unique(test_dataset.data[:, 0]).astype(int)\n num_total_items = test_dataset.num_total_items\n test_consumption_matrix = scipy.sparse.csr_matrix(\n (\n test_dataset.data[:, 2],\n (\n test_dataset.data[:, 0].astype(int),\n test_dataset.data[:, 1].astype(int),\n ),\n ),\n shape=(test_dataset.num_total_users, test_dataset.num_total_items),\n )\n\n users_items_recommended = defaultdict(list)\n num_test_users = len(test_users)\n print(f\"Starting {model.name} Training\")\n model.reset(train_dataset)\n print(f\"Ended {model.name} Training\")\n users_num_items_to_recommend_from_test = dict()\n available_users = set()\n for uid in test_users:\n users_num_items_to_recommend_from_test[uid] = np.floor(\n (test_consumption_matrix[uid] > 0).count_nonzero()\n * self.recommend_test_data_rate_limit\n )\n if users_num_items_to_recommend_from_test[uid] > 0:\n available_users |= {uid}\n\n users_num_items_recommended_from_test = defaultdict(int)\n\n history_items_recommended = []\n\n while len(available_users) > 0:\n uid = random.sample(available_users, k=1)[0]\n not_recommended = np.ones(num_total_items, dtype=bool)\n not_recommended[users_items_recommended[uid]] = 0\n items_not_recommended = np.nonzero(not_recommended)[0]\n \n actions, info = model.act(\n (uid, items_not_recommended), self.interaction_size\n )\n best_items = actions[1]\n users_items_recommended[uid].extend(best_items)\n\n for item in best_items:\n history_items_recommended.append((uid, item))\n model.observe(\n None, (uid, item), test_consumption_matrix[uid, item], info\n )\n users_num_items_recommended_from_test[uid] += (\n test_consumption_matrix[uid, item] > 0\n )\n\n if (\n users_num_items_recommended_from_test[uid]\n >= users_num_items_to_recommend_from_test[uid]\n ):\n available_users = available_users - {uid}\n\n return history_items_recommended, None"
] |
[
[
"numpy.unique",
"numpy.nonzero",
"numpy.ones"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sheroze1123/HROM_BIDL
|
[
"7a7efba71d93fecf9be560e920e71cfa737a384c",
"7a7efba71d93fecf9be560e920e71cfa737a384c"
] |
[
"bayesian_inference/muq_old/muq_mod_five_param.py",
"rom/petsc_affine_ROM.py"
] |
[
"import sys; sys.path.append('../')\nsys.path.insert(0,'/home/fenics/Installations/MUQ_INSTALL/lib')\nimport pymuqModeling as mm\nimport numpy as np\nfrom tensorflow.keras.optimizers import Adam, RMSprop, Adadelta\nfrom fom.forward_solve import Fin, get_space\nfrom deep_learning.dl_model import load_parametric_model\n\nclass FOM_forward(mm.PyModPiece):\n \"\"\"\n Solves the thermal fin steady state problem with\n a full order model\n \"\"\"\n def __init__(self, resolution=40, out_type=\"total_avg\"):\n \"\"\" \n INPUTS:\n \n \"\"\"\n V = get_space(resolution)\n dofs = len(V.dofmap().dofs())\n self.solver = Fin(V)\n self.out_type=out_type\n\n if out_type == \"total_avg\":\n out_dim = 1\n elif out_type == \"subfin_avg\":\n out_dim = 5\n elif out_type == \"rand_pt\":\n out_dim = 1\n elif out_type == \"rand_pts\":\n out_dim = 5\n mm.PyModPiece.__init__(self, [5],[out_dim])\n\n def EvaluateImpl(self, inputs):\n \"\"\"\n Performs the forward solve and returns observations.\n \n \"\"\"\n z = inputs[0]\n\n x, y, A, B, C = self.solver.forward_five_param(z)\n output = self.solver.qoi_operator(x)\n self.outputs = [output]\n\nclass ROM_forward(mm.PyModPiece):\n \"\"\"\n Solves the thermal fin steady state problem with \n projection based ROM with a given basis\n \"\"\"\n \n def __init__(self, resolution=40, out_type=\"total_avg\"):\n \"\"\" \n INPUTS:\n \n \"\"\"\n V = get_space(resolution)\n dofs = len(V.dofmap().dofs())\n self.solver = Fin(V)\n self.phi = np.loadtxt('data/basis_five_param.txt',delimiter=\",\")\n self.phi = self.phi[:,0:10]\n self.out_type=out_type\n\n if out_type == \"total_avg\":\n out_dim = 1\n elif out_type == \"subfin_avg\":\n out_dim = 5\n elif out_type == \"rand_pt\":\n out_dim = 1\n elif out_type == \"rand_pts\":\n out_dim = 5\n mm.PyModPiece.__init__(self, [5],[out_dim])\n \n def EvaluateImpl(self, inputs):\n \"\"\"\n Performs the forward solve and returns observations.\n \n \"\"\"\n z = inputs[0]\n\n A_r, B_r, C_r, x_r, y_r = self.solver.r_fwd_no_full_5_param(z, self.phi)\n if self.out_type == \"total_avg\":\n output = np.array([y_r])\n else:\n # The QoI operator determines whether we look at subfin averages\n # or random points on the boundary or domain\n output = self.solver.reduced_qoi_operator(x_r)\n \n self.outputs = [output]\n\nclass DL_ROM_forward(mm.PyModPiece):\n \"\"\"\n Solves the thermal fin steady state problem with \n projection based ROM with a given basis and augments\n QoI prediction with deep learning prediciton.\n \"\"\"\n \n def __init__(self, resolution=40, out_type=\"total_avg\"):\n \"\"\" \n INPUTS:\n \n \"\"\"\n V = get_space(resolution)\n dofs = len(V.dofmap().dofs())\n self.solver = Fin(V)\n self.phi = np.loadtxt('data/basis_five_param.txt',delimiter=\",\")\n self.phi = self.phi[:,0:10]\n self.model = load_parametric_model('relu', Adam, 0.004, 6, 50, 150, 600)\n\n self.out_type=out_type\n\n if out_type == \"total_avg\":\n out_dim = 1\n elif out_type == \"subfin_avg\":\n out_dim = 5\n elif out_type == \"rand_pt\":\n out_dim = 1\n elif out_type == \"rand_pts\":\n out_dim = 5\n \n mm.PyModPiece.__init__(self, [5],[out_dim])\n \n def EvaluateImpl(self, inputs):\n \"\"\"\n Performs the forward solve and returns observations.\n \n \"\"\"\n z = inputs[0]\n A_r, B_r, C_r, x_r, y_r = self.solver.r_fwd_no_full_5_param(z, self.phi)\n e_NN = self.model.predict(z.reshape((1,5)))\n\n if self.out_type == \"total_avg\":\n output = np.array([y_r + e_NN[0,0]])\n else:\n # The QoI operator determines whether we look at subfin averages\n # or random points on the boundary or domain\n output = self.solver.reduced_qoi_operator(x_r) + e_NN[0]\n \n self.outputs = [output]\n",
"import sys\nsys.path.append('../')\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom dolfin import *\nfrom mshr import Rectangle, generate_mesh\nfrom petsc4py import PETSc\n\nfrom tensorflow.keras.backend import get_session, gradients\n# from tensorflow.keras.backend import gradients\nimport tensorflow as tf\n\nfrom fom.thermal_fin import get_space\n\nclass SubFin(SubDomain):\n def __init__(self, subfin_bdry, **kwargs):\n self.y_b = subfin_bdry[0]\n self.is_left = subfin_bdry[1]\n super(SubFin, self).__init__(**kwargs)\n\n def inside(self, x, on_boundary):\n if self.is_left:\n return (between(x[1], (self.y_b, self.y_b+0.75)) and between(x[0], (0.0, 2.5)))\n else:\n return (between(x[1], (self.y_b, self.y_b+0.75)) and between(x[0], (3.5, 6.0)))\n\nclass SubFinBoundary(SubDomain):\n def __init__(self, subfin_bdry, **kwargs):\n self.y_b = subfin_bdry[0]\n self.is_left = subfin_bdry[1]\n super(SubFinBoundary, self).__init__(**kwargs)\n\n def inside(self, x, on_boundary):\n if self.is_left:\n return (on_boundary and between(x[1], (self.y_b, self.y_b+0.75)) \n and between(x[0], (0.0, 2.5)))\n else:\n return (on_boundary and between(x[1], (self.y_b, self.y_b+0.75)) \n and between(x[0], (3.5, 6.0)))\n\nclass CenterFin(SubDomain):\n def inside(self, x, on_boundary):\n return between(x[0], (2.5, 3.5))\n\nclass CenterFinBoundary(SubDomain):\n def inside(self, x, on_boundary):\n return (on_boundary and between(x[0], (2.5, 3.5)) and not (near(x[1], 0.0)))\n\nclass AffineROMFin:\n '''\n A class the implements the heat conduction problem for a thermal fin\n '''\n\n def __init__(self, V, err_model, phi):\n '''\n Initializes a thermal fin instance for a given function space\n\n Arguments:\n V - dolfin FunctionSpace\n '''\n\n self.num_params = 9\n\n self.phi = phi\n (self.n,self.n_r) = self.phi.shape\n\n self.phi_p = PETSc.Mat().createDense([self.n,self.n_r], array=phi)\n self.phi_p.assemblyBegin()\n self.phi_p.assemblyEnd()\n\n self.V = V\n self.dofs = len(V.dofmap().dofs()) \n\n # Currently uses a fixed Biot number\n self.Bi = Constant(0.1)\n\n # Trial and test functions for the weak forms\n self.w = TrialFunction(V)\n self.v = TestFunction(V)\n\n self.w_hat = TestFunction(V)\n self.v_trial = TrialFunction(V)\n\n self.fin1 = SubFin([0.75, True])\n self.fin2 = SubFin([1.75, True])\n self.fin3 = SubFin([2.75, True])\n self.fin4 = SubFin([3.75, True])\n self.fin5 = CenterFin()\n self.fin6 = SubFin([3.75, False])\n self.fin7 = SubFin([2.75, False])\n self.fin8 = SubFin([1.75, False])\n self.fin9 = SubFin([0.75, False])\n\n mesh = V.mesh()\n domains = MeshFunction(\"size_t\", mesh, mesh.topology().dim())\n domains.set_all(0)\n self.fin1.mark(domains, 1)\n self.fin2.mark(domains, 2)\n self.fin3.mark(domains, 3)\n self.fin4.mark(domains, 4)\n self.fin5.mark(domains, 5)\n self.fin6.mark(domains, 6)\n self.fin7.mark(domains, 7)\n self.fin8.mark(domains, 8)\n self.fin9.mark(domains, 9)\n\n # Marking boundaries for boundary conditions\n bottom = CompiledSubDomain(\"near(x[1], side) && on_boundary\", side = 0.0)\n fin1_b = SubFinBoundary([0.75, True])\n fin2_b = SubFin([1.75, True])\n fin3_b = SubFin([2.75, True])\n fin4_b = SubFin([3.75, True])\n fin5_b = CenterFinBoundary()\n fin6_b = SubFin([3.75, False])\n fin7_b = SubFin([2.75, False])\n fin8_b = SubFin([1.75, False])\n fin9_b = SubFin([0.75, False])\n\n boundaries = MeshFunction(\"size_t\", mesh, mesh.topology().dim()-1)\n boundaries.set_all(0)\n fin1_b.mark(boundaries, 1)\n fin2_b.mark(boundaries, 2)\n fin3_b.mark(boundaries, 3)\n fin4_b.mark(boundaries, 4)\n fin5_b.mark(boundaries, 5)\n fin6_b.mark(boundaries, 6)\n fin7_b.mark(boundaries, 7)\n fin8_b.mark(boundaries, 8)\n fin9_b.mark(boundaries, 9)\n bottom.mark(boundaries, 10)\n\n self.dx = Measure('dx', domain=mesh, subdomain_data=domains)\n self.ds = Measure('ds', domain=mesh, subdomain_data=boundaries)\n\n self.fin1_A = assemble(Constant(1.0) * self.dx(1))\n self.fin2_A = assemble(Constant(1.0) * self.dx(2))\n self.fin3_A = assemble(Constant(1.0) * self.dx(3))\n self.fin4_A = assemble(Constant(1.0) * self.dx(4))\n self.fin5_A = assemble(Constant(1.0) * self.dx(5))\n self.fin6_A = assemble(Constant(1.0) * self.dx(6))\n self.fin7_A = assemble(Constant(1.0) * self.dx(7))\n self.fin8_A = assemble(Constant(1.0) * self.dx(8))\n self.fin9_A = assemble(Constant(1.0) * self.dx(9))\n\n # Dummy init for averaged subfin values\n self.averaged_k_s = [Constant(1.0) for i in range(self.num_params)]\n\n self._F = self.averaged_k_s[0] * inner(grad(self.w), grad(self.v)) \\\n * self.dx(1) + \\\n self.Bi * self.v * self.w * self.ds(1)\n for i in range(1,9):\n self._F += self.averaged_k_s[i] * inner(grad(self.w), grad(self.v)) \\\n * self.dx(i+1) + \\\n self.Bi * self.v * self.w * self.ds(i+1)\n self._a = self.v * self.ds(10)\n\n\n # Reduced variables (PETSc)\n self._w_r = PETSc.Vec().createSeq(self.n_r)\n self._A_r = PETSc.Mat()\n self._B_r = PETSc.Vec().createSeq(self.n_r)\n self._C_r = PETSc.Vec().createSeq(self.n_r)\n self.B_p = as_backend_type(assemble(self._a))\n self.ksp = PETSc.KSP().create()\n self.ksp.setType('cg')\n self.ksp.setType('gmres')\n self.psi_p = PETSc.Mat()\n\n self.A = PETScMatrix()\n\n self._adj_F = self.averaged_k_s[0] * inner(grad(self.w_hat), grad(self.v_trial)) \\\n * self.dx(1) + \\\n self.Bi * self.w_hat * self.v_trial * self.ds(1)\n for i in range(1,9):\n self._adj_F += self.averaged_k_s[i] * inner(grad(self.w_hat), grad(self.v_trial)) \\\n * self.dx(i+1) + \\\n self.Bi * self.w_hat * self.v_trial * self.ds(i+1)\n self.A_adj = PETScMatrix()\n\n self.psi = None\n self.data = None\n self.data_ph = tf.placeholder(tf.float32, shape=(9,))\n self.B_obs = self.observation_operator()\n self.B_obs_phi = np.dot(self.B_obs, self.phi)\n\n self.dA_dsigmak = np.zeros((self.num_params, self.n, self.n))\n self.dA_dsigmak_phi = np.zeros((self.num_params, self.n, self.n_r))\n for i in range(self.num_params):\n A_i = assemble(inner(grad(self.w), grad(self.v)) * self.dx(i+1)).array()\n self.dA_dsigmak[i, :, :] = A_i\n self.dA_dsigmak_phi[i, :, :] = np.dot(A_i, self.phi)\n\n self.dl_model = err_model\n\n # Placeholders and precomputed values required for setting up gradients\n self.reduced_fwd_obs = tf.placeholder(tf.float32, shape=(9,))\n self.loss = tf.divide(tf.reduce_sum(tf.square(\n self.data_ph - self.reduced_fwd_obs - self.dl_model.layers[-1].output)), 2)\n self.NN_grad = gradients(self.loss, self.dl_model.input)\n\n self.dL_dsigmak = np.zeros(self.num_params)\n\n\n self.dA_dsigmak_phi = np.zeros((self.num_params, self.dofs, self.phi.shape[1]))\n for i in range(self.num_params):\n self.dA_dsigmak_phi[i, :, :] = np.dot(self.dA_dsigmak[i], self.phi)\n\n self.NN_grad_val = None\n\n # @tf.function\n # def cost_function(self, x_inp, data, y_ROM):\n # y_NN = self.dl_model.predict([x_inp])[0]\n # return tf.divide(tf.reduce_sum(tf.square(data - y_ROM - y_NN)), 2)\n\n\n def forward(self, k):\n '''\n Computes the forward solution given a conductivity field\n by averaging over subfins.\n\n Arguments:\n k : dolfin function - thermal conductivity\n\n Returns:\n w : dolfin function - temperature distribution over the fin \n '''\n\n k_s = self.subfin_avg_op(k)\n\n for i in range(len(k_s)):\n self.averaged_k_s[i].assign(k_s[i])\n\n w = Function(self.V)\n\n solve(self._F == self._a, w) \n\n return w\n\n def forward_reduced(self, k):\n '''\n Computes the forward solution given a conductivity field\n by averaging over subfins and then using a ROM on the resulting system.\n\n Arguments:\n k : dolfin function - thermal conductivity\n phi: numpy array - reduced basis\n\n Returns:\n w : numpy array - reduced solution\n '''\n\n k_s = self.subfin_avg_op(k)\n return self.forward_nine_param_reduced(k_s)\n\n def forward_nine_param_reduced(self, k_s):\n '''\n Given average thermal conductivity values of each subfin,\n returns the reduced forward solve\n '''\n for i in range(len(k_s)):\n self.averaged_k_s[i].assign(k_s[i])\n\n assemble(self._F, tensor=self.A)\n\n # Setup reduced matrices in PETSc\n self.A.mat().matMult(self.phi_p, self.psi_p)\n self.psi_p.transposeMatMult(self.psi_p, self._A_r)\n self.psi_p.multTranspose(self.B_p.vec(), self._B_r)\n\n # Perform reduced solve with KSP\n self.ksp.setOperators(self._A_r)\n self.ksp.solve(self._B_r, self._w_r)\n w_r = self._w_r[:]\n\n return w_r\n\n def qoi(self, w):\n return self.subfin_avg_op(w) \n\n def qoi_reduced(self, w_r):\n # w = Function(self.V)\n # w.vector().set_local(np.dot(self.phi, w_r))\n # return self.subfin_avg_op(w)\n return np.dot(self.B_obs_phi, w_r)\n\n def grad_reduced(self, k):\n w_r = self.forward_reduced(k)\n reduced_fwd_obs = np.dot(self.B_obs_phi, w_r)\n\n reduced_adj_rhs = np.dot(self.B_obs_phi.T, self.data - reduced_fwd_obs)\n\n psi = self.psi_p.getDenseArray()\n A_r = self._A_r.getDenseArray()\n self.ksp.setOperators(self._A_r.transpose())\n self.ksp.solve(reduced_adj_rhs, self._v_r)\n # v_r = np.linalg.solve(A_r.T, reduced_adj_rhs)\n\n psi_v_r = np.dot(psi, v_r)\n\n A_phi_w_r = np.dot(self.dA_dsigmak_phi, w_r).T\n dROM_dk = np.dot(A_phi_w_r, self.B_obs)\n dJ_dk = np.dot(psi_v_r.T, dROM_dk)\n\n J = 0.5 * np.linalg.norm(self.data - reduced_fwd_obs)**2\n\n return dJ_dk, J\n\n def grad_romml(self, k):\n w_r = self.forward_reduced(k)\n e_NN = self.dl_model.predict([[k.vector()[:]]])[0]\n\n reduced_fwd_obs = np.dot(self.B_obs_phi, w_r)\n romml_fwd_obs = reduced_fwd_obs + e_NN\n\n reduced_adj_rhs = np.dot(self.B_obs_phi.T, self.data - romml_fwd_obs)\n\n psi = self.psi_p.getDenseArray()\n A_r = self._A_r.getDenseArray()\n v_r = np.linalg.solve(A_r.T, reduced_adj_rhs)\n\n psi_v_r = np.dot(psi, v_r)\n\n A_phi_w_r = np.dot(self.dA_dsigmak_phi, w_r).T\n dROM_dk = np.dot(A_phi_w_r, self.B_obs)\n f_x_dp_x = np.dot(psi_v_r.T, dROM_dk)\n\n x_inp = [k.vector()[:]]\n session = get_session()\n f_eps_dp_eps = session.run(self.NN_grad, \n feed_dict={self.dl_model.input: x_inp,\n self.reduced_fwd_obs: reduced_fwd_obs,\n self.data_ph: self.data})[0]\n\n loss = session.run(self.loss,\n feed_dict={self.dl_model.input: x_inp,\n self.reduced_fwd_obs: reduced_fwd_obs,\n self.data_ph: self.data})\n\n self.NN_grad_val = f_eps_dp_eps.reshape(f_eps_dp_eps.size)\n grad = f_x_dp_x + self.NN_grad_val\n return grad, loss\n\n def set_reduced_basis(self, phi):\n '''\n Sets the computed trial basis for the ROM system\n\n Arguments:\n phi: numpy array - reduced basis\n '''\n self.phi = phi\n\n def set_data(self, data):\n self.data = data\n\n def set_dl_model(self, model):\n self.dl_model = model\n\n def subfin_avg_op(self, k):\n # Subfin averages\n fin1_avg = assemble(k * self.dx(1))/self.fin1_A \n fin2_avg = assemble(k * self.dx(2))/self.fin2_A \n fin3_avg = assemble(k * self.dx(3))/self.fin3_A \n fin4_avg = assemble(k * self.dx(4))/self.fin4_A \n fin5_avg = assemble(k * self.dx(5))/self.fin5_A\n fin6_avg = assemble(k * self.dx(6))/self.fin6_A \n fin7_avg = assemble(k * self.dx(7))/self.fin7_A \n fin8_avg = assemble(k * self.dx(8))/self.fin8_A \n fin9_avg = assemble(k * self.dx(9))/self.fin9_A \n subfin_avgs = np.array([fin1_avg, fin2_avg, fin3_avg, fin4_avg, fin5_avg, \n fin6_avg, fin7_avg, fin8_avg, fin9_avg])\n # print(\"Subfin averages: {}\".format(subfin_avgs))\n return subfin_avgs\n\n def observation_operator(self):\n z = TestFunction(self.V)\n fin1_avg = assemble(z * self.dx(1))/self.fin1_A \n fin2_avg = assemble(z * self.dx(2))/self.fin2_A \n fin3_avg = assemble(z * self.dx(3))/self.fin3_A \n fin4_avg = assemble(z * self.dx(4))/self.fin4_A \n fin5_avg = assemble(z * self.dx(5))/self.fin5_A\n fin6_avg = assemble(z * self.dx(6))/self.fin6_A \n fin7_avg = assemble(z * self.dx(7))/self.fin7_A \n fin8_avg = assemble(z * self.dx(8))/self.fin8_A \n fin9_avg = assemble(z * self.dx(9))/self.fin9_A \n\n B = np.vstack((\n fin1_avg[:],\n fin2_avg[:],\n fin3_avg[:],\n fin4_avg[:],\n fin5_avg[:],\n fin6_avg[:],\n fin7_avg[:],\n fin8_avg[:],\n fin9_avg[:]))\n\n return B\n"
] |
[
[
"numpy.array",
"numpy.loadtxt"
],
[
"numpy.dot",
"numpy.linalg.solve",
"tensorflow.keras.backend.get_session",
"tensorflow.keras.backend.gradients",
"tensorflow.placeholder",
"numpy.linalg.norm",
"tensorflow.square",
"numpy.array",
"numpy.zeros",
"numpy.vstack"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
aracoara/price_action_teste
|
[
"1bfd1e4f2f2446108832f969a038a3616ba13e4a"
] |
[
"e_web_app_local_function_final_teste.py"
] |
[
"\r\n\r\n## import custom functions\r\nfrom c_price_action_function_teste import pa_long_ativo_func\r\nfrom c_price_action_function_teste import ranking_ativo_func\r\nfrom c_price_action_function_teste import pa_segmentos_temp_func\r\nfrom c_price_action_function_teste import ranking_segmento_func\r\nfrom c_price_action_function_teste import pa_long_func\r\nfrom d_price_holc_function_teste import prices_long_holc_ta\r\nfrom d_price_holc_function_teste import prices_wide_holc_ta\r\nfrom b_prices_function_atualizacao_teste import update_database\r\n\r\n# import libraries\r\nimport pandas as pd\r\nimport cufflinks as cf\r\nimport plotly.express as px\r\nimport plotly.graph_objects as go\r\nimport dash\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nimport dash_bootstrap_components as dbc\r\nfrom datetime import datetime as dt\r\nfrom plotly.subplots import make_subplots\r\nimport datetime as dt \r\nfrom datetime import timedelta, datetime\r\n# import plotly.io as pio\r\n\r\ncf.go_offline()\r\n\r\n# #####################################\r\n# ## import prices database\r\n# ##################################### \r\n\r\n# segmentos = pd.read_csv(\"segmentos_eod.csv\")\r\n# prices_segmento_base = pd.read_csv(\"prices_segmento.csv\")\r\nsegmentos = pd.read_json(\"segmentos_eod - segmentos_eod.json\")\r\n\r\nprices_segmento_base = pd.read_json('prices_segmento_base.json')\r\nprices_segmento_base = update_database(prices_segmento_base)\r\n# prices_segmento_base = pd.read_json(r'prices_segmento_base.json')\r\n\r\n\r\n# #####################################\r\n# ## auxiliary data for global variables\r\n# ##################################### \r\nprices_segmento_base_temp = pd.merge(prices_segmento_base,segmentos,how='left',left_on='ativo',right_on='ativo')\r\nsegmentos_lista2 = prices_segmento_base_temp['segmento_x'].unique()\r\nacoes_lista = prices_segmento_base_temp['ativo'].unique()\r\nsegmentos_lista = prices_segmento_base_temp['segmento_x'].unique() # lista dos segmentos\r\nfim_temp1 = prices_segmento_base_temp['data'].tail(1).iloc[0]\r\nfim_temp2 = dt.datetime.strptime(fim_temp1, '%Y-%m-%d')\r\ninicio_temp2 = fim_temp2 - timedelta(days=59)\r\ninicio_temp = inicio_temp2.strftime('%Y-%m-%d')\r\nfim_temp = fim_temp2.strftime('%Y-%m-%d')\r\n\r\npa_long_ativo = pa_long_ativo_func(inicio_temp,fim_temp,prices_segmento_base_temp)\r\nranking_ativo = ranking_ativo_func(pa_long_ativo)\r\n\r\n\r\npa_segmentos_temp = pa_segmentos_temp_func(segmentos,pa_long_ativo)\r\nranking_segmento = ranking_segmento_func(pa_long_ativo,pa_segmentos_temp)\r\nsegmentos_lista2 = ranking_segmento['segmento'].to_list()\r\npa_long_segmentos = pd.merge(pa_segmentos_temp, ranking_segmento, \r\n how='left', left_on='segmento', right_on='segmento')\r\npa_long = pa_long_func(segmentos,pa_long_ativo, ranking_ativo, ranking_segmento)\r\n\r\npa_long = pa_long.sort_values(by=['ranking_ativo'],ascending=True)\r\nacoes_lista = pa_long['ativo'].unique()\r\n\r\n# dt.datetime.strptime(ult_dt_prices_base, '%Y-%m-%d')\r\n# # #####################################\r\n# # ## prices long and wide\r\n# # ##################################### \r\nprices_long_holc = prices_long_holc_ta(segmentos,prices_segmento_base)\r\nprices_wide_holc = prices_wide_holc_ta(segmentos,prices_long_holc)\r\n\r\npa_wide_holc_indice = prices_wide_holc[prices_wide_holc['segmento']=='indice']\r\npa_wide_holc_ibov = prices_wide_holc[prices_wide_holc['ativo']=='IBOV']\r\n\r\n## dados auxiliares para os indices\r\npa_long_indice = prices_long_holc[prices_long_holc['segmento']=='indice']\r\nindice_lista = pa_long_indice['ativo'].unique()\r\nsegmentos_lista = prices_segmento_base_temp['segmento_x'].unique() # lista dos segmentos'\r\n\r\npa_long_ibov = prices_long_holc[(prices_long_holc['segmento']=='indice')&(prices_long_holc['ativo']=='IBOV')]\r\nult_data2 = prices_long_holc['data'].tail(1).iloc[0]\r\n\r\n\r\n#####################################\r\n## input de data p/ o price action\r\n##################################### \r\n# inicio = '2021-01-11'\r\n# fim = prices_segmento_base_temp['data'].tail(1).iloc[0]\r\n# # fim = '2021-03-12'\r\n# # #####################################\r\n# # ## função price action\r\n# # ##################################### \r\n# pa_long_ativo = pa_long_ativo_func(inicio,fim,prices_segmento_base)\r\n# ranking_ativo = ranking_ativo_func(pa_long_ativo)\r\n# pa_segmentos_temp = pa_segmentos_temp_func(segmentos,pa_long_ativo)\r\n# ranking_segmento = ranking_segmento_func(pa_long_ativo,pa_segmentos_temp)\r\n# pa_long_segmentos = pd.merge(pa_segmentos_temp, ranking_segmento, \r\n# how='left', left_on='segmento', right_on='segmento')\r\n# pa_long = pa_long_func(segmentos,pa_long_ativo, ranking_ativo, ranking_segmento)\r\n\r\n# pa_long = pa_long.sort_values(by=['ranking_ativo'],ascending=True)\r\n# acoes_lista = pa_long['ativo'].unique()\r\n\r\n# # segmentos_lista = prices_segmento_base_temp['segmento_x'].unique() # lista dos segmentos\r\n# segmentos_lista = ranking_segmento['segmento'].unique()\r\n# ## TESTE\r\n# pio.renderers.default = 'browser'\r\n# fig.show()\r\n\r\n\r\n### Dash\r\n\r\n# external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\r\n\r\napp = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP],\r\n meta_tags=[{'name': 'viewport',\r\n 'content': 'width=device-width, initial-scale=1.0'}]\r\n )\r\n\r\napp.layout = dbc.Container([\r\n \r\n html.Div(id='df',\r\n style={'display': 'none'},\r\n # children = 'df'['ativo'].unique(),\r\n ), # Div hidden para armazenar o price action da seleção\r\n\r\n html.Div(id='df2',style={'display': 'none'}), # Div hidden para armazenar o price action de segmentos da seleção\r\n \r\n dbc.Row(\r\n dbc.Col(html.H1(\"Painel Price Action\" , className='text-center text-primary mb-4'), width=12)),\r\n \r\n \r\n dbc.Row([\r\n \r\n dbc.Col([\r\n \r\n html.H2(children = 'Evolução do Bovespa',\r\n style = {\r\n 'text-align': 'center',\r\n 'color':'#456FBV'\r\n } \r\n ), \r\n\r\n dcc.DatePickerRange(\r\n id='DatePickerRange_ind1', # ID to be used for callback\r\n end_date_placeholder_text=\"Return\", # text that appears when no end date chosen\r\n with_portal=False, # if True calendar will open in a full screen overlay portal\r\n first_day_of_week=0, # Display of calendar when open (0 = Sunday)\r\n reopen_calendar_on_clear=True,\r\n is_RTL=False, # True or False for direction of calendar\r\n clearable=True, # whether or not the user can clear the dropdown\r\n number_of_months_shown=1, # number of months shown when calendar is open\r\n # min_date_allowed=dt(2018, 1, 1), # minimum date allowed on the DatePickerRange component\r\n # max_date_allowed=dt(2020, 6, 20), # maximum date allowed on the DatePickerRange component\r\n # initial_visible_month=dt(2020, 5, 1), # the month initially presented when the user opens the calendar\r\n # start_date=dt.date(2020, 11, 3),\r\n start_date=dt.date(2020, 11, 3),\r\n # end_date=dt(2021, 2, 9).date(),\r\n end_date = ult_data2,\r\n display_format='MMM Do, YY', # how selected dates are displayed in the DatePickerRange component.\r\n month_format='MMMM, YYYY', # how calendar headers are displayed when the calendar is opened.\r\n minimum_nights=2, # minimum number of days between start and end date\r\n persistence=True,\r\n persisted_props=['start_date'],\r\n persistence_type='session', # session, local, or memory. Default is 'local'\r\n updatemode='singledate', # singledate or bothdates. Determines when callback is triggered\r\n style={\r\n # 'width': '200px', \r\n 'margin-left': 100, \r\n # 'margin-top': 20, \r\n # 'display':'inline-block'\r\n } \r\n ) , \r\n\r\n html.Br(),\r\n # html.Br(),\r\n # html.Br(),\r\n \r\n dcc.Graph(id='indice1',\r\n className='container', \r\n # style={'maxWidth': '850px'}\r\n ), \r\n ], width={'size':4, 'offset':1, 'order':1},),\r\n\r\n\r\n dbc.Col([\r\n\r\n html.H2(children = 'Evolução de Outros Índices',\r\n style = {\r\n 'text-align': 'center',\r\n 'color':'#456FBV'\r\n } \r\n ), \r\n\r\n dcc.DatePickerRange(\r\n id='DatePickerRange_ind2', # ID to be used for callback\r\n end_date_placeholder_text=\"Return\", # text that appears when no end date chosen\r\n with_portal=False, # if True calendar will open in a full screen overlay portal\r\n first_day_of_week=0, # Display of calendar when open (0 = Sunday)\r\n reopen_calendar_on_clear=True,\r\n is_RTL=False, # True or False for direction of calendar\r\n clearable=True, # whether or not the user can clear the dropdown\r\n number_of_months_shown=1, # number of months shown when calendar is open\r\n # min_date_allowed=dt(2018, 1, 1), # minimum date allowed on the DatePickerRange component\r\n # max_date_allowed=dt(2020, 6, 20), # maximum date allowed on the DatePickerRange component\r\n # initial_visible_month=dt(2020, 5, 1), # the month initially presented when the user opens the calendar\r\n start_date=dt.date(2020, 11, 3),\r\n # end_date=dt(2021, 2, 9).date(),\r\n end_date = ult_data2,\r\n display_format='MMM Do, YY', # how selected dates are displayed in the DatePickerRange component.\r\n month_format='MMMM, YYYY', # how calendar headers are displayed when the calendar is opened.\r\n minimum_nights=2, # minimum number of days between start and end date\r\n persistence=True,\r\n persisted_props=['start_date'],\r\n persistence_type='session', # session, local, or memory. Default is 'local'\r\n updatemode='singledate', # singledate or bothdates. Determines when callback is triggered \r\n style={\r\n # 'width': '200px', \r\n 'margin-left': 100, \r\n # 'margin-top': 20, \r\n 'display':'inline-block'\r\n }\r\n ) , \r\n \r\n\r\n # html.Br(), \r\n\r\n dcc.Dropdown(id='dropdown3', options=[ \r\n {'label': i, 'value': i} for i in indice_lista ## list of unique segments\r\n ],\r\n value=indice_lista[0],\r\n multi=False, placeholder='Filtrar por ...',\r\n style={\r\n # 'width': '200px', \r\n 'margin-left': 50, \r\n # 'margin-top': 20, \r\n # 'display':'inline-block'\r\n } \r\n ),\r\n \r\n # ]), \r\n \r\n dcc.Graph(id='indice2',\r\n className='container', \r\n # style={'maxWidth': '850px'}\r\n ), \r\n\r\n ], width={'size':4, 'offset':1, 'order':1},), \r\n \r\n \r\n \r\n \r\n ], no_gutters=True, justify='start'), # Fechamento da Row evolução do índice e retorno por segmentos\r\n \r\n\r\n\r\n html.H2(children = 'Datas para o Price Action',\r\n style = {\r\n 'text-align': 'center',\r\n 'color':'#456FBV'\r\n } \r\n ),\r\n html.Br(),\r\n\r\n# DataRange do Price Action\r\n dcc.DatePickerRange(\r\n id='DatePickerRange1', # ID to be used for callback\r\n end_date_placeholder_text=\"Return\", # text that appears when no end date chosen\r\n with_portal=False, # if True calendar will open in a full screen overlay portal\r\n first_day_of_week=0, # Display of calendar when open (0 = Sunday)\r\n reopen_calendar_on_clear=True,\r\n is_RTL=False, # True or False for direction of calendar\r\n clearable=True, # whether or not the user can clear the dropdown\r\n number_of_months_shown=1, # number of months shown when calendar is open\r\n # min_date_allowed=dt(2018, 1, 1), # minimum date allowed on the DatePickerRange component\r\n # max_date_allowed=dt(2020, 6, 20), # maximum date allowed on the DatePickerRange component\r\n # initial_visible_month=dt(2020, 5, 1), # the month initially presented when the user opens the calendar\r\n start_date=inicio_temp2,\r\n end_date = fim_temp2,\r\n display_format='MMM Do, YY', # how selected dates are displayed in the DatePickerRange component.\r\n month_format='MMMM, YYYY', # how calendar headers are displayed when the calendar is opened.\r\n minimum_nights=2, # minimum number of days between start and end date\r\n persistence=True,\r\n persisted_props=['start_date'],\r\n persistence_type='session', # session, local, or memory. Default is 'local'\r\n updatemode='singledate', # singledate or bothdates. Determines when callback is triggered\r\n style={\r\n # 'width': '200px', \r\n 'margin-left': 750, \r\n # 'margin-top': 20, \r\n # 'display':'inline-block'\r\n } \r\n ) , \r\n \r\n html.Br(),\r\n html.Br(),\r\n # html.Br(),\r\n \r\n dbc.Row([\r\n \r\n dbc.Col([\r\n \r\n html.H2(children = 'Retorno por segmentos',\r\n style = {\r\n 'text-align': 'center',\r\n 'color':'#456FBV'\r\n } \r\n ),\r\n \r\n dcc.Dropdown(id='dropdown-evolucao-segmento', \r\n options=[{'label': i, 'value': i} for i in segmentos_lista2 ## list of unique segments\r\n ],\r\n value=segmentos_lista2[0],\r\n multi=True, placeholder='Filtrar por ativo...',\r\n style={\r\n # 'width': '200px', \r\n 'margin-left': 50, \r\n # 'margin-top': 20, \r\n # 'display':'inline-block'\r\n } ), \r\n \r\n dbc.Col(dcc.Graph(id='evolucao-segmento')), \r\n \r\n ], width={'size':4, 'offset':1, 'order':1}, ),\r\n \r\n dbc.Col([\r\n \r\n html.H2(children = 'Ativos por Segmentos',\r\n style = {\r\n 'text-align': 'center',\r\n 'color':'#456FBV'\r\n } \r\n ),\r\n \r\n dcc.Dropdown(id='dropdown_ativos_segmentos', options=[ \r\n {'label': i, 'value': i} for i in segmentos_lista2 ## list of unique segments\r\n ],\r\n value=segmentos_lista2[0],\r\n multi=True, placeholder='Filtrar por segmentos...',\r\n style={\r\n # 'width': '200px', \r\n 'margin-left': 50, \r\n # 'margin-top': 20, \r\n # 'display':'inline-block'\r\n } ),\r\n \r\n dcc.Graph(id='retorno_ativos_segmentos'), \r\n \r\n \r\n ] , width={'size':4, 'offset':1, 'order':1}, ),\r\n \r\n \r\n ],no_gutters=True, justify='start'),\r\n \r\n dbc.Row([\r\n \r\n dbc.Col([\r\n\r\n # Price Action: seleção de ativos\r\n\r\n html.H2(children = 'Seleção de ativos',\r\n style = {\r\n 'text-align': 'center',\r\n 'color':'#456FBV'\r\n } \r\n ),\r\n \r\n dcc.Dropdown(id='dropdown_selecao_ativos', \r\n options=[{'label': i, 'value': i} for i in acoes_lista ## list of unique segments\r\n ],\r\n value=acoes_lista[0],\r\n multi=True, placeholder='Filtrar por ativo...',\r\n style={\r\n # 'width': '200px', \r\n 'margin-left': 50, \r\n # 'margin-top': 20, \r\n # 'display':'inline-block'\r\n } ), \r\n \r\n dbc.Col(dcc.Graph(id='retorno_selecao_ativos')), \r\n\r\n \r\n ], width={'size':4, 'offset':1, 'order':1},), \r\n # xs=12, sm=12, md=12, lg=5, xl=5 \r\n \r\n \r\n dbc.Col([\r\n\r\n html.H2(children = 'Evolução do retorno da volatilidade',\r\n style = {\r\n 'text-align': 'center',\r\n 'color':'#456FBV'\r\n } \r\n ),\r\n \r\n dcc.Dropdown(id='dropdown-retorno-volatilidade', options=[ \r\n {'label': i, 'value': i} for i in acoes_lista ## list of unique segments\r\n ],\r\n value=acoes_lista[0],\r\n multi=False, placeholder='Filtrar por ativo...',\r\n style={\r\n # 'width': '200px', \r\n 'margin-left': 50, \r\n # 'margin-top': 20, \r\n # 'display':'inline-block'\r\n } ), \r\n \r\n dbc.Col(dcc.Graph(id='retorno-volatilidade')),\r\n \r\n ], width={'size':4, 'offset':1, 'order':1},),\r\n \r\n ] , no_gutters=True, justify='start'),\r\n\r\n html.Br(),\r\n html.Br(),\r\n \r\n dbc.Row([ \r\n\r\n dbc.Col([ \r\n \r\n html.H2(children = 'Evolução de preços',\r\n style = {\r\n 'margin-left': 100, \r\n # 'margin-top': 20, \r\n 'display':'inline-block'\r\n },), \r\n dcc.DatePickerRange(\r\n id='DatePickerRange2', # ID to be used for callback\r\n end_date_placeholder_text=\"Return\", # text that appears when no end date chosen\r\n with_portal=False, # if True calendar will open in a full screen overlay portal\r\n first_day_of_week=0, # Display of calendar when open (0 = Sunday)\r\n reopen_calendar_on_clear=True,\r\n is_RTL=False, # True or False for direction of calendar\r\n clearable=True, # whether or not the user can clear the dropdown\r\n number_of_months_shown=1, # number of months shown when calendar is open\r\n # min_date_allowed=dt(2018, 1, 1), # minimum date allowed on the DatePickerRange component\r\n # max_date_allowed=dt(2020, 6, 20), # maximum date allowed on the DatePickerRange component\r\n # initial_visible_month=dt(2020, 5, 1), # the month initially presented when the user opens the calendar\r\n start_date=inicio_temp2,\r\n end_date = fim_temp2,\r\n display_format='MMM Do, YY', # how selected dates are displayed in the DatePickerRange component.\r\n month_format='MMMM, YYYY', # how calendar headers are displayed when the calendar is opened.\r\n minimum_nights=2, # minimum number of days between start and end date\r\n persistence=True,\r\n persisted_props=['start_date'],\r\n persistence_type='session', # session, local, or memory. Default is 'local'\r\n updatemode='singledate', # singledate or bothdates. Determines when callback is triggered \r\n style={\r\n # 'width': '200px', \r\n 'margin-left': 100, \r\n # 'margin-top': 20, \r\n 'display':'inline-block'\r\n }\r\n ) , \r\n \r\n # ]),\r\n\r\n html.Br(),\r\n \r\n # dbc.Row([\r\n dcc.Dropdown(id='dropdown2', options=[ \r\n {'label': i, 'value': i} for i in acoes_lista ## list of unique segments\r\n ],\r\n value=acoes_lista[0],\r\n multi=False, placeholder='Filtrar por ...',\r\n style={\r\n # 'width': '200px', \r\n 'margin-left': 40, \r\n # 'margin-top': 20, \r\n # 'display':'inline-block'\r\n } \r\n ),\r\n \r\n # ]), \r\n \r\n dcc.Graph(id='evolucao',\r\n className='container', \r\n # style={'maxWidth': '850px'}\r\n ),\r\n \r\n \r\n ], width={'size':4, 'offset':1, 'order':1},),\r\n\r\n ] , no_gutters=True, justify='start'),\r\n\r\n ] ,fluid=True) # fechamento do dbc.Container\r\n\r\n## callback que retorna o price action de acordo com a seleção de datas\r\[email protected](dash.dependencies.Output('df', 'children'),\r\n [dash.dependencies.Input('DatePickerRange1', 'start_date'),\r\n dash.dependencies.Input('DatePickerRange1', 'end_date')])\r\n\r\n\r\n\r\ndef price_action(inicio,fim):\r\n \r\n pa_long_ativo = pa_long_ativo_func(inicio,fim,prices_segmento_base)\r\n ranking_ativo = ranking_ativo_func(pa_long_ativo)\r\n pa_segmentos_temp = pa_segmentos_temp_func(segmentos,pa_long_ativo)\r\n ranking_segmento = ranking_segmento_func(pa_long_ativo,pa_segmentos_temp)\r\n pa_long_segmentos = pd.merge(pa_segmentos_temp, ranking_segmento, \r\n how='left', left_on='segmento', right_on='segmento')\r\n pa_long = pa_long_func(segmentos,pa_long_ativo, ranking_ativo, ranking_segmento)\r\n\r\n pa_long = pa_long.sort_values(by=['ranking_ativo'],ascending=True)\r\n \r\n return pa_long.to_json(date_format='iso', orient='split')\r\n\r\n\r\n## callback que retorna o price action de acordo com a seleção de datas\r\[email protected](dash.dependencies.Output('df2', 'children'),\r\n [dash.dependencies.Input('DatePickerRange1', 'start_date'),\r\n dash.dependencies.Input('DatePickerRange1', 'end_date')])\r\n\r\ndef price_action_segmentos(inicio,fim):\r\n \r\n pa_long_ativo = pa_long_ativo_func(inicio,fim,prices_segmento_base)\r\n ranking_ativo = ranking_ativo_func(pa_long_ativo)\r\n pa_segmentos_temp = pa_segmentos_temp_func(segmentos,pa_long_ativo)\r\n ranking_segmento = ranking_segmento_func(pa_long_ativo,pa_segmentos_temp)\r\n pa_long_segmentos = pd.merge(pa_segmentos_temp, ranking_segmento, \r\n how='left', left_on='segmento', right_on='segmento')\r\n \r\n \r\n return pa_long_segmentos.to_json(date_format='iso', orient='split')\r\n\r\n\r\n# ## callback que retorna o price action de acordo com a seleção de datas\r\n# @app.callback(dash.dependencies.Output('acoes_lista2', 'children'),\r\n# [dash.dependencies.Input('DatePickerRange1', 'start_date'),\r\n# dash.dependencies.Input('DatePickerRange1', 'end_date')])\r\n\r\n# def acao_lista(inicio,fim):\r\n \r\n# pa_long_ativo = pa_long_ativo_func(inicio,fim,prices_segmento_base)\r\n# ranking_ativo = ranking_ativo_func(pa_long_ativo)\r\n# pa_segmentos_temp = pa_segmentos_temp_func(segmentos,pa_long_ativo)\r\n# ranking_segmento = ranking_segmento_func(pa_long_ativo,pa_segmentos_temp)\r\n# pa_long_segmentos = pd.merge(pa_segmentos_temp, ranking_segmento, \r\n# how='left', left_on='segmento', right_on='segmento')\r\n# pa_long = pa_long_func(segmentos,pa_long_ativo, ranking_ativo, ranking_segmento)\r\n\r\n# pa_long = pa_long.sort_values(by=['ranking_ativo'],ascending=True)\r\n# acoes_lista2 = pa_long['ativo'].unique()\r\n \r\n# return acoes_lista2.to_json(date_format='iso', orient='split')\r\n\r\n# pa_long = pa_long\r\n\r\n# Price Action: Seleção de Ativos por Segmentos\r\[email protected](dash.dependencies.Output('retorno_ativos_segmentos', 'figure'),\r\n dash.dependencies.Input('dropdown_ativos_segmentos', 'value'),\r\n dash.dependencies.Input('df', 'children'))\r\n\r\n\r\ndef update_graph(value_segmento_ativos,df):\r\n if type(value_segmento_ativos)!=str:\r\n pa_long = pd.read_json(df, orient='split')\r\n pa_ativos_segmentos = pa_long[(pa_long['segmento'].isin(value_segmento_ativos))&(pa_long['tipo']=='Adj Close') ]\r\n pa_ativos_segmentos.sort_values(by=['data'],inplace=True)\r\n else:\r\n pa_long = pd.read_json(df, orient='split')\r\n pa_ativos_segmentos = pa_long[(pa_long['segmento']==value_segmento_ativos)&(pa_long['tipo']=='Adj Close')]\r\n pa_ativos_segmentos.sort_values(by=['data'],inplace=True)\r\n \r\n fig_pa_ativos_segmentos = px.line(pa_ativos_segmentos,x='data', y='rentabilidade', color='ativo', width=800, height=600 )\r\n \r\n fig_pa_ativos_segmentos.update_xaxes(\r\n type='category',\r\n tickangle = -45)\r\n \r\n \r\n return fig_pa_ativos_segmentos\r\n\r\n## Evolução do retorno da volatilidade\r\[email protected](dash.dependencies.Output('retorno-volatilidade','figure'),\r\n dash.dependencies.Input('dropdown-retorno-volatilidade', 'value'),\r\n dash.dependencies.Input('df', 'children'))\r\n\r\ndef update_graph(value_volatilidade,df):\r\n \r\n if type(value_volatilidade)!=str:\r\n pa_long = pd.read_json(df, orient='split')\r\n retorno_volatilidade_temp1 = pa_long[(pa_long['ativo'].isin(value_volatilidade)) ]\r\n else:\r\n pa_long = pd.read_json(df, orient='split')\r\n retorno_volatilidade_temp1 = pa_long[(pa_long['ativo']==value_volatilidade)]\r\n \r\n x = retorno_volatilidade_temp1[retorno_volatilidade_temp1['tipo']=='low adj'][['data','rentabilidade']]\r\n y = retorno_volatilidade_temp1[retorno_volatilidade_temp1['tipo']=='high adj'][['data','rentabilidade']]\r\n retorno_volatilidade = pd.merge(x,y,left_on=\"data\",right_on=\"data\")\r\n retorno_volatilidade.sort_values(by=['data'],inplace=True)\r\n \r\n fig_retorno_volatilidade = go.Figure()\r\n \r\n fig_retorno_volatilidade.add_trace(go.Scatter(x=retorno_volatilidade['data'], y=retorno_volatilidade['rentabilidade_x'],\r\n fill=None,\r\n mode='lines',\r\n line_color='indigo',\r\n ))\r\n \r\n fig_retorno_volatilidade.add_trace(go.Scatter(x=retorno_volatilidade['data'], y=retorno_volatilidade['rentabilidade_y'],\r\n fill='tonexty', # fill area between trace0 and trace1\r\n mode='lines', line_color='indigo'))\r\n\r\n fig_retorno_volatilidade.update_layout(\r\n dict(\r\n xaxis = dict(type=\"category\", tickangle = -45),\r\n width=800, height=600)\r\n )\r\n \r\n return fig_retorno_volatilidade\r\n\r\n## Price Action: Seleção de Ativos\r\[email protected](dash.dependencies.Output('retorno_selecao_ativos', 'figure'),\r\n dash.dependencies.Input('dropdown_selecao_ativos', 'value'),\r\n dash.dependencies.Input('df', 'children'))\r\n\r\ndef update_graph(value_selecao_ativos,df):\r\n\r\n if type(value_selecao_ativos)!=str:\r\n pa_long = pd.read_json(df, orient='split')\r\n price_action_segmentos_ativos = pa_long[(pa_long['ativo'].isin(value_selecao_ativos))&(pa_long['tipo']=='Adj Close') ]\r\n price_action_segmentos_ativos.sort_values(by=['data'],inplace=True)\r\n else:\r\n pa_long = pd.read_json(df, orient='split')\r\n price_action_segmentos_ativos = pa_long[(pa_long['ativo']==value_selecao_ativos)&(pa_long['tipo']=='Adj Close')]\r\n price_action_segmentos_ativos.sort_values(by=['data'],inplace=True)\r\n \r\n fig_pa_segmentos_ativos = px.line(price_action_segmentos_ativos,x='data', y='rentabilidade', color='ativo', width=800, height=600 )\r\n # fig_pa_segmentos_ativos.sort_values(by=['data'],inplace=True)\r\n \r\n \r\n fig_pa_segmentos_ativos.update_xaxes(\r\n type='category',\r\n tickangle = -45)\r\n \r\n return fig_pa_segmentos_ativos\r\n\r\n## Evolução do retorno dos segmentos\r\[email protected](dash.dependencies.Output('evolucao-segmento', 'figure'),\r\n dash.dependencies.Input('dropdown-evolucao-segmento', 'value'),\r\n dash.dependencies.Input('df2', 'children'))\r\n\r\ndef update_graph(value_evolucao_segmento,df2):\r\n if type(value_evolucao_segmento)!=str:\r\n pa_long_segmentos = pd.read_json(df2, orient='split')\r\n evolucao_segmento = pa_long_segmentos[pa_long_segmentos['segmento'].isin(value_evolucao_segmento)]\r\n evolucao_segmento.sort_values(by=['data'],inplace=True) \r\n else:\r\n pa_long_segmentos = pd.read_json(df2, orient='split')\r\n evolucao_segmento = pa_long_segmentos[pa_long_segmentos['segmento']==value_evolucao_segmento]\r\n evolucao_segmento.sort_values(by=['data'],inplace=True) \r\n \r\n fig_evolucao_segmento = px.line(evolucao_segmento,x='data', y='rentabilidade', color='segmento', width=800, height=600 )\r\n \r\n fig_evolucao_segmento.update_xaxes(\r\n type='category',\r\n tickangle = -45)\r\n \r\n return fig_evolucao_segmento\r\n\r\n## indices2\r\[email protected](\r\n dash.dependencies.Output('indice2', 'figure'),\r\n [dash.dependencies.Input('dropdown3', 'value'),\r\n dash.dependencies.Input('DatePickerRange_ind2', 'start_date'),\r\n dash.dependencies.Input('DatePickerRange_ind2', 'end_date')]\r\n )\r\n\r\ndef update_graph(value2,start_date2, end_date2):\r\n \r\n\r\n prices_wide_holc_temp1 = pa_wide_holc_indice[(pa_wide_holc_indice['data']>=start_date2) &\r\n (pa_wide_holc_indice['data']<=end_date2)] \r\n \r\n prices_wide_holc_temp1.sort_values(by=['data'],inplace=True)\r\n \r\n if type(value2)!=str:\r\n prices_wide_holc_temp2 = prices_wide_holc_temp1[prices_wide_holc_temp1['ativo'].isin(value2)]\r\n else:\r\n prices_wide_holc_temp2 = prices_wide_holc_temp1[prices_wide_holc_temp1['ativo']==value2] \r\n\r\n fig = make_subplots(vertical_spacing = 0, rows=4, cols=1, row_heights=[0.8, 0.15, 0.15, 0.15])\r\n\r\n fig.add_trace(go.Candlestick(x=prices_wide_holc_temp2['data'],\r\n open=prices_wide_holc_temp2['open adj'],\r\n high=prices_wide_holc_temp2['high adj'],\r\n low=prices_wide_holc_temp2['low adj'],\r\n close=prices_wide_holc_temp2['Adj Close'],\r\n name='Preço Ajustado'))\r\n\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_temp2['data'],\r\n y=prices_wide_holc_temp2['ema_7'],\r\n mode='lines',\r\n line = dict(color='purple', width=2),\r\n name='EMA 7 dias'))\r\n\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_temp2['data'],\r\n y=prices_wide_holc_temp2['ema_21'],\r\n mode='lines',\r\n line = dict(color='black', width=2),\r\n name='EMA 21 dias'))\r\n\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_temp2['data'], y = prices_wide_holc_temp2['ppo_line'], name='ppo line'), row=2, col=1)\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_temp2['data'], y = prices_wide_holc_temp2['ppo_signal'], name='ppo signal'), row=2, col=1)\r\n fig.add_trace(go.Bar(x=prices_wide_holc_temp2['data'], y = prices_wide_holc_temp2['ppo_hist'], name='ppo hist'), row=3, col=1)\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_temp2['data'], y = prices_wide_holc_temp2['rsi'], name='rsi'), row=4, col=1)\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_temp2['data'], y = prices_wide_holc_temp2['low_rsi'], name='low rsi'), row=4, col=1)\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_temp2['data'], y = prices_wide_holc_temp2['high_rsi'], name='high rsi',\r\n fill='tonexty', mode='lines', line=dict(width=0.5, color='rgb(222, 196, 255)', dash='dash')), row=4, col=1)\r\n\r\n fig.update_layout(xaxis_rangeslider_visible=False,\r\n xaxis=dict(zerolinecolor='black', showticklabels=False, type=\"category\"),\r\n xaxis2=dict(showticklabels=False, type=\"category\"),\r\n xaxis3=dict(showticklabels=False, type=\"category\"),\r\n width=800, height=600\r\n )\r\n\r\n fig.update_xaxes(showline=True, linewidth=1, linecolor='black', mirror=False)\r\n \r\n return fig\r\n\r\n## indices1\r\[email protected](\r\n dash.dependencies.Output('indice1', 'figure'),\r\n [dash.dependencies.Input('DatePickerRange_ind1', 'start_date'),\r\n dash.dependencies.Input('DatePickerRange_ind1', 'end_date')]\r\n )\r\n\r\ndef update_graph(start_date, end_date):\r\n \r\n\r\n prices_wide_holc_ibov_fig = pa_wide_holc_ibov[(pa_wide_holc_ibov['data']>=start_date) &\r\n (pa_wide_holc_ibov['data']<=end_date)]\r\n prices_wide_holc_ibov_fig.sort_values(by=['data'],ascending=True) \r\n\r\n fig = make_subplots(vertical_spacing = 0, rows=4, cols=1, row_heights=[0.8, 0.15, 0.15, 0.15])\r\n\r\n fig.add_trace(go.Candlestick(x=prices_wide_holc_ibov_fig['data'],\r\n open=prices_wide_holc_ibov_fig['open adj'],\r\n high=prices_wide_holc_ibov_fig['high adj'],\r\n low=prices_wide_holc_ibov_fig['low adj'],\r\n close=prices_wide_holc_ibov_fig['Adj Close'],\r\n name='Preço Ajustado'))\r\n\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_ibov_fig['data'],\r\n y=prices_wide_holc_ibov_fig['ema_7'],\r\n mode='lines',\r\n line = dict(color='purple', width=2),\r\n name='EMA 7 dias'))\r\n\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_ibov_fig['data'],\r\n y=prices_wide_holc_ibov_fig['ema_21'],\r\n mode='lines',\r\n line = dict(color='black', width=2),\r\n name='EMA 21 dias'))\r\n\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_ibov_fig['data'], y = prices_wide_holc_ibov_fig['ppo_line'], name='ppo line'), row=2, col=1)\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_ibov_fig['data'], y = prices_wide_holc_ibov_fig['ppo_signal'], name='ppo signal'), row=2, col=1)\r\n fig.add_trace(go.Bar(x=prices_wide_holc_ibov_fig['data'], y = prices_wide_holc_ibov_fig['ppo_hist'], name='ppo hist'), row=3, col=1)\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_ibov_fig['data'], y = prices_wide_holc_ibov_fig['rsi'], name='rsi'), row=4, col=1)\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_ibov_fig['data'], y = prices_wide_holc_ibov_fig['low_rsi'], name='low rsi'), row=4, col=1)\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_ibov_fig['data'], y = prices_wide_holc_ibov_fig['high_rsi'], name='high rsi',\r\n fill='tonexty', mode='lines', line=dict(width=0.5, color='rgb(222, 196, 255)', dash='dash')), row=4, col=1)\r\n\r\n fig.update_layout(xaxis_rangeslider_visible=False,\r\n xaxis=dict(zerolinecolor='black', showticklabels=False, type=\"category\"),\r\n xaxis2=dict(showticklabels=False, type=\"category\"),\r\n xaxis3=dict(showticklabels=False, type=\"category\"),\r\n width=800, height=600\r\n )\r\n\r\n fig.update_xaxes(showline=True, linewidth=1, linecolor='black', mirror=False)\r\n \r\n return fig\r\n\r\n## Evolução de preço por ativo\r\[email protected](\r\n dash.dependencies.Output('evolucao', 'figure'),\r\n [dash.dependencies.Input('dropdown2', 'value'),\r\n dash.dependencies.Input('DatePickerRange2', 'start_date'),\r\n dash.dependencies.Input('DatePickerRange2', 'end_date')]\r\n )\r\n\r\ndef update_graph(value2,start_date2, end_date2):\r\n\r\n prices_wide_holc_temp1 = prices_wide_holc[(prices_wide_holc['data']>=start_date2) &\r\n (prices_wide_holc['data']<=end_date2)]\r\n\r\n prices_wide_holc_temp1.sort_values(by=['data'],inplace=True) \r\n \r\n if type(value2)!=str:\r\n prices_wide_holc_temp2 = prices_wide_holc_temp1[prices_wide_holc_temp1['ativo'].isin(value2)]\r\n else:\r\n prices_wide_holc_temp2 = prices_wide_holc_temp1[prices_wide_holc_temp1['ativo']==value2] \r\n\r\n fig = make_subplots(vertical_spacing = 0, rows=4, cols=1, row_heights=[0.8, 0.15, 0.15, 0.15])\r\n\r\n fig.add_trace(go.Candlestick(x=prices_wide_holc_temp2['data'],\r\n open=prices_wide_holc_temp2['open adj'],\r\n high=prices_wide_holc_temp2['high adj'],\r\n low=prices_wide_holc_temp2['low adj'],\r\n close=prices_wide_holc_temp2['Adj Close'],\r\n name='Preço Ajustado'))\r\n\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_temp2['data'],\r\n y=prices_wide_holc_temp2['ema_7'],\r\n mode='lines',\r\n line = dict(color='purple', width=2),\r\n name='EMA 7 dias'))\r\n\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_temp2['data'],\r\n y=prices_wide_holc_temp2['ema_21'],\r\n mode='lines',\r\n line = dict(color='black', width=2),\r\n name='EMA 21 dias'))\r\n\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_temp2['data'], y = prices_wide_holc_temp2['ppo_line'], name='ppo line'), row=2, col=1)\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_temp2['data'], y = prices_wide_holc_temp2['ppo_signal'], name='ppo signal'), row=2, col=1)\r\n fig.add_trace(go.Bar(x=prices_wide_holc_temp2['data'], y = prices_wide_holc_temp2['ppo_hist'], name='ppo hist'), row=3, col=1)\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_temp2['data'], y = prices_wide_holc_temp2['rsi'], name='rsi'), row=4, col=1)\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_temp2['data'], y = prices_wide_holc_temp2['low_rsi'], name='low rsi'), row=4, col=1)\r\n fig.add_trace(go.Scatter(x=prices_wide_holc_temp2['data'], y = prices_wide_holc_temp2['high_rsi'], name='high rsi',\r\n fill='tonexty', mode='lines', line=dict(width=0.5, color='rgb(222, 196, 255)', dash='dash')), row=4, col=1)\r\n\r\n fig.update_layout(xaxis_rangeslider_visible=False,\r\n xaxis=dict(zerolinecolor='black', showticklabels=False, type=\"category\"),\r\n xaxis2=dict(showticklabels=False, type=\"category\"),\r\n xaxis3=dict(showticklabels=False, type=\"category\"),\r\n width=1200, height=800\r\n )\r\n\r\n fig.update_xaxes(showline=True, linewidth=1, linecolor='black', mirror=False)\r\n \r\n return fig\r\n\r\nif __name__ == '__main__':\r\n app.run_server(debug=False, dev_tools_ui=False, port=8054)\r\n\r\n"
] |
[
[
"pandas.merge",
"pandas.read_json"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
JMichaelStringer/NeMo
|
[
"b5b29a69ccb0ec3d8c9ace2f33872ee99858a559"
] |
[
"nemo/collections/asr/modules/conv_asr.py"
] |
[
"# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom collections import OrderedDict\nfrom dataclasses import dataclass, field\nfrom typing import List, Optional, Union\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom omegaconf import MISSING, ListConfig, OmegaConf\n\nfrom nemo.collections.asr.parts.submodules.jasper import (\n JasperBlock,\n MaskedConv1d,\n ParallelBlock,\n SqueezeExcite,\n init_weights,\n jasper_activations,\n)\nfrom nemo.collections.asr.parts.submodules.tdnn_attention import (\n AttentivePoolLayer,\n StatsPoolLayer,\n TDNNModule,\n TDNNSEModule,\n)\nfrom nemo.core.classes.common import typecheck\nfrom nemo.core.classes.exportable import Exportable\nfrom nemo.core.classes.module import NeuralModule\nfrom nemo.core.neural_types import (\n AcousticEncodedRepresentation,\n LengthsType,\n LogitsType,\n LogprobsType,\n NeuralType,\n SpectrogramType,\n)\nfrom nemo.utils import logging\n\n__all__ = ['ConvASRDecoder', 'ConvASREncoder', 'ConvASRDecoderClassification']\n\n\nclass ConvASREncoder(NeuralModule, Exportable):\n \"\"\"\n Convolutional encoder for ASR models. With this class you can implement JasperNet and QuartzNet models.\n\n Based on these papers:\n https://arxiv.org/pdf/1904.03288.pdf\n https://arxiv.org/pdf/1910.10261.pdf\n \"\"\"\n\n def _prepare_for_export(self, **kwargs):\n m_count = 0\n for m in self.modules():\n if isinstance(m, MaskedConv1d):\n if self._rnnt_export:\n pass\n else:\n m.use_mask = False\n m_count += 1\n if isinstance(m, SqueezeExcite):\n m._se_pool_step = m._se_pool_step_export\n\n Exportable._prepare_for_export(self, **kwargs)\n logging.warning(f\"Turned off {m_count} masked convolutions\")\n\n def input_example(self):\n \"\"\"\n Generates input examples for tracing etc.\n Returns:\n A tuple of input examples.\n \"\"\"\n input_example = torch.randn(1, self._feat_in, 8192).to(next(self.parameters()).device)\n lens = torch.randint(0, input_example.shape[-1], size=(input_example.shape[0],))\n\n if self._rnnt_export:\n return tuple([input_example, lens])\n else:\n return tuple([input_example])\n\n @property\n def disabled_deployment_input_names(self):\n \"\"\"Implement this method to return a set of input names disabled for export\"\"\"\n if self._rnnt_export:\n return set([])\n else:\n return set([\"length\"])\n\n @property\n def disabled_deployment_output_names(self):\n \"\"\"Implement this method to return a set of output names disabled for export\"\"\"\n if self._rnnt_export:\n return set([])\n else:\n return set([\"encoded_lengths\"])\n\n def save_to(self, save_path: str):\n pass\n\n @classmethod\n def restore_from(cls, restore_path: str):\n pass\n\n @property\n def input_types(self):\n \"\"\"Returns definitions of module input ports.\n \"\"\"\n return OrderedDict(\n {\n \"audio_signal\": NeuralType(('B', 'D', 'T'), SpectrogramType()),\n \"length\": NeuralType(tuple('B'), LengthsType()),\n }\n )\n\n @property\n def output_types(self):\n \"\"\"Returns definitions of module output ports.\n \"\"\"\n return OrderedDict(\n {\n \"outputs\": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()),\n \"encoded_lengths\": NeuralType(tuple('B'), LengthsType()),\n }\n )\n\n def __init__(\n self,\n jasper,\n activation: str,\n feat_in: int,\n normalization_mode: str = \"batch\",\n residual_mode: str = \"add\",\n norm_groups: int = -1,\n conv_mask: bool = True,\n frame_splicing: int = 1,\n init_mode: Optional[str] = 'xavier_uniform',\n quantize: bool = False,\n ):\n super().__init__()\n if isinstance(jasper, ListConfig):\n jasper = OmegaConf.to_container(jasper)\n\n activation = jasper_activations[activation]()\n\n # If the activation can be executed in place, do so.\n if hasattr(activation, 'inplace'):\n activation.inplace = True\n\n feat_in = feat_in * frame_splicing\n\n self._feat_in = feat_in\n\n residual_panes = []\n encoder_layers = []\n self.dense_residual = False\n for lcfg in jasper:\n dense_res = []\n if lcfg.get('residual_dense', False):\n residual_panes.append(feat_in)\n dense_res = residual_panes\n self.dense_residual = True\n groups = lcfg.get('groups', 1)\n separable = lcfg.get('separable', False)\n heads = lcfg.get('heads', -1)\n residual_mode = lcfg.get('residual_mode', residual_mode)\n se = lcfg.get('se', False)\n se_reduction_ratio = lcfg.get('se_reduction_ratio', 8)\n se_context_window = lcfg.get('se_context_size', -1)\n se_interpolation_mode = lcfg.get('se_interpolation_mode', 'nearest')\n kernel_size_factor = lcfg.get('kernel_size_factor', 1.0)\n stride_last = lcfg.get('stride_last', False)\n future_context = lcfg.get('future_context', -1)\n encoder_layers.append(\n JasperBlock(\n feat_in,\n lcfg['filters'],\n repeat=lcfg['repeat'],\n kernel_size=lcfg['kernel'],\n stride=lcfg['stride'],\n dilation=lcfg['dilation'],\n dropout=lcfg['dropout'],\n residual=lcfg['residual'],\n groups=groups,\n separable=separable,\n heads=heads,\n residual_mode=residual_mode,\n normalization=normalization_mode,\n norm_groups=norm_groups,\n activation=activation,\n residual_panes=dense_res,\n conv_mask=conv_mask,\n se=se,\n se_reduction_ratio=se_reduction_ratio,\n se_context_window=se_context_window,\n se_interpolation_mode=se_interpolation_mode,\n kernel_size_factor=kernel_size_factor,\n stride_last=stride_last,\n future_context=future_context,\n quantize=quantize,\n )\n )\n feat_in = lcfg['filters']\n\n self._feat_out = feat_in\n\n self.encoder = torch.nn.Sequential(*encoder_layers)\n self.apply(lambda x: init_weights(x, mode=init_mode))\n\n # Flag needed for RNNT export support\n self._rnnt_export = False\n\n @typecheck()\n def forward(self, audio_signal, length=None):\n s_input, length = self.encoder(([audio_signal], length))\n if length is None:\n return s_input[-1]\n\n return s_input[-1], length\n\n\nclass ParallelConvASREncoder(NeuralModule, Exportable):\n \"\"\"\n Convolutional encoder for ASR models with parallel blocks. CarneliNet can be implemented with this class.\n \"\"\"\n\n def _prepare_for_export(self):\n m_count = 0\n for m in self.modules():\n if isinstance(m, MaskedConv1d):\n m.use_mask = False\n m_count += 1\n logging.warning(f\"Turned off {m_count} masked convolutions\")\n\n def input_example(self):\n \"\"\"\n Generates input examples for tracing etc.\n Returns:\n A tuple of input examples.\n \"\"\"\n input_example = torch.randn(16, self._feat_in, 256).to(next(self.parameters()).device)\n return tuple([input_example])\n\n @property\n def disabled_deployment_input_names(self):\n \"\"\"Implement this method to return a set of input names disabled for export\"\"\"\n return set([\"length\"])\n\n @property\n def disabled_deployment_output_names(self):\n \"\"\"Implement this method to return a set of output names disabled for export\"\"\"\n return set([\"encoded_lengths\"])\n\n def save_to(self, save_path: str):\n pass\n\n @classmethod\n def restore_from(cls, restore_path: str):\n pass\n\n @property\n def input_types(self):\n \"\"\"Returns definitions of module input ports.\n \"\"\"\n return OrderedDict(\n {\n \"audio_signal\": NeuralType(('B', 'D', 'T'), SpectrogramType()),\n \"length\": NeuralType(tuple('B'), LengthsType()),\n }\n )\n\n @property\n def output_types(self):\n \"\"\"Returns definitions of module output ports.\n \"\"\"\n return OrderedDict(\n {\n \"outputs\": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()),\n \"encoded_lengths\": NeuralType(tuple('B'), LengthsType()),\n }\n )\n\n def __init__(\n self,\n jasper,\n activation: str,\n feat_in: int,\n normalization_mode: str = \"batch\",\n residual_mode: str = \"add\",\n norm_groups: int = -1,\n conv_mask: bool = True,\n frame_splicing: int = 1,\n init_mode: Optional[str] = 'xavier_uniform',\n aggregation_mode: Optional[str] = None,\n quantize: bool = False,\n ):\n super().__init__()\n if isinstance(jasper, ListConfig):\n jasper = OmegaConf.to_container(jasper)\n\n activation = jasper_activations[activation]()\n feat_in = feat_in * frame_splicing\n\n self._feat_in = feat_in\n\n residual_panes = []\n encoder_layers = []\n self.dense_residual = False\n for lcfg in jasper:\n dense_res = []\n if lcfg.get('residual_dense', False):\n residual_panes.append(feat_in)\n dense_res = residual_panes\n self.dense_residual = True\n groups = lcfg.get('groups', 1)\n separable = lcfg.get('separable', False)\n heads = lcfg.get('heads', -1)\n residual_mode = lcfg.get('residual_mode', residual_mode)\n se = lcfg.get('se', False)\n se_reduction_ratio = lcfg.get('se_reduction_ratio', 8)\n se_context_window = lcfg.get('se_context_size', -1)\n se_interpolation_mode = lcfg.get('se_interpolation_mode', 'nearest')\n kernel_size_factor = lcfg.get('kernel_size_factor', 1.0)\n stride_last = lcfg.get('stride_last', False)\n aggregation_mode = lcfg.get('aggregation_mode', 'sum')\n block_dropout = lcfg.get('block_dropout', 0.0)\n parallel_residual_mode = lcfg.get('parallel_residual_mode', 'sum')\n\n parallel_blocks = []\n for kernel_size in lcfg['kernel']:\n parallel_blocks.append(\n JasperBlock(\n feat_in,\n lcfg['filters'],\n repeat=lcfg['repeat'],\n kernel_size=[kernel_size],\n stride=lcfg['stride'],\n dilation=lcfg['dilation'],\n dropout=lcfg['dropout'],\n residual=lcfg['residual'],\n groups=groups,\n separable=separable,\n heads=heads,\n residual_mode=residual_mode,\n normalization=normalization_mode,\n norm_groups=norm_groups,\n activation=activation,\n residual_panes=dense_res,\n conv_mask=conv_mask,\n se=se,\n se_reduction_ratio=se_reduction_ratio,\n se_context_window=se_context_window,\n se_interpolation_mode=se_interpolation_mode,\n kernel_size_factor=kernel_size_factor,\n stride_last=stride_last,\n quantize=quantize,\n )\n )\n if len(parallel_blocks) == 1:\n encoder_layers.append(parallel_blocks[0])\n else:\n encoder_layers.append(\n ParallelBlock(\n parallel_blocks,\n aggregation_mode=aggregation_mode,\n block_dropout_prob=block_dropout,\n residual_mode=parallel_residual_mode,\n in_filters=feat_in,\n out_filters=lcfg['filters'],\n )\n )\n feat_in = lcfg['filters']\n\n self._feat_out = feat_in\n\n self.encoder = torch.nn.Sequential(*encoder_layers)\n self.apply(lambda x: init_weights(x, mode=init_mode))\n\n @typecheck()\n def forward(self, audio_signal, length=None):\n s_input, length = self.encoder(([audio_signal], length))\n if length is None:\n return s_input[-1]\n\n return s_input[-1], length\n\n\nclass ConvASRDecoder(NeuralModule, Exportable):\n \"\"\"Simple ASR Decoder for use with CTC-based models such as JasperNet and QuartzNet\n\n Based on these papers:\n https://arxiv.org/pdf/1904.03288.pdf\n https://arxiv.org/pdf/1910.10261.pdf\n https://arxiv.org/pdf/2005.04290.pdf\n \"\"\"\n\n def save_to(self, save_path: str):\n pass\n\n @classmethod\n def restore_from(cls, restore_path: str):\n pass\n\n @property\n def input_types(self):\n return OrderedDict({\"encoder_output\": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation())})\n\n @property\n def output_types(self):\n return OrderedDict({\"logprobs\": NeuralType(('B', 'T', 'D'), LogprobsType())})\n\n def __init__(self, feat_in, num_classes, init_mode=\"xavier_uniform\", vocabulary=None):\n super().__init__()\n\n if vocabulary is not None:\n if num_classes != len(vocabulary):\n raise ValueError(\n f\"If vocabulary is specified, it's length should be equal to the num_classes. Instead got: num_classes={num_classes} and len(vocabulary)={len(vocabulary)}\"\n )\n self.__vocabulary = vocabulary\n self._feat_in = feat_in\n # Add 1 for blank char\n self._num_classes = num_classes + 1\n\n self.decoder_layers = torch.nn.Sequential(\n torch.nn.Conv1d(self._feat_in, self._num_classes, kernel_size=1, bias=True)\n )\n self.apply(lambda x: init_weights(x, mode=init_mode))\n\n @typecheck()\n def forward(self, encoder_output):\n return torch.nn.functional.log_softmax(self.decoder_layers(encoder_output).transpose(1, 2), dim=-1)\n\n def input_example(self):\n \"\"\"\n Generates input examples for tracing etc.\n Returns:\n A tuple of input examples.\n \"\"\"\n bs = 8\n seq = 64\n input_example = torch.randn(bs, self._feat_in, seq).to(next(self.parameters()).device)\n return tuple([input_example])\n\n def _prepare_for_export(self, **kwargs):\n m_count = 0\n for m in self.modules():\n if type(m).__name__ == \"MaskedConv1d\":\n m.use_mask = False\n m_count += 1\n if m_count > 0:\n logging.warning(f\"Turned off {m_count} masked convolutions\")\n Exportable._prepare_for_export(self, **kwargs)\n\n @property\n def vocabulary(self):\n return self.__vocabulary\n\n @property\n def num_classes_with_blank(self):\n return self._num_classes\n\n\nclass ConvASRDecoderClassification(NeuralModule, Exportable):\n \"\"\"Simple ASR Decoder for use with classification models such as JasperNet and QuartzNet\n\n Based on these papers:\n https://arxiv.org/pdf/2005.04290.pdf\n \"\"\"\n\n def input_example(self):\n \"\"\"\n Generates input examples for tracing etc.\n Returns:\n A tuple of input examples.\n \"\"\"\n input_example = torch.randn(16, self._feat_in, 128).to(next(self.parameters()).device)\n return tuple([input_example])\n\n @property\n def input_types(self):\n return OrderedDict({\"encoder_output\": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation())})\n\n @property\n def output_types(self):\n return OrderedDict({\"logits\": NeuralType(('B', 'D'), LogitsType())})\n\n def __init__(\n self,\n feat_in: int,\n num_classes: int,\n init_mode: Optional[str] = \"xavier_uniform\",\n return_logits: bool = True,\n pooling_type='avg',\n ):\n super().__init__()\n\n self._feat_in = feat_in\n self._return_logits = return_logits\n self._num_classes = num_classes\n\n if pooling_type == 'avg':\n self.pooling = torch.nn.AdaptiveAvgPool1d(1)\n elif pooling_type == 'max':\n self.pooling = torch.nn.AdaptiveMaxPool1d(1)\n else:\n raise ValueError('Pooling type chosen is not valid. Must be either `avg` or `max`')\n\n self.decoder_layers = torch.nn.Sequential(torch.nn.Linear(self._feat_in, self._num_classes, bias=True))\n self.apply(lambda x: init_weights(x, mode=init_mode))\n\n @typecheck()\n def forward(self, encoder_output):\n batch, in_channels, timesteps = encoder_output.size()\n\n encoder_output = self.pooling(encoder_output).view(batch, in_channels) # [B, C]\n logits = self.decoder_layers(encoder_output) # [B, num_classes]\n\n if self._return_logits:\n return logits\n\n return torch.nn.functional.softmax(logits, dim=-1)\n\n @property\n def num_classes(self):\n return self._num_classes\n\n\nclass ECAPAEncoder(NeuralModule, Exportable):\n \"\"\"\n Modified ECAPA Encoder layer without Res2Net module for faster training and inference which achieves\n better numbers on speaker diarization tasks\n Reference: ECAPA-TDNN Embeddings for Speaker Diarization (https://arxiv.org/pdf/2104.01466.pdf)\n\n input:\n feat_in: input feature shape (mel spec feature shape)\n filters: list of filter shapes for SE_TDNN modules\n kernel_sizes: list of kernel shapes for SE_TDNN modules\n dilations: list of dilations for group conv se layer\n scale: scale value to group wider conv channels (deafult:8)\n\n output:\n outputs : encoded output\n output_length: masked output lengths\n \"\"\"\n\n @property\n def input_types(self):\n \"\"\"Returns definitions of module input ports.\n \"\"\"\n return OrderedDict(\n {\n \"audio_signal\": NeuralType(('B', 'D', 'T'), SpectrogramType()),\n \"length\": NeuralType(tuple('B'), LengthsType()),\n }\n )\n\n @property\n def output_types(self):\n \"\"\"Returns definitions of module output ports.\n \"\"\"\n return OrderedDict(\n {\n \"outputs\": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()),\n \"encoded_lengths\": NeuralType(tuple('B'), LengthsType()),\n }\n )\n\n def __init__(\n self,\n feat_in: int,\n filters: list,\n kernel_sizes: list,\n dilations: list,\n scale: int = 8,\n init_mode: str = 'xavier_uniform',\n ):\n super().__init__()\n self.layers = nn.ModuleList()\n self.layers.append(TDNNModule(feat_in, filters[0], kernel_size=kernel_sizes[0], dilation=dilations[0]))\n\n for i in range(len(filters) - 2):\n self.layers.append(\n TDNNSEModule(\n filters[i],\n filters[i + 1],\n group_scale=scale,\n se_channels=128,\n kernel_size=kernel_sizes[i + 1],\n dilation=dilations[i + 1],\n )\n )\n self.feature_agg = TDNNModule(filters[-1], filters[-1], kernel_sizes[-1], dilations[-1])\n self.apply(lambda x: init_weights(x, mode=init_mode))\n\n def forward(self, audio_signal, length=None):\n x = audio_signal\n outputs = []\n\n for layer in self.layers:\n x = layer(x, length=length)\n outputs.append(x)\n\n x = torch.cat(outputs[1:], dim=1)\n x = self.feature_agg(x)\n return x, length\n\n\nclass SpeakerDecoder(NeuralModule, Exportable):\n \"\"\"\n Speaker Decoder creates the final neural layers that maps from the outputs\n of Jasper Encoder to the embedding layer followed by speaker based softmax loss.\n Args:\n feat_in (int): Number of channels being input to this module\n num_classes (int): Number of unique speakers in dataset\n emb_sizes (list) : shapes of intermediate embedding layers (we consider speaker embbeddings from 1st of this layers)\n Defaults to [1024,1024]\n pool_mode (str) : Pooling stratergy type. options are 'xvector','tap', 'attention'\n Defaults to 'xvector (mean and variance)'\n tap (temporal average pooling: just mean)\n attention (attention based pooling)\n\n init_mode (str): Describes how neural network parameters are\n initialized. Options are ['xavier_uniform', 'xavier_normal',\n 'kaiming_uniform','kaiming_normal'].\n Defaults to \"xavier_uniform\".\n \"\"\"\n\n def input_example(self):\n \"\"\"\n Generates input examples for tracing etc.\n Returns:\n A tuple of input examples.\n \"\"\"\n input_example = torch.randn(16, self.input_feat_in, 256).to(next(self.parameters()).device)\n return tuple([input_example])\n\n @property\n def input_types(self):\n return OrderedDict(\n {\n \"encoder_output\": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()),\n \"length\": NeuralType(('B',), LengthsType(), optional=True),\n }\n )\n\n @property\n def output_types(self):\n return OrderedDict(\n {\n \"logits\": NeuralType(('B', 'D'), LogitsType()),\n \"embs\": NeuralType(('B', 'D'), AcousticEncodedRepresentation()),\n }\n )\n\n def __init__(\n self,\n feat_in: int,\n num_classes: int,\n emb_sizes: Optional[Union[int, list]] = 256,\n pool_mode: str = 'xvector',\n angular: bool = False,\n attention_channels: int = 128,\n init_mode: str = \"xavier_uniform\",\n ):\n super().__init__()\n self.angular = angular\n self.emb_id = 2\n bias = False if self.angular else True\n emb_sizes = [emb_sizes] if type(emb_sizes) is int else emb_sizes\n\n self._num_classes = num_classes\n self.pool_mode = pool_mode.lower()\n if self.pool_mode == 'xvector' or self.pool_mode == 'tap':\n self._pooling = StatsPoolLayer(feat_in=feat_in, pool_mode=self.pool_mode)\n affine_type = 'linear'\n elif self.pool_mode == 'attention':\n self._pooling = AttentivePoolLayer(inp_filters=feat_in, attention_channels=attention_channels)\n affine_type = 'conv'\n\n shapes = [self._pooling.feat_in]\n for size in emb_sizes:\n shapes.append(int(size))\n\n emb_layers = []\n for shape_in, shape_out in zip(shapes[:-1], shapes[1:]):\n layer = self.affine_layer(shape_in, shape_out, learn_mean=False, affine_type=affine_type)\n emb_layers.append(layer)\n\n self.emb_layers = nn.ModuleList(emb_layers)\n\n self.final = nn.Linear(shapes[-1], self._num_classes, bias=bias)\n\n self.apply(lambda x: init_weights(x, mode=init_mode))\n\n def affine_layer(\n self, inp_shape, out_shape, learn_mean=True, affine_type='conv',\n ):\n if affine_type == 'conv':\n layer = nn.Sequential(\n nn.BatchNorm1d(inp_shape, affine=True, track_running_stats=True),\n nn.Conv1d(inp_shape, out_shape, kernel_size=1),\n )\n\n else:\n layer = nn.Sequential(\n nn.Linear(inp_shape, out_shape),\n nn.BatchNorm1d(out_shape, affine=learn_mean, track_running_stats=True),\n nn.ReLU(),\n )\n\n return layer\n\n @typecheck()\n def forward(self, encoder_output, length=None):\n pool = self._pooling(encoder_output, length)\n embs = []\n\n for layer in self.emb_layers:\n pool, emb = layer(pool), layer[: self.emb_id](pool)\n embs.append(emb)\n\n pool = pool.squeeze(-1)\n if self.angular:\n for W in self.final.parameters():\n W = F.normalize(W, p=2, dim=1)\n pool = F.normalize(pool, p=2, dim=1)\n\n out = self.final(pool)\n\n return out, embs[-1].squeeze(-1)\n\n\n@dataclass\nclass JasperEncoderConfig:\n filters: int = MISSING\n repeat: int = MISSING\n kernel: List[int] = MISSING\n stride: List[int] = MISSING\n dilation: List[int] = MISSING\n dropout: float = MISSING\n residual: bool = MISSING\n\n # Optional arguments\n groups: int = 1\n separable: bool = False\n heads: int = -1\n residual_mode: str = \"add\"\n residual_dense: bool = False\n se: bool = False\n se_reduction_ratio: int = 8\n se_context_size: int = -1\n se_interpolation_mode: str = 'nearest'\n kernel_size_factor: float = 1.0\n stride_last: bool = False\n\n\n@dataclass\nclass ConvASREncoderConfig:\n _target_: str = 'nemo.collections.asr.modules.ConvASREncoder'\n jasper: Optional[JasperEncoderConfig] = field(default_factory=list)\n activation: str = MISSING\n feat_in: int = MISSING\n normalization_mode: str = \"batch\"\n residual_mode: str = \"add\"\n norm_groups: int = -1\n conv_mask: bool = True\n frame_splicing: int = 1\n init_mode: Optional[str] = \"xavier_uniform\"\n\n\n@dataclass\nclass ConvASRDecoderConfig:\n _target_: str = 'nemo.collections.asr.modules.ConvASRDecoder'\n feat_in: int = MISSING\n num_classes: int = MISSING\n init_mode: Optional[str] = \"xavier_uniform\"\n vocabulary: Optional[List[str]] = field(default_factory=list)\n\n\n@dataclass\nclass ConvASRDecoderClassificationConfig:\n _target_: str = 'nemo.collections.asr.modules.ConvASRDecoderClassification'\n feat_in: int = MISSING\n num_classes: int = MISSING\n init_mode: Optional[str] = \"xavier_uniform\"\n return_logits: bool = True\n pooling_type: str = 'avg'\n"
] |
[
[
"torch.nn.functional.normalize",
"torch.nn.Sequential",
"torch.nn.functional.softmax",
"torch.nn.AdaptiveMaxPool1d",
"torch.randint",
"torch.nn.BatchNorm1d",
"torch.cat",
"torch.randn",
"torch.nn.ModuleList",
"torch.nn.Linear",
"torch.nn.Conv1d",
"torch.nn.AdaptiveAvgPool1d",
"torch.nn.ReLU"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
NicolasISEN/Facial_landmark_emotion_detection
|
[
"c7b8d7b0ea91a3496e3611bc1aab221709added4"
] |
[
"models/model_source/v1.0.0/learning.py"
] |
[
"import sys\nfrom dataset import Dataset\nimport tqdm\nimport time\nfrom cnn import Net32, Net256\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport logging\nimport argparse\nimport torchvision.models as models\nfrom torchvision import datasets\nfrom tensorboardX import SummaryWriter\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\ndef getArgs():\n parser = argparse.ArgumentParser(description='Setting model')\n parser.add_argument('-m','--model', type=int, choices=[32,256], default=32, help='Choose the model')\n parser.add_argument('-l','--learning',type=str, choices=['images','landmarks','images_landmarks'], default='images', help='Select the learning type')\n args = parser.parse_args()\n return args.model,args.learning\n\n\n\n\ndef save_checkpoint(state, is_best, checkpoint_path,best_model_path):\n torch.save(state, checkpoint_path)\n if is_best:\n torch.save(state, best_model_path)\n\ndef startLearning(model_type:int ,mode:str):\n print(device)\n #cudnn.Benchmark = True\n resnet18 = models.resnet18(False)\n writer = SummaryWriter()\n batch_size = 32\n max_epochs = 150\n print(\"load dataset\")\n loader = torch.utils.data.DataLoader(dataset=Dataset('data.h5',model_type), batch_size=batch_size, shuffle=True,num_workers=0)\n print(\"Done\")\n\n if model_type ==256:\n model = Net256(loader.dataset.getInputSize()).cuda()\n elif model_type == 32:\n model = Net32(loader.dataset.getInputSize()).cuda()\n else:\n print(\"Model doesn't exist\")\n return\n\n\n \n criterion = nn.CrossEntropyLoss().cuda()\n optimizer = torch.optim.Adam(model.parameters(), lr=0.0001, betas=(0.9,0.999)) \n #déclarer scheduler reduce plateau\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer,mode='min',factor=0.1,patience=10)\n best_loss = None\n ######\n\n \n ######\n for epoch in range(1,max_epochs+1): # loop over the dataset multiple times\n\n running_loss = 0.\n is_best= False\n loader.dataset.training()\n print(\"Training...\")\n pbart = tqdm.tqdm(total=int(len(loader.dataset)/batch_size),postfix={\"loss\":None,\"accuracy\":None},desc=\"Epoch: {}/{}\".format(epoch,max_epochs))\n acc = 0\n val_loss = 0.\n val_acc =0.\n\n for i, data in enumerate(loader, 0):\n # get the inputs\n images, expressions = data\n images = images.to(device)\n expressions = expressions.to(device).long()\n # zero the parameter gradients\n optimizer.zero_grad()\n outputs = model(images)\n loss = criterion(outputs, expressions)\n loss.backward()\n optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n _,predicted = torch.max(outputs,1)\n acc += (predicted == expressions).sum().float()/batch_size\n\n pbart.update(1)\n pbart.set_postfix({\"loss\": running_loss/(i+1),\"accuracy\":acc.item()/(i+1)})\n\n pbart.close()\n running_loss /= (len(loader.dataset)/batch_size)\n acc /= (len(loader.dataset)/batch_size)\n \n with open(\"log/training\"+\"_\"+str(model_type)+\"_\"+mode+\".log\",\"a\") as f:\n f.write(\"epoch: {} / {} loss: {} accuracy: {}\\n\".format(epoch,max_epochs,running_loss,acc))\n f.close()\n\n \n print(\"Validation...\")\n loader.dataset.validation()\n pbarv = tqdm.tqdm(total=int(len(loader.dataset)/batch_size),postfix={\"loss\":None,\"accuracy\":None},desc=\"Epoch: {}/{}\".format(epoch,max_epochs))\n\n \n with torch.no_grad():\n for i, data in enumerate(loader, 0):\n # get the inputs\n images, expressions = data\n images = images.to(device)\n expressions = expressions.to(device).long()\n\n outputs = model(images)\n loss = criterion(outputs, expressions)\n val_loss += loss.item()\n\n _,predicted = torch.max(outputs,1)\n val_acc +=(predicted == expressions).sum().float()/batch_size\n\n pbarv.update(1)\n pbarv.set_postfix({\"loss\": val_loss/(i+1),\"accuracy\":val_acc.item()/(i+1)})\n\n \n pbarv.close()\n val_loss /= (len(loader.dataset)/batch_size) \n val_acc /= (len(loader.dataset)/batch_size) \n \n \n\n if best_loss == None or val_loss < best_loss:\n best_loss = val_loss\n is_best = True\n save_checkpoint({\n 'epoch': epoch + 1,\n 'state_dict': model.state_dict(),\n 'loss': val_loss,\n 'accuracy': val_acc,\n 'optimizer' : optimizer.state_dict()}, is_best,\"save_model/checkpoint\"+\"_\"+str(model_type)+\"_\"+mode+\".pth\",\"save_model/best_model\"+\"_\"+str(model_type)+\"_\"+mode+\".pth\")\n is_best = False\n\n scheduler.step(val_loss)\n #loss accuracy training et validation dans les logs\n \n with open(\"log/validation\"+\"_\"+str(model_type)+\"_\"+mode+\".log\",\"a\") as f:\n f.write(\"epoch: {} / {} loss: {} accuracy: {}\\n\".format(epoch,max_epochs,val_loss,val_acc))\n f.close()\n\n writer.add_scalar('data/Loss training', running_loss, epoch)\n writer.add_scalar('data/Loss validation', val_loss, epoch)\n writer.add_scalar('data/Accuracy training', acc, epoch)\n writer.add_scalar('data/Accuracy validation', val_acc, epoch)\n\n loader.dataset.shuffle_training()\n\n\n\n\n\n\n\n \nif __name__ == \"__main__\":\n print(sys.version)\n args =getArgs()\n model_type = args[0]\n mode = args[1]\n with open(\"log/training\"+\"_\"+str(model_type)+\"_\"+mode+\".log\",\"w\") as f:\n f.close()\n with open(\"log/validation\"+\"_\"+str(model_type)+\"_\"+mode+\".log\",\"w\") as f:\n f.close()\n\n \n startLearning(model_type,mode)\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.max",
"torch.no_grad",
"torch.cuda.is_available",
"torch.save"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
vykimo/twitter_best_date
|
[
"557c3a1e084633760ceda11ae340a3d2871d7926"
] |
[
"train_hashtag.py"
] |
[
"#!/usr/bin/env python\n# encoding: utf-8\nimport numpy\nimport random\nimport argparse\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.svm import SVR\nfrom sklearn.ensemble import RandomForestRegressor\nfrom baselines import baselines\nimport calendar\nimport json\nimport os\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(description='Normalize a json.')\n group = parser.add_mutually_exclusive_group(required=True)\n group.add_argument('-f, --file', dest='file', type=open, help='file with twitter accounts')\n parser.add_argument('-s, --skip', dest='skip', action='store_true', help='skip tweets with no hashtags')\n return parser.parse_args()\n\n\ndef label_to_mins(label):\n\t[hour, min] = label.split(\":\")\t\n\treturn int(int(min) + 60*int(hour))\n\t\ndef mins_to_label(mins):\n\tif mins < 139440:\n\t\thour = str(int(mins/60))\n\t\tif hour < 10:\n\t\t\thour = \"0\" + hour \n\t\tmin = str(int(mins%60))\n\t\tif min < 10:\n\t\t\tmin = \"0\" + min\n\telse:\n\t\thour = \"00\"\n\t\tmin = \"00\"\n\treturn \":\".join([hour, min])\n\ndef build_hashtag_vector(hashtags, lower = 0):\n\th = dict()\n\ti = 0\n\tfor hashtag in hashtags:\n\t\tif not hashtag.lower() in h:\n\t\t\th[hashtag.lower()] = i\n\t\t\ti += 1\n\treturn h\n\ndef train_baselines(train, test, test_y):\n\tpredictions = []\n\n\tpredictions1 = baselines.overall_mean(train,test)\n\ttest_score1 = mean_squared_error(test_y, predictions1)\n\tprint('=Baseline 1 = Test MSE: %.3f' % test_score1)\n\tpredictions.append({'score':test_score1, 'prediction':predictions1})\n\t\t\n\tpredictions2 = baselines.maximum_mean_for_hashtag_in_tweet(train,test)\n\ttest_score2 = mean_squared_error(test_y, predictions2)\n\tprint('=Baseline 2 = Test MSE: %.3f' % test_score2)\n\tpredictions.append({'score':test_score2, 'prediction':predictions2})\n\t\n\tpredictions3 = baselines.mean_for_user(train,test)\n\ttest_score3 = mean_squared_error(test_y, predictions3)\n\tprint('=Baseline 3 = Test MSE: %.3f' % test_score3)\n\tpredictions.append({'score':test_score3, 'prediction':predictions3})\n\t\n\tpredictions4 = baselines.maximum_mean_for_hashtag_for_user(train,test)\n\ttest_score4 = mean_squared_error(test_y, predictions4)\n\tprint('=Baseline 4 = Test MSE: %.3f' % test_score4)\n\tpredictions.append({'score':test_score4, 'prediction':predictions4})\n\t\n\tpredictions5 = []\n\tfor i in range(0,len(predictions1)):\n\t\tlis = [predictions1[i], predictions2[i], predictions3[i], predictions4[i]]\n\t\tpredictions5.append(max(lis))\n\ttest_score5 = mean_squared_error(test_y, predictions5)\n\tprint('=Max Baseline = Test MSE: %.3f' % test_score5)\n\tpredictions.append({'score':test_score5, 'prediction':predictions5})\n\t\n\tpredictions6 = []\n\tfor i in range(0,len(predictions1)):\n\t\tlis = [predictions1[i], predictions2[i], predictions3[i], predictions4[i]]\n\t\tpredictions6.append(sum(lis)/len(lis))\n\ttest_score6 = mean_squared_error(test_y, predictions6)\n\tprint('=Mean Baseline = Test MSE: %.3f' % test_score6)\n\tpredictions.append({'score':test_score6, 'prediction':predictions6})\n\t\n\treturn predictions\n\t\ndef evaluation(prediction_baseline, predictions, test_score):\n\tfor i in range(6):\n\t\tif test_score < prediction_baseline[i]['score']:\n\t\t\tprint(\"** Baseline \"+ i +\" OK\")\n\t\telse:\n\t\t\tprint(\"** Baseline \"+ i +\" NOT OK\")\n\t\t\t\n\t\tprint('=Model-baselines '+ i +' prediction Test MSE: %.3f' % mean_squared_error(prediction_baseline[i]['prediction'], predictions))\n\t\ndef main(run_args):\n\tif run_args.file:\n\t\n\t\t# load dataset\n\t\tdatas = json.load(run_args.file)\n\t\t\t\t\n\t\tif run_args.skip:\n\t\t\t# Delete empty hashtags\n\t\t\tprint(\"Before cleaning tweets without hashtags : \"+str(len(datas)))\n\t\t\tdatas = [row for row in datas if len(row['hashtag'])>0]\n\t\t\tprint(\"After cleaning tweets without hashtags : \"+str(len(datas)))\n\t\t\t\n\t\t# Split data\n\t\t#train_size = int(len(datas) * 0.66)\n\t\t#train, test = datas[1:train_size], datas[train_size:]\n\t\ttrain, test = train_test_split(datas, test_size=0.33, shuffle=True, random_state=42)\n\t\ttest_y, train_y = [row['score'] for row in test], [row['score'] for row in train]\n\t\ttest_X, train_X = [[\"-\".join(row['hashtag']), row['weekday'], row['hour']] for row in test], [[\"-\".join(row['hashtag']), row['weekday'], row['hour']] for row in train]\n\t\t\n\t\thashtags = []\n\t\tfor data in datas:\n\t\t\tcomposition_h = \"-\".join(data['hashtag'])\n\t\t\thashtags.extend([composition_h.lower()])\n\t\thashtag_vector = build_hashtag_vector(hashtags,1)\n\t\t\n\t\tprint(\"Num of Hashtag datas : \"+str(len(datas)))\n\t\tprint(\"Num of unique Hashtags : \"+str(len(hashtag_vector)))\n\t\t\n\t\t# baselines\n\t\t\n\t\tcache_baseline = \"data/cache/\" + run_args.file.name.split('\\\\')[2].split('.')[0] + \"-baselines.json\"\n\t\t\n\t\tif not os.path.exists(cache_baseline):\n\t\t\tprediction_baseline = train_baselines(train, test, test_y)\n\t\t\twith open(cache_baseline, 'w') as f:\n\t\t\t\tf.write(json.dumps(prediction_baseline))\n\t\t\tpass\n\t\telse:\n\t\t\tprediction_baseline = json.load(open(cache_baseline))\n\t\t\n\t\t\n\t\tprint(\"Train model\")\n\t\t\n\t\tfor i in range(0,len(test_X)):\n\t\t\ttest_X[i][0] = hashtag_vector[test_X[i][0].lower()]\n\t\t\ttest_X[i][2] = label_to_mins(test_X[i][2])\n\t\t\t\n\t\tfor i in range(0,len(train_X)):\n\t\t\ttrain_X[i][0] = hashtag_vector[train_X[i][0].lower()]\n\t\t\ttrain_X[i][2] = label_to_mins(train_X[i][2])\n\t\t\t\n\t\t#svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1)\n\t\t#svr_rbf.fit(train_X, train_y)\n\t\t\n\t\tregr_rf = RandomForestRegressor(n_estimators=15, min_samples_leaf=1000, n_jobs=-1)\n\t\tregr_rf.fit(train_X, train_y)\t\t\n\t\t\n\t\tprint(\"Predict model\")\n\t\t#predictions_svr = svr_rbf.predict(test_X)\n\t\tpredictions_rf = regr_rf.predict(test_X)\n\t\tprint(\"importance : \")\n\t\tprint(regr_rf.feature_importances_)\n\t\t#test_score_svr = mean_squared_error(test_y, predictions_svr)\n\t\t#print('=Model Test MSE: %.3f' % test_score_svr)\n\t\ttest_score_rf = mean_squared_error(test_y, predictions_rf)\n\t\tprint('=Model Test MSE: %.3f' % test_score_rf)\n\t\t\n\t\ttest_score = test_score_rf\n\t\tpredictions = predictions_rf\n\t\t\n\t\tevaluation(prediction_baseline, predictions, test_score)\n\t\t\n\t\tdays = {\"Monday\":1, \"Tuesday\":2, \"Wednesday\":3, \"Thursday\":4, \"Friday\":5, \"Saturday\":6, \"Sunday\":0}\n\t\twhile 1:\n\t\t\tdoc = input(\"\\n============\\nWhat hashtag do you want to test? for instance '\"+hashtags[random.randint(0, len(hashtags))]+\"'\\n\").lower()\n\t\t\tif doc in hashtag_vector:\n\t\t\t\tday = int(input(\"Day of the week?\\n\"))\n\t\t\t\tif day >= 0 and day <= 6:\n\t\t\t\t\thour_label = input(\"Hour of the day? format HH:MM\\n\").strip('\\n')\n\t\t\t\t\thour = label_to_mins(hour_label)\n\n\t\t\t\t\tprint(\"\\nScore for '\"+ str(doc) +\"' , Day : \"+ str(calendar.day_name[day+1])+\", Hour : \"+ str(hour_label) +\" = \"+ str(int(regr_rf.predict([[hashtag_vector[doc], day, hour]]))))\n\t\t\t\t\t#print(\"\\nScore for '\"+ str(doc) +\"' , Day : \"+ str(calendar.day_name[day+1])+\", Hour : \"+ str(hour_label) +\" = \"+ str(int(svr_rbf.predict([[hashtag_vector[doc], day, hour]]))))\n\t\t\telse:\n\t\t\t\tprint(\"Hashtag not found\")\n\t\t\t\t\nif __name__ == \"__main__\":\n args = parse_arguments()\n main(args)"
] |
[
[
"sklearn.ensemble.RandomForestRegressor",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.mean_squared_error"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
riemarc/pyinduct
|
[
"5c407b6ae301be76639d464d43a20ba3fafd7e66",
"5c407b6ae301be76639d464d43a20ba3fafd7e66"
] |
[
"pyinduct/examples/string_with_mass/observer_evp_scripts/modal_approximation.py",
"pyinduct/simulation.py"
] |
[
"from pyinduct.examples.string_with_mass.utils import sym, param, obs_gain\nfrom sympy.utilities import lambdify\nfrom scipy.integrate import quad\nimport numpy as np\nimport sympy as sp\n\n\ndef _sum(iterable):\n sum = iterable[0] * 0\n for v in iterable:\n sum += v\n return sum\n\n\ndef _discard_small_values(mat, eps=10 ** -6):\n mat = np.array(mat).astype(complex)\n rmat = np.real(mat)\n rmat[np.abs(rmat) < eps] = 0\n imat = np.imag(mat)\n imat[np.abs(imat) < eps] = 0\n return np.real_if_close(mat)\n\n\ndef _pprint(item, discard_sv=True):\n if discard_sv and isinstance(item, (np.ndarray, sp.Matrix)):\n item = sp.Matrix(_discard_small_values(item))\n elif discard_sv and isinstance(item, (list, tuple)):\n item = [sp.Matrix(_discard_small_values(it)) for it in item]\n else:\n item = sp.Matrix(item)\n sp.pprint(item, num_columns=200)\n\n\ndef _numeric_integration(f1, f2, bounds, coef):\n iv, lb, ub = bounds\n f1 = sp.sympify(f1)\n occurrences = [c in f1.atoms(sp.Function)\n or sp.diff(c, sym.t) in f1.atoms(sp.Function)\n for c in coef]\n if any(occurrences):\n # handle derivatives first\n coef_ders = sp.Matrix([sp.diff(c, sym.t) for c in coef])\n vec, _ = _linear_eq_to_matrix(f1, coef_ders)\n if_ = [lambdify(iv, el * f2, modules=\"numpy\") for el in vec]\n res = np.sum([quad(f, lb, ub)[0] * sp.diff(c, sym.t)\n for c, f in zip(coef, if_)])\n rem_f1 = f1 - (vec * coef_ders)[0]\n vec, _ = _linear_eq_to_matrix(rem_f1, sp.Array(coef))\n if_ = [lambdify(iv, el * f2, modules=\"numpy\") for el in vec]\n res += np.sum([quad(f, lb, ub)[0] * c for c, f in zip(coef, if_)])\n else:\n if_ = lambdify(iv, (f1 * f2).doit(), modules=\"numpy\")\n res = quad(if_, lb, ub)[0]\n return res\n\n\ndef _l2_ip(f1, f2, coef):\n return _numeric_integration(f1, f2, (sym.z, 0, 1), coef)\n\n\ndef _l2_ip_nf(f1, f2, coef, lb=-1, ub=1):\n return _numeric_integration(f1, f2, (sym.theta, lb, ub), coef)\n\n\ndef _inner_product(primal, dual, coef):\n return (_l2_ip(sp.diff(primal[0], sym.z), sp.diff(dual[0], sym.z), coef)\n + _l2_ip(primal[1], dual[1], coef)\n + primal[2] * dual[2] +\n + param.m * primal[3] * dual[3])\n\n\ndef _inner_product_nf(primal, dual, coef):\n return (primal[0] * dual[0] + primal[1] * dual[1]\n + _l2_ip_nf(primal[2], dual[2], coef))\n\n\ndef _linear_eq_to_matrix(leq, coef):\n try:\n iter(coef)\n except TypeError:\n coef = sp.Array(coef)\n\n # substitute objects with dummies to circumvent problems\n d_map = {c: sp.Dummy() for c in coef}\n d_coef = coef.xreplace(d_map)\n d_leq = leq.xreplace(d_map)\n mat, _leq = sp.linear_eq_to_matrix(d_leq, *d_coef)\n return mat, -_leq\n\n\ndef build_bases_for_modal_observer_approximation(m):\n if m % 2 == 1:\n raise ValueError(\"Only even number of eigenvalues supported.\")\n\n n = int(m / 2)\n coef = [sp.Function(\"c_{}\".format(i))(sym.t) for i in range(n * 2)]\n\n # solve eigenvalue problems in normal form coordinates by hand: manual = 1\n # or derive from the solutions in original coordinates: manual = 0\n manual = 1\n\n # compute eigenvalues\n from pyinduct.examples.string_with_mass.utils import find_eigenvalues\n eig_om, eig_vals = find_eigenvalues(n)\n\n # fill primal base list\n from pyinduct.examples.string_with_mass.observer_evp_scripts.evp_primal import phi0, phi00, real_phi, imag_phi\n real_phi, imag_phi, phi0, phi00 = [\n it.subs(sym.m, param.m)\n for it in (real_phi, imag_phi, phi0, phi00)]\n primal_base = [list(phi0), list(phi00)]\n for _om in eig_om[1:]:\n primal_base.append(list(real_phi.subs(sym.om, _om)))\n primal_base.append(list(imag_phi.subs(sym.om, _om)))\n if 1: # manual:\n from pyinduct.examples.string_with_mass.observer_evp_scripts.evp_primal_nf import (\n real_eta as __real_eta, imag_eta as __imag_eta, eta0 as __eta0,\n eta00 as __eta00)\n __real_eta, __imag_eta, __eta0, __eta00 = [\n it.subs(sym.m, param.m)\n for it in (__real_eta, __imag_eta, __eta0, __eta00)]\n primal_base_nf = [list(__eta0), list(__eta00)]\n for _om in eig_om[1:]:\n primal_base_nf.append(list(__real_eta.subs(sym.om, _om)))\n primal_base_nf.append(list(__imag_eta.subs(sym.om, _om)))\n else:\n _theta = sym.theta - 1\n raise NotImplementedError(\n \"Leads to a differential equation, which coincides with the\"\n \"eigenvalue problem. Hence, there is no alternetive 'easy way'.\")\n\n # fill dual base list\n from pyinduct.examples.string_with_mass.observer_evp_scripts.evp_dual import psi0, psi00, real_psi, imag_psi\n real_psi, imag_psi, psi0, psi00 = [\n it.subs(sym.m, param.m)\n for it in (real_psi, imag_psi, psi0, psi00)]\n dual_base = [list(psi00), list(psi0)]\n for _om in eig_om[1:]:\n dual_base.append(list(real_psi.subs(sym.om, _om)))\n dual_base.append(list(imag_psi.subs(sym.om, _om)))\n if manual:\n from pyinduct.examples.string_with_mass.observer_evp_scripts.evp_dual_nf import (\n real_eta as _real_eta, imag_eta as _imag_eta, eta0 as _eta0,\n eta00 as _eta00)\n _real_eta, _imag_eta, _eta0, _eta00 = [\n it.subs(sym.m, param.m)\n for it in (_real_eta, _imag_eta, _eta0, _eta00)]\n dual_base_nf = [list(_eta00), list(_eta0)]\n for _om in eig_om[1:]:\n dual_base_nf.append(list(_real_eta.subs(sym.om, _om)))\n dual_base_nf.append(list(_imag_eta.subs(sym.om, _om)))\n else:\n _theta = sym.theta + 1\n dual_base_flat = [_theta - 1, sp.Integer(1)]\n for _om in eig_om[1:]:\n dual_base_flat.append(\n (sp.cos(sym.om * _theta)).subs(sym.om, _om))\n dual_base_flat.append(\n (sp.sin(sym.om * _theta)).subs(sym.om, _om))\n dual_base_nf = [[f.subs(sym.theta, -1),\n sp.diff(f, sym.theta).subs(sym.theta, -1),\n sp.diff(f, sym.theta, sym.theta)]\n for f in dual_base_flat]\n\n # build bi-orthonormal base\n for i, (ef, d_ef, d_ef_nf) in enumerate(zip(primal_base, dual_base, dual_base_nf)):\n c = _inner_product(ef, d_ef, coef)\n dual_base[i] = [it / c for it in d_ef]\n b = np.array([1, 1, (sp.sign(sym.theta) - 1) * .5 * sym.theta]) * 2 / param.m\n for i, _ in enumerate(dual_base_nf):\n if i % 2 == 0:\n scale = dual_base[i + 1][1].subs(sym.z, 1) / _inner_product_nf(\n b, dual_base_nf[i + 1], coef)\n dual_base_nf[i] = list(np.array(dual_base_nf[i]) * -scale * (-1 if i == 0 else 1))\n dual_base_nf[i + 1] = list(np.array(dual_base_nf[i + 1]) * scale)\n\n # print bases\n if 0:\n print(\"\\n primal base\")\n _pprint(primal_base, discard_sv=False)\n print(\"\\n dual base\")\n _pprint(dual_base, discard_sv=False)\n print(\"\\n primal normal form base\")\n _pprint(primal_base_nf, discard_sv=False)\n print(\"\\n dual normal form base\")\n _pprint(dual_base_nf, discard_sv=False)\n\n return primal_base, primal_base_nf, dual_base, dual_base_nf, eig_vals\n\n\ndef get_observer_gain(spring_damper_params=tuple()):\n\n # observer gain\n a = np.array([0,\n 0,\n param.m ** -1])\n a_bc = np.array([1])\n if len(spring_damper_params) > 0:\n kd0, ks0, kd1, ks1 = spring_damper_params\n\n a0 = param.m * (kd1 + 1) / 2\n a1 = a0 ** -1 * (ks0)\n a2 = a0 ** -1 * (ks1 * (2 * kd0 + ks0 + 2) / 2 + kd1 * (kd0 + 1) + ks0 * (1 + kd1))\n a3 = (a0 ** -1 *\n (ks1 * (param.m / 2 * sp.sign(sym.theta) + (kd0 + 1) / 2 *(1 - sym.theta) + ks0 / 2 * (sp.sign(sym.theta) * sym.theta ** 2 / 2 - sym.theta + .5)) +\n (kd1 + 1) * (kd0 + 1) / 2 + ks0 * (1 + kd1) * (1 - sym.theta) / 2)\n )\n a_desired = np.array([a1, a2, a3])\n a_bc_desired = np.array([a0 ** -1 * (param.m * (1 - kd1) / 2)])\n else:\n a_desired = np.array([(1+obs_gain.alpha) * obs_gain.k0,\n (1+obs_gain.alpha) * obs_gain.k1 + 2 * obs_gain.k0,\n obs_gain.k0 * (1 - sym.theta) + obs_gain.k1])\n a_bc_desired = np.array([obs_gain.alpha])\n l = a - a_desired\n l_bc = a_bc - a_bc_desired\n\n return l, l_bc\n\n\ndef validate_modal_bases(primal_base, primal_base_nf, dual_base, dual_base_nf,\n eig_vals):\n m = len(primal_base)\n n = int(m / 2)\n assert all([len(it_) == m for it_ in (primal_base_nf, dual_base, dual_base_nf, eig_vals)])\n\n coef = sp.Array([sp.Function(\"c_{}\".format(i))(sym.t) for i in range(n * 2)])\n\n # approximate state\n x = _sum([c * sp.Matrix(f) for c, f in zip(coef, primal_base)])\n x1 = np.sum([c * f[0] for c, f in zip(coef, primal_base)])\n x2 = np.sum([c * f[1] for c, f in zip(coef, primal_base)])\n xi1 = np.sum([c * f[2] for c, f in zip(coef, primal_base)])\n xi2 = np.sum([c * f[3] for c, f in zip(coef, primal_base)])\n\n # approximate normal form state\n eta = _sum([c * sp.Matrix(f) for c, f in zip(coef, primal_base_nf)])\n eta1 = np.sum([c * f[0] for c, f in zip(coef, primal_base_nf)])\n eta2 = np.sum([c * f[1] for c, f in zip(coef, primal_base_nf)])\n eta3 = np.sum([c * f[2] for c, f in zip(coef, primal_base_nf)])\n\n # test functions\n psi = [sp.Matrix(tf) for tf in dual_base]\n psi1 = [tf[0] for tf in dual_base]\n psi2 = [tf[1] for tf in dual_base]\n tau1 = [tf[2] for tf in dual_base]\n tau2 = [tf[3] for tf in dual_base]\n\n # normal form test functions\n nu = [sp.Matrix(tf) for tf in dual_base_nf]\n nu1 = [tf[0] for tf in dual_base_nf]\n nu2 = [tf[1] for tf in dual_base_nf]\n nu3 = [tf[2] for tf in dual_base_nf]\n\n # choose kind of desired dynamic\n spring_damper = 0\n if spring_damper:\n kd0, ks0, kd1, ks1 = [1] * 4\n spring_damper_params = kd0, ks0, kd1, ks1\n else:\n k0, k1, alpha = 9, 10, 0\n spring_damper_params = list()\n l, l_bc = get_observer_gain(spring_damper_params)\n\n # observer projections\n if 1:\n observer_projections = [\n (_inner_product_nf(l, ftf, coef)\n + l_bc * ftf3.subs(sym.theta, -1)) * sym.yt(sym.t)\n for ftf, ftf3 in zip(nu, nu3)]\n else:\n observer_projections = [\n (-_inner_product_nf(a_desired, ftf, coef)\n - a_bc_desired * ftf3.subs(sym.theta, -1)\n - ftf3.subs(sym.theta, 1)) * sym.yt(sym.t)\n for ftf, ftf3 in zip(nu, nu3)]\n\n # just the unbounded part\n L_unbounded = sp.Matrix([[l_bc[0] * ftf3.subs(sym.theta, -1)]\n for ftf3 in nu3])\n\n # project test functions on state space\n C = list()\n system_projections = [\n -_inner_product(sp.diff(x, sym.t), tf, coef)\n + _l2_ip(sp.diff(x2, sym.z), sp.diff(tf1, sym.z), coef)\n + (sym.u(sym.t) * tf2).subs(sym.z, 1)\n - (sp.diff(x1, sym.z) * tf2).subs(sym.z, 0)\n - _l2_ip(sp.diff(x1, sym.z), sp.diff(tf2, sym.z), coef)\n + xi2 * t1 + sp.diff(x1, sym.z).subs(sym.z, 0) * t2\n for tf, tf1, tf2, t1, t2\n in zip(psi, psi1, psi2, tau1, tau2)\n ]\n C.append(_linear_eq_to_matrix(xi1, coef)[0])\n system_projections_nf = [\n -_inner_product_nf(sp.diff(eta, sym.t), ftf, coef)\n + eta1 * ftf2\n + _l2_ip_nf(eta3, sp.diff(ftf3, sym.theta), coef)\n - eta3.subs(sym.theta, 1) * ftf3.subs(sym.theta, 1)\n + (eta2 - eta3.subs(sym.theta, 1)) * ftf3.subs(sym.theta, -1)\n - eta3.subs(sym.theta, 1) * _l2_ip_nf(param.m ** -1, ftf3, coef)\n + (2 / param.m * ftf1\n + 2 / param.m * ftf2\n + _l2_ip_nf(-2 / param.m * sym.theta, ftf3, coef, lb=-1, ub=0)) * sym.u(sym.t)\n for ftf, ftf1, ftf2, ftf3\n in zip(nu, nu1, nu2, nu3)\n ]\n C.append(_linear_eq_to_matrix(eta3.subs(sym.theta, 1), coef)[0])\n\n # add observer projections to the system projections\n projections = sp.Matrix([sp + op for sp, op in zip(system_projections,\n observer_projections)])\n projections_nf = sp.Matrix([sp + op for sp, op in zip(system_projections_nf,\n observer_projections)])\n\n # parse matrices\n E1, E0, G, J, A, B, L = [[None, None] for _ in range(7)]\n for i, proj in enumerate([projections, projections_nf]):\n E1[i], proj = _linear_eq_to_matrix(proj, sp.Array([sp.diff(c, sym.t)\n for c in coef]))\n E0[i], proj = _linear_eq_to_matrix(proj, coef)\n G[i], proj = _linear_eq_to_matrix(proj, sym.u(sym.t))\n J[i], proj = _linear_eq_to_matrix(proj, sym.yt(sym.t))\n if proj != proj * 0:\n print(\"\\n Something went wrong! This is left:\")\n _pprint(proj, discard_sv=False)\n raise ValueError\n print(\"\\n E1\")\n _pprint(E1[i])\n print(\"\\n E0\")\n _pprint(E0[i])\n\n # compute state space\n np.testing.assert_array_almost_equal(np.eye(n * 2), -E1[i])\n A[i] = E0[i]\n B[i] = G[i]\n L[i] = J[i]\n\n # display matrices\n print(\"\\n A\")\n np.testing.assert_array_almost_equal(A[0], A[1])\n _pprint(A[0])\n _pprint(A[1])\n print(\"\\n B\")\n np.testing.assert_array_almost_equal(B[0], B[1])\n _pprint((B[0], B[1]))\n print(\"\\n C\")\n np.testing.assert_array_almost_equal(C[0], C[1])\n _pprint(C[0])\n _pprint(C[1])\n print(\"\\n L\")\n np.testing.assert_array_almost_equal(L[0], L[1])\n _pprint((L[0], L[1]))\n\n # compare eigenvalue\n print(\"\\n open loop eigenvalues\")\n _pprint((np.linalg.eigvals(np.array(A[0]).astype(complex)),\n np.linalg.eigvals(np.array(A[1]).astype(complex)),\n eig_vals))\n if spring_damper:\n if __name__ == \"__main__\" and n <= 5:\n import pyinduct as pi\n def char_eq(lam):\n return complex(\n np.exp(lam * 2) * lam ** 2 + a_bc_desired[0] * lam ** 2 +\n _inner_product_nf(sp.Matrix(a_desired), sp.Matrix([1, lam, sp.exp(lam * (sym.theta + 1)) * lam ** 2]), coef)\n )\n char_eq_vec = np.vectorize(char_eq)\n eig_vals_d = sp.Matrix(pi.find_roots(\n char_eq_vec, [np.linspace(-2, 0, n), np.linspace(-10, 10, n)],\n cmplx=True))\n else:\n eig_vals_d = sp.Matrix([0])\n else:\n eig_vals_d = list(np.roots([1, k1, k0]))\n for i in range(1, n):\n if alpha == 0:\n eig_vals_d.append(-sp.oo)\n eig_vals_d.append(-sp.oo)\n elif alpha < 0:\n eig_vals_d.append(np.log(np.abs(alpha)) + 1j * 2 * i * np.pi)\n eig_vals_d.append(np.log(np.abs(alpha)) - 1j * 2 * i * np.pi)\n else:\n eig_vals_d.append(np.log(np.abs(alpha)) + 1j * (2*i - 1) * np.pi)\n eig_vals_d.append(np.log(np.abs(alpha)) + 1j * (-2*i - 1) * np.pi)\n print(\"\\n closed loop eigenvalues\")\n eig_vals_cl = [np.linalg.eigvals(np.array(A[0] + L[0] * C[0]).astype(complex)),\n np.linalg.eigvals(np.array(A[1] + L[1] * C[1]).astype(complex))]\n _pprint((eig_vals_cl[0], eig_vals_cl[1], eig_vals_d))\n\n return A[0], B[0], C[0], L[0], L_unbounded\n",
"\"\"\"\nSimulation infrastructure with helpers and data structures for preprocessing of the given equations\nand functions for postprocessing of simulation data.\n\"\"\"\n\nimport warnings\nfrom abc import ABCMeta, abstractmethod\nfrom collections import OrderedDict, Callable\nfrom copy import copy\nfrom itertools import chain\n\nimport numpy as np\nfrom scipy.integrate import ode\nfrom scipy.interpolate import interp1d\nfrom scipy.linalg import block_diag\n\nfrom .core import (Domain, Parameters, Function,\n domain_intersection, integrate_function,\n calculate_scalar_product_matrix,\n vectorize_scalar_product, sanitize_input,\n StackedBase, get_weight_transformation,\n get_transformation_info,\n EvalData, project_on_bases)\nfrom .placeholder import (Scalars, TestFunction, Input, FieldVariable,\n EquationTerm, get_common_target, get_common_form,\n ObserverGain, ScalarTerm, IntegralTerm,\n ScalarProductTerm)\nfrom .registry import get_base, register_base\n\n__all__ = [\"SimulationInput\", \"SimulationInputSum\", \"WeakFormulation\",\n \"parse_weak_formulation\",\n \"create_state_space\", \"StateSpace\", \"simulate_state_space\",\n \"simulate_system\", \"simulate_systems\",\n \"get_sim_result\", \"evaluate_approximation\",\n \"parse_weak_formulations\",\n \"get_sim_results\", \"set_dominant_labels\", \"CanonicalEquation\",\n \"CanonicalForm\", \"SimulationInputVector\"]\n\n\nclass SimulationInput(object, metaclass=ABCMeta):\n \"\"\"\n Base class for all objects that want to act as an input for the time-step\n simulation.\n\n The calculated values for each time-step are stored in internal memory and\n can be accessed by :py:meth:`.get_results` (after the simulation is\n finished).\n\n Note:\n Due to the underlying solver, this handle may get called with time\n arguments, that lie outside of the specified integration domain. This\n should not be a problem for a feedback controller but might cause\n problems for a feedforward or trajectory implementation.\n \"\"\"\n\n def __init__(self, name=\"\"):\n self._time_storage = []\n self._value_storage = {}\n self.name = name\n self._res = np.array([0])\n\n def __call__(self, **kwargs):\n \"\"\"\n handle that is used by the simulator to retrieve input.\n \"\"\"\n out = self._calc_output(**kwargs)\n self._time_storage.append(kwargs[\"time\"])\n for key, value in out.items():\n entries = self._value_storage.get(key, [])\n entries.append(copy(value))\n self._value_storage[key] = entries\n\n return np.atleast_1d(out[\"output\"])\n\n @abstractmethod\n def _calc_output(self, **kwargs):\n \"\"\"\n Handle that has to be implemented for output calculation.\n\n Keyword Args:\n time: The current simulation time.\n weights: The current weight vector.\n weight_lbl: The label of the weights used.\n\n Returns:\n dict: Dictionary with mandatory key ``output``.\n \"\"\"\n return dict(output=self._res)\n\n def get_results(self, time_steps, result_key=\"output\",\n interpolation=\"nearest\", as_eval_data=False):\n \"\"\"\n Return results from internal storage for given time steps.\n\n Raises:\n Error: If calling this method before a simulation was run.\n\n Args:\n time_steps: Time points where values are demanded.\n result_key: Type of values to be returned.\n interpolation: Interpolation method to use if demanded time-steps\n are not covered by the storage, see\n :func:`scipy.interpolate.interp1d` for all possibilities.\n as_eval_data (bool): Return results as\n :py:class:`.EvalData` object for straightforward display.\n\n Return:\n Corresponding function values to the given time steps.\n \"\"\"\n t_data = np.array(self._time_storage)\n res_data = np.array(self._value_storage[result_key])\n invalid_idxs = np.logical_not(np.isnan(res_data))\n mask = [np.all(a) for a in invalid_idxs]\n\n func = interp1d(t_data[mask],\n res_data[mask],\n kind=interpolation,\n assume_sorted=False,\n bounds_error=False,\n fill_value=(res_data[mask][0], res_data[mask][-1]),\n axis=0)\n values = func(time_steps)\n\n if as_eval_data:\n return EvalData([time_steps],\n values,\n name=\".\".join([self.name, result_key]),\n fill_axes=True)\n\n return values\n\n def clear_cache(self):\n \"\"\"\n Clear the internal value storage.\n\n When the same *SimulationInput* is used to perform various simulations,\n there is no possibility to distinguish between the different runs when\n :py:meth:`.get_results` gets called. Therefore this method can be used\n to clear the cache.\n \"\"\"\n self._time_storage.clear()\n self._value_storage.clear()\n\n\nclass EmptyInput(SimulationInput):\n def __init__(self, dim):\n SimulationInput.__init__(self)\n self.dim = dim\n\n def _calc_output(self, **kwargs):\n return dict(output=np.zeros((len(np.atleast_1d(kwargs['time'])), self.dim)))\n\n\nclass SimulationInputSum(SimulationInput):\n \"\"\"\n Helper that represents a signal mixer.\n \"\"\"\n\n def __init__(self, inputs):\n SimulationInput.__init__(self)\n self.inputs = inputs\n\n def _calc_output(self, **kwargs):\n outs = [handle(**kwargs) for handle in self.inputs]\n return dict(output=np.sum(outs, axis=0))\n\n\nclass WeakFormulation(object):\n r\"\"\"\n This class represents the weak formulation of a spatial problem.\n It can be initialized with several terms (see children of\n :py:class:`.EquationTerm`).\n The equation is interpreted as\n\n .. math:: term_0 + term_1 + ... + term_N = 0.\n\n Args:\n terms (list): List of object(s) of type EquationTerm.\n name (string): Name of this weak form.\n dominant_lbl (string): Name of the variable that dominates this weak\n form.\n \"\"\"\n\n def __init__(self, terms, name, dominant_lbl=None):\n self.terms = sanitize_input(terms, EquationTerm)\n self.name = name\n self.dominant_lbl = dominant_lbl\n\n\nclass StateSpace(object):\n r\"\"\"\n Wrapper class that represents the state space form of a dynamic system where\n\n .. math::\n \\boldsymbol{\\dot{x}}(t) &= \\sum\\limits_{k=0}^{L}\\boldsymbol{A}_{k}\n \\boldsymbol{x}^{p_k}(t)\n + \\sum\\limits_{j=0}^{V} \\sum\\limits_{k=0}^{L}\\boldsymbol{B}_{j, k}\n \\frac{\\mathrm{d}^j u^{p_k}}{\\mathrm{d}t^j}(t)\n + \\boldsymbol{L}\\tilde{\\boldsymbol{y}}(t)\\\\\n \\boldsymbol{y}(t) &= \\boldsymbol{C}\\boldsymbol{x}(t)\n + \\boldsymbol{D}u(t)\n\n which has been approximated by projection on a base given by weight_label.\n\n Args:\n a_matrices (dict): State transition matrices\n :math:`\\boldsymbol{A}_{p_k}` for the corresponding powers of\n :math:`\\boldsymbol{x}`.\n b_matrices (dict): Cascaded dictionary for the input matrices\n :math:`\\boldsymbol{B}_{j, k}` in the sequence: temporal derivative\n order, exponent.\n input_handle (:py:class:`.SimulationInput`): System input :math:`u(t)`.\n c_matrix: :math:`\\boldsymbol{C}`\n d_matrix: :math:`\\boldsymbol{D}`\n \"\"\"\n\n def __init__(self, a_matrices, b_matrices, base_lbl=None,\n input_handle=None, c_matrix=None, d_matrix=None,\n obs_fb_handle=None):\n self.C = c_matrix\n self.D = d_matrix\n self.base_lbl = base_lbl\n self.observer_fb = obs_fb_handle\n\n # mandatory\n if isinstance(a_matrices, np.ndarray):\n self.A = {1: a_matrices}\n else:\n self.A = a_matrices\n if 0 not in self.A:\n # this is the constant term (power 0) aka the f-vector\n self.A[0] = np.zeros((self.A[1].shape[0],))\n\n # optional\n if isinstance(b_matrices, np.ndarray):\n # fake import order and power for backward compatibility\n self.B = {0: {1: b_matrices}}\n else:\n self.B = b_matrices\n\n # TODO calculate available order\n available_power = 1\n if self.B is None:\n self.B = {0: {available_power: np.zeros((self.A[available_power].shape[0], available_power))}}\n if self.C is None:\n self.C = np.zeros((available_power, self.A[available_power].shape[1]))\n if self.D is None:\n self.D = np.zeros((self.C.shape[0], np.atleast_2d(self.B[0][available_power]).T.shape[1]))\n\n if input_handle is None:\n self.input = EmptyInput(self.B[0][available_power].shape[1])\n elif isinstance(input_handle, SimulationInput):\n self.input = input_handle\n else:\n raise NotImplementedError\n\n # TODO export cython code?\n def rhs(self, _t, _q):\n r\"\"\"\n Callback for the integration of the dynamic system, described by this object.\n\n Args:\n _t (float): timestamp\n _q (array): weight vector\n\n Returns:\n (array): :math:`\\boldsymbol{\\dot{x}}(t)`\n \"\"\"\n state_part = self.A[0]\n for power, a_mat in self.A.items():\n state_part = state_part + a_mat @ np.power(_q, power)\n\n input_part = np.zeros_like(state_part)\n inputs = np.atleast_2d(\n self.input(time=_t, weights=_q, weight_lbl=self.base_lbl))\n for der_order, power_dict in self.B.items():\n for power, b_mat in power_dict.items():\n for idx, col in enumerate(b_mat.T):\n input_part = input_part + col * inputs[idx][der_order]\n\n q_t = state_part + input_part\n\n if self.observer_fb is not None:\n q_t = q_t + self.observer_fb(\n time=_t, weights=_q, weight_lbl=self.base_lbl)\n\n return q_t\n\n\ndef simulate_system(weak_form, initial_states,\n temporal_domain, spatial_domain,\n derivative_orders=(0, 0), settings=None):\n r\"\"\"\n Convenience wrapper for :py:func:`.simulate_systems`.\n\n Args:\n weak_form (:py:class:`.WeakFormulation`): Weak formulation of the system\n to simulate.\n initial_states (numpy.ndarray): Array of core.Functions for\n :math:`x(t=0, z), \\dot{x}(t=0, z), \\dotsc, x^{(n)}(t=0, z)`.\n temporal_domain (:py:class:`.Domain`): Domain object holding information\n for time evaluation.\n spatial_domain (:py:class:`.Domain`): Domain object holding information\n for spatial evaluation.\n derivative_orders (tuple): tuples of derivative orders (time, spat) that\n shall be evaluated additionally as values\n settings: Integrator settings, see :py:func:`.simulate_state_space`.\n \"\"\"\n ics = sanitize_input(initial_states, Function)\n initial_states = {weak_form.name: ics}\n spatial_domains = {weak_form.name: spatial_domain}\n derivative_orders = {weak_form.name: derivative_orders}\n res = simulate_systems([weak_form], initial_states, temporal_domain, spatial_domains, derivative_orders, settings)\n return res\n\n\ndef simulate_systems(weak_forms, initial_states, temporal_domain,\n spatial_domains, derivative_orders=None, settings=None,\n out=list()):\n \"\"\"\n Convenience wrapper that encapsulates the whole simulation process.\n\n Args:\n weak_forms ((list of) :py:class:`.WeakFormulation`): (list of) Weak\n formulation(s) of the system(s) to simulate.\n initial_states (dict, numpy.ndarray): Array of core.Functions for\n :math:`x(t=0, z), \\dot{x}(t=0, z), \\dotsc, x^{(n)}(t=0, z)`.\n temporal_domain (:py:class:`.Domain`): Domain object holding\n information for time evaluation.\n spatial_domains (dict): Dict with :py:class:`.Domain` objects holding\n information for spatial evaluation.\n derivative_orders (dict): Dict, containing tuples of derivative orders\n (time, spat) that shall be evaluated additionally as values\n settings: Integrator settings, see :py:func:`.simulate_state_space`.\n out (list): List from user namespace, where the following intermediate\n results will be appended:\n\n - canonical equations (list of types: :py:class:`.CanocialEquation`)\n - state space object (type: :py:class:`.StateSpace`)\n - initial weights (type: :py:class:`numpy.array`)\n - simulation results/weights (type: :py:class:`numpy.array`)\n\n Note:\n The *name* attributes of the given weak forms must be unique!\n\n Return:\n list: List of :py:class:`.EvalData` objects, holding the results for the\n FieldVariable and demanded derivatives.\n \"\"\"\n if derivative_orders is None:\n derivative_orders = dict([(lbl, (0, 0))for lbl in spatial_domains])\n\n weak_forms = sanitize_input(weak_forms, WeakFormulation)\n print(\"simulate systems: {}\".format([f.name for f in weak_forms]))\n\n print(\">>> parse weak formulations\")\n canonical_equations = parse_weak_formulations(weak_forms)\n out.append(canonical_equations)\n\n print(\">>> create state space system\")\n state_space_form = create_state_space(canonical_equations)\n out.append(state_space_form)\n\n print(\">>> derive initial conditions\")\n q0 = project_on_bases(initial_states, canonical_equations)\n out.append(q0)\n\n print(\">>> perform time step integration\")\n sim_domain, q = simulate_state_space(state_space_form, q0, temporal_domain,\n settings=settings)\n out.append(q)\n\n print(\">>> perform postprocessing\")\n results = get_sim_results(sim_domain, spatial_domains, q, state_space_form,\n derivative_orders=derivative_orders)\n\n print(\">>> finished simulation\")\n return results\n\n\ndef get_sim_result(weight_lbl, q, temp_domain, spat_domain, temp_order, spat_order, name=\"\"):\n \"\"\"\n Create handles and evaluate at given points.\n\n Args:\n weight_lbl (str): Label of Basis for reconstruction.\n temp_order: Order or temporal derivatives to evaluate additionally.\n spat_order: Order or spatial derivatives to evaluate additionally.\n q: weights\n spat_domain (:py:class:`.Domain`): Domain object providing values for\n spatial evaluation.\n temp_domain (:py:class:`.Domain`): Time steps on which rows of q are\n given.\n name (str): Name of the WeakForm, used to generate the data set.\n \"\"\"\n data = []\n\n # temporal\n ini_funcs = get_base(weight_lbl).fractions\n for der_idx in range(temp_order + 1):\n name = \"{0}{1}\".format(name, \"_\" + \"\".join([\"d\" for x in range(der_idx)] + [\"t\"]) if der_idx > 0 else \"\")\n data.append(evaluate_approximation(weight_lbl, q[:, der_idx * ini_funcs.size:(der_idx + 1) * ini_funcs.size],\n temp_domain, spat_domain, name=name))\n\n # spatial (0th derivative is skipped since this is already handled above)\n for der_idx in range(1, spat_order + 1):\n name = \"{0}{1}\".format(name, \"_\" + \"\".join([\"d\" for x in range(der_idx)] + [\"z\"]) if der_idx > 0 else \"\")\n data.append(\n evaluate_approximation(weight_lbl, q[:, :ini_funcs.size], temp_domain, spat_domain, der_idx, name=name))\n\n return data\n\n\ndef get_sim_results(temp_domain, spat_domains, weights, state_space, names=None,\n derivative_orders=None):\n \"\"\"\n Convenience wrapper for :py:func:`.get_sim_result`.\n\n Args:\n temp_domain (:py:class:`.Domain`): Time domain\n spat_domains (dict): Spatial domain from all subsystems which belongs to\n *state_space* as values and name of the systems as keys.\n weights (numpy.array): Weights gained through simulation. For example\n with :py:func:`.simulate_state_space`.\n state_space (:py:class:`.StateSpace`): Simulated state space instance.\n names: List of names of the desired systems. If not given all available\n subssystems will be processed.\n derivative_orders (dict): Desired derivative orders.\n\n Returns:\n List of :py:class:`.EvalData` objects.\n \"\"\"\n ss_base = get_base(state_space.base_lbl)\n if names is None:\n if isinstance(ss_base, StackedBase):\n labels = ss_base.base_lbls\n names = ss_base.system_names\n else:\n names = list(spat_domains)\n labels = [state_space.base_lbl]\n else:\n if isinstance(ss_base, StackedBase):\n labels = [ss_base.base_lbls[ss_base.system_names.index(name)]\n for name in names]\n else:\n labels = [state_space.base_lbl]\n\n if derivative_orders is None:\n derivative_orders = dict([(name, (0, 0)) for name in names])\n\n results = []\n for nm, lbl in zip(names, labels):\n # if derivative_orders[n] is None derivatives of the\n # corresponding variables are not provided\n if derivative_orders[nm][0] is None:\n derivative_orders[nm][0] = 0\n if derivative_orders[nm][1] is None:\n derivative_orders[nm][1] = 0\n\n # acquire a transformation into the original weights\n src_order = int(weights.shape[1] / ss_base.fractions.size) - 1\n info = get_transformation_info(state_space.base_lbl,\n lbl,\n src_order,\n derivative_orders[nm][0])\n transformation = get_weight_transformation(info)\n\n # project back\n data = get_sim_result(info.dst_lbl,\n np.apply_along_axis(transformation, 1, weights),\n temp_domain,\n spat_domains[nm],\n info.dst_order,\n derivative_orders[nm][1],\n name=nm)\n results += data\n\n return results\n\n\nclass CanonicalForm(object):\n \"\"\"\n The canonical form of an nth order ordinary differential equation system.\n \"\"\"\n\n def __init__(self, name=None):\n self.name = name\n self.matrices = {}\n # self._max_idx = dict(E=0, f=0, G=0)\n self._weights = None\n self._input_function = None\n self._observer_feedback = list()\n self._finalized = False\n self.powers = None\n self.max_power = None\n self.max_temp_order = None\n self.dim_u = 0\n self.dim_x = None\n self.dim_xb = None\n self.e_n_pb = None\n self.e_n_pb_inv = None\n self.singular = True\n\n # @staticmethod\n # def _build_name(term):\n # return \"_\" + term[0] + str(term[1])\n\n # def __add__(self, other):\n # for name, names in other._matrices.items():\n # for der, derivatives in names.items():\n # for p, pow in derivatives.items():\n # self._matrices[name][der][p] += pow\n\n @property\n def input_function(self):\n return self._input_function\n\n def set_input_function(self, func):\n if not isinstance(func, SimulationInput):\n raise TypeError(\"Inputs must be of type `SimulationInput`.\")\n\n if self._input_function is None:\n self._input_function = func\n elif self._input_function is not func:\n raise ValueError(\"already defined input is overridden!\")\n\n # @property\n # def weights(self):\n # return self._weights\n #\n # @weights.setter\n # def weights(self, weight_lbl):\n # if not isinstance(weight_lbl, str):\n # raise TypeError(\"only string allowed as weight label!\")\n # if self._weights is None:\n # self._weights = weight_lbl\n # if self._weights != weight_lbl:\n # raise ValueError(\"already defined target weights are overridden!\")\n\n def add_to(self, term, value, column=None):\n \"\"\"\n Adds the value :py:obj:`value` to term :py:obj:`term`. :py:obj:`term` is a dict that describes which\n coefficient matrix of the canonical form the value shall be added to.\n\n Args:\n term (dict): Targeted term in the canonical form h. It has to contain:\n\n - name: Type of the coefficient matrix: 'E', 'f', or 'G'.\n - order: Temporal derivative order of the assigned weights.\n - exponent: Exponent of the assigned weights.\n value (:py:obj:`numpy.ndarray`): Value to add.\n column (int): Add the value only to one column of term (useful if only one dimension of term is known).\n \"\"\"\n if self._finalized:\n raise RuntimeError(\"Object has already been finalized, you are trying some nasty stuff there.\")\n\n if term[\"name\"] == \"L\":\n self._observer_feedback.append(value)\n return\n\n if not isinstance(value, np.ndarray):\n raise TypeError(\"val must be numpy.ndarray\")\n if column and not isinstance(column, int):\n raise TypeError(\"column index must be int\")\n\n # get entry\n if term[\"name\"] == \"f\":\n if (\"order\" in term) \\\n or (\"exponent\" in term\n and term[\"exponent\"] != 0):\n warnings.warn(\"order and exponent are ignored for f_vector!\")\n f_vector = self.matrices.get(\"f\", np.zeros_like(value))\n self.matrices[\"f\"] = value + f_vector\n return\n\n type_group = self.matrices.get(term[\"name\"], {})\n derivative_group = type_group.get(term[\"order\"], {})\n target_matrix = derivative_group.get(term[\"exponent\"],\n np.zeros_like(value))\n\n if target_matrix.shape != value.shape and column is None:\n msg = \"{0}{1}{2} was already initialized with dimensions {3} but \" \\\n \"value to add has dimension {4}\".format(term[\"name\"],\n term[\"order\"],\n term[\"exponent\"],\n target_matrix.shape,\n value.shape)\n raise ValueError(msg)\n\n if column is not None:\n # check whether the dimensions fit or if the matrix must be extended\n if column >= target_matrix.shape[1]:\n new_target_matrix = np.zeros((target_matrix.shape[0],\n column + 1))\n new_target_matrix[\n :target_matrix.shape[0],\n :target_matrix.shape[1]\n ] = target_matrix\n target_matrix = new_target_matrix\n\n target_matrix[:, column:column + 1] += value\n else:\n target_matrix += value\n\n # store changes\n derivative_group[term[\"exponent\"]] = target_matrix\n type_group[term[\"order\"]] = derivative_group\n self.matrices[term[\"name\"]] = type_group\n\n def finalize(self):\n \"\"\"\n Finalizes the object.\n This method must be called after all terms have been added by\n :py:meth:`.add_to` and before :py:meth:`.convert_to_state_space` can be\n called. This functions makes sure that the formulation can be converted\n into state space form (highest time derivative only comes in one power)\n and collects information like highest derivative order, it's power and\n the sizes of current and state-space state vector (`dim_x` resp.\n `dim_xb`). Furthermore, the coefficient matrix of the highest derivative\n order `e_n_pb` and it's inverse are made accessible.\n \"\"\"\n if self._finalized:\n return\n\n # get highest power\n self.powers = set(chain.from_iterable([list(mat) for mat in self.matrices[\"E\"].values()]))\n self.max_power = max(self.powers)\n\n # check whether the system can be formulated in an explicit form\n self.max_temp_order = max(self.matrices[\"E\"])\n\n if len(self.matrices[\"E\"][self.max_temp_order]) > 1:\n # more than one power of the highest derivative -> implicit formulation\n raise NotImplementedError\n\n pb = next(iter(self.matrices[\"E\"][self.max_temp_order]))\n if pb != 1:\n # TODO raise the resulting last blocks to 1/pb\n raise NotImplementedError\n\n self.e_n_pb = self.matrices[\"E\"][self.max_temp_order][pb]\n self.dim_x = self.e_n_pb.shape[0] # length of the weight vector\n rank_e_n_pb = np.linalg.matrix_rank(self.e_n_pb)\n if rank_e_n_pb != max(self.e_n_pb.shape) or self.e_n_pb.shape[0] != self.e_n_pb.shape[1]:\n # this form cannot be used as dominant form\n self.singular = True\n else:\n self.singular = False\n self.e_n_pb_inv = np.linalg.inv(self.e_n_pb)\n\n self.dim_xb = self.max_temp_order * self.dim_x # dimension of the new system\n\n # input\n for derivatives in self.matrices.get(\"G\", {}).values():\n for power in derivatives.values():\n self.dim_u = max(self.dim_u, power.shape[1])\n\n def get_terms(self):\n \"\"\"\n Return all coefficient matrices of the canonical formulation.\n\n Return:\n Cascade of dictionaries: Structure: Type > Order > Exponent.\n \"\"\"\n return self.matrices\n\n def convert_to_state_space(self):\n \"\"\"\n Convert the canonical ode system of order n a into an ode system of\n order 1.\n\n Note:\n This will only work if the highest derivative order of the given\n form can be isolated. This is the case if the highest order is only\n present in one power and the equation system can therefore be\n solved for it.\n\n Return:\n :py:class:`.StateSpace` object:\n \"\"\"\n if not self._finalized:\n self.finalize()\n\n # system matrices A_*\n a_matrices = {}\n for p in self.powers:\n a_mat = np.zeros((self.dim_xb, self.dim_xb))\n\n # add integrator chain\n a_mat[:-self.dim_x:, self.dim_x:] = block_diag(\n *[np.eye(self.dim_x) for a in range(self.max_temp_order - 1)])\n\n # add \"block-line\" with feedback entries\n a_mat[-self.dim_x:, :] = -self._build_feedback(\"E\",\n p,\n self.e_n_pb_inv)\n a_matrices.update({p: a_mat})\n\n # input matrices B_*\n if \"G\" in self.matrices:\n max_temp_input_order = max(iter(self.matrices[\"G\"]))\n input_powers = set(chain.from_iterable(\n [list(mat) for mat in self.matrices[\"G\"].values()])\n )\n dim_u = next(iter(\n self.matrices[\"G\"][max_temp_input_order].values())).shape[1]\n\n # generate nested dict of B_o_p matrices where o is\n # derivative order and p is power\n b_matrices = {}\n for order in range(max_temp_input_order + 1):\n if order in self.matrices[\"G\"]:\n b_powers = {}\n for q in input_powers:\n b_mat = np.zeros((self.dim_xb, dim_u))\n # overwrite the last \"block-line\" in the matrices\n # with input entries\n b_mat[-self.dim_x:, :] = \\\n - self.e_n_pb_inv @ self.matrices[\"G\"][order][q]\n b_powers.update({q: b_mat})\n\n b_matrices.update({order: b_powers})\n else:\n b_matrices = None\n\n # the f vector aka the A matrix corresponding to the power zero\n f_mat = np.zeros((self.dim_xb,))\n if \"f\" in self.matrices:\n f_mat[-self.dim_x:] = self.matrices[\"f\"]\n\n a_matrices.update({0: f_mat})\n\n ss = StateSpace(a_matrices, b_matrices,\n input_handle=self.input_function)\n return ss\n\n def _build_feedback(self, entry, power, product_mat):\n max_order = max(sorted(self.matrices[entry]))\n entry_shape = next(iter(self.matrices[entry][max_order].values())).shape\n if entry == \"G\":\n # include highest order for system input\n max_order += 1\n\n blocks = [np.dot(product_mat, self.matrices[entry].get(order, {}).get(power, np.zeros(entry_shape)))\n for order in range(max_order)]\n return np.hstack(blocks)\n\n\nclass CanonicalEquation(object):\n \"\"\"\n Wrapper object, holding several entities of canonical forms for different\n weight-sets that form an equation when summed up.\n After instantiation, this object can be filled with information by passing\n the corresponding coefficients to :py:meth:`.add_to`. When the parsing\n process is completed and all coefficients have been collected, calling\n :py:meth:`.finalize` is required to compute all necessary information for\n further processing. When finalized, this object provides access to the\n dominant form of this equation.\n\n Args:\n name (str): Unique identifier of this equation.\n dominant_lbl (str): Label of the variable that dominates this equation.\n \"\"\"\n\n def __init__(self, name, dominant_lbl=None):\n self.name = name\n self.dominant_lbl = dominant_lbl\n self.dynamic_forms = {}\n self._static_form = CanonicalForm(self.name + \"_static\")\n self._finalized = False\n self._finalized_dynamic_forms = False\n\n def add_to(self, weight_label, term, val, column=None):\n \"\"\"\n Add the provided *val* to the canonical form for *weight_label*,\n see :py:meth:`.CanonicalForm.add_to` for further information.\n\n Args:\n weight_label (str): Basis to add onto.\n term: Coefficient to add onto, see :py:func:`~CanonicalForm.add_to`.\n val: Values to add.\n column (int): passed to :py:func:`~CanonicalForm.add_to`.\n \"\"\"\n if self._finalized:\n raise RuntimeError(\"Object has already been finalized, you are trying some nasty stuff there.\")\n\n if term[\"name\"] in \"fGL\":\n # hold f and g vector separately\n self._static_form.add_to(term, val, column)\n return\n\n if weight_label is None:\n raise ValueError(\"weight_label can only be none if target is f or G.\")\n\n if weight_label not in list(self.dynamic_forms.keys()):\n self.dynamic_forms[weight_label] = CanonicalForm(\"_\".join([self.name + weight_label]))\n\n self.dynamic_forms[weight_label].add_to(term, val)\n\n def finalize(self):\n \"\"\"\n Finalize the Object.\n After the complete formulation has been parsed and all terms have been\n sorted into this Object via :py:meth:`.add_to` this function has to be\n called to inform this object about it. Furthermore, the f and G parts of\n the static_form will be copied to the dominant form for easier\n state-space transformation.\n\n Note:\n This function must be called to use the :py:attr:`dominant_form`\n attribute.\n\n \"\"\"\n if self.dominant_lbl is None:\n raise ValueError(\"You have to set the dominant labels of the\\n\"\n \"canonical equation (weak form), for example\\n\"\n \"with pyinduct.simulation.set_dominant_labels().\")\n\n if not self._finalized_dynamic_forms:\n self.finalize_dynamic_forms()\n\n if self.dynamic_forms[self.dominant_lbl].singular:\n raise ValueError(\"The form that has to be chosen is singular.\")\n\n # copy static terms to dominant form to transform them correctly\n for letter in \"fG\":\n if letter in self._static_form.matrices:\n self.dynamic_forms[self.dominant_lbl].matrices.update({letter: self._static_form.matrices[letter]})\n\n self._finalized = True\n\n def finalize_dynamic_forms(self):\n \"\"\"\n Finalize all dynamic forms. See method\n :py:meth:`.CanonicalForm.finalize`.\n \"\"\"\n for lbl, form in self.dynamic_forms.items():\n form.finalize()\n self._finalized_dynamic_forms = True\n\n @property\n def static_form(self):\n \"\"\"\n :py:class:`.WeakForm` that does not depend on any weights.\n :return:\n \"\"\"\n return self._static_form\n\n @property\n def dominant_form(self):\n \"\"\"\n direct access to the dominant :py:class:`.CanonicalForm`.\n\n Note:\n :py:meth:`.finalize` must be called first.\n\n Returns:\n :py:class:`.CanonicalForm`: the dominant canonical form\n \"\"\"\n if self.dominant_lbl is None:\n raise RuntimeError(\"Dominant label is not defined! Use for\\n\"\n \"expample pyinduct.simulation.\"\n \"set_dominant_label or set it manually.\")\n return self.dynamic_forms[self.dominant_lbl]\n\n def get_static_terms(self):\n \"\"\"\n Return:\n Terms that do not depend on a certain weight set.\n \"\"\"\n return self._static_form.get_terms()\n\n def get_dynamic_terms(self):\n \"\"\"\n Return:\n dict: Dictionary of terms for each weight set.\n \"\"\"\n return {label: val.get_terms() for label, val in self.dynamic_forms.items()}\n\n @property\n def input_function(self):\n \"\"\"\n The input handles for the equation.\n \"\"\"\n return self._static_form.input_function\n\n def set_input_function(self, func):\n self._static_form.set_input_function(func)\n\n\ndef create_state_space(canonical_equations):\n \"\"\"\n Create a state-space system constituted by several\n :py:class:`.CanonicalEquations` (created by\n :py:func:`.parse_weak_formulation`)\n\n Args:\n canonical_equations: List of :py:class:`.CanonicalEquation`'s.\n\n Raises:\n ValueError: If compatibility criteria cannot be fulfilled\n\n Return:\n :py:class:`.StateSpace`: State-space representation of the approximated\n system\n \"\"\"\n set_dominant_labels(canonical_equations)\n\n if isinstance(canonical_equations, CanonicalEquation):\n # backward compatibility\n canonical_equations = [canonical_equations]\n\n # check whether the formulations are compatible\n for eq in canonical_equations:\n for lbl, form in eq.dynamic_forms.items():\n coupling_order = form.max_temp_order\n\n # search corresponding dominant form in other equations\n for _eq in canonical_equations:\n # check uniqueness of name - dom_lbl mappings\n if eq.name != _eq.name and eq.dominant_lbl == _eq.dominant_lbl:\n raise ValueError(\"A dominant form has to be unique over all given Equations\")\n\n # identify coupling terms\n if lbl == eq.dominant_lbl:\n break\n\n # identify corresponding dominant form\n if _eq.dominant_lbl != lbl:\n continue\n\n dominant_order = _eq.dominant_form.max_temp_order\n if dominant_order <= coupling_order:\n # dominant order has to be at least one higher than\n # the coupling order\n raise ValueError(\"Formulations are not compatible\")\n\n # transform dominant forms into state-space representation\n # and collect information\n dominant_state_spaces = {}\n state_space_props = Parameters(size=0,\n parts=OrderedDict(),\n powers=set(),\n input_powers=set(),\n dim_u=0,\n input=None)\n for eq in canonical_equations:\n dom_lbl = eq.dominant_lbl\n dom_form = eq.dominant_form\n dom_ss = dom_form.convert_to_state_space()\n dominant_state_spaces.update({dom_lbl: dom_ss})\n\n # collect some information\n state_space_props.parts[dom_lbl] = dict(start=copy(state_space_props.size),\n orig_size=dom_form.dim_x,\n size=dom_form.dim_xb,\n order=dom_form.max_temp_order - 1,\n sys_name=eq.name)\n state_space_props.powers.update(dom_form.powers)\n state_space_props.size += dom_form.dim_xb\n state_space_props.dim_u = max(state_space_props.dim_u, dom_form.dim_u)\n\n # update input handles\n if state_space_props.input is None:\n state_space_props.input = eq.input_function\n elif eq.input_function is not None:\n if not state_space_props.input is eq.input_function:\n raise ValueError(\"Only one input object allowed.\")\n\n # build new basis by concatenating the dominant bases of every equation\n if len(canonical_equations) == 1:\n new_name = next(iter(canonical_equations)).dominant_lbl\n else:\n base_info = copy(state_space_props.parts)\n base_lbls = state_space_props.parts.keys()\n for lbl in base_lbls:\n base_info[lbl].update({\"base\": get_base(lbl)})\n new_base = StackedBase(base_info)\n new_name = \"_\".join(base_lbls)\n register_base(new_name, new_base)\n\n # build new state transition matrices A_p_k for corresponding powers p_k of the state vector\n a_matrices = {}\n for p in state_space_props.powers:\n a_mat = np.zeros((state_space_props.size, state_space_props.size))\n for row_eq in canonical_equations:\n row_dom_lbl = row_eq.dominant_lbl\n row_dom_dim = state_space_props.parts[row_dom_lbl][\"size\"]\n row_dom_trans_mat = row_eq.dominant_form.e_n_pb_inv\n row_dom_sys_mat = dominant_state_spaces[row_dom_lbl].A.get(p, None)\n row_idx = state_space_props.parts[row_dom_lbl][\"start\"]\n\n for col_eq in canonical_equations:\n col_dom_lbl = col_eq.dominant_lbl\n\n # main diagonal\n if col_eq.name == row_eq.name:\n if row_dom_sys_mat is not None:\n a_mat[row_idx:row_idx + row_dom_dim, row_idx:row_idx + row_dom_dim] = row_dom_sys_mat\n continue\n\n # coupling terms\n if col_dom_lbl in row_eq.dynamic_forms:\n for order, mats in row_eq.dynamic_forms[col_dom_lbl].matrices[\"E\"].items():\n orig_mat = mats.get(p, None)\n if orig_mat is not None:\n # transform matrix with row-transformation matrix and add to last \"row\"\n # since it's not the dominant entry, revert sign change\n cop_mat = row_dom_trans_mat @ -orig_mat\n v_idx = row_idx + row_dom_dim - state_space_props.parts[row_dom_lbl][\"orig_size\"]\n col_idx = state_space_props.parts[col_dom_lbl][\"start\"]\n h_idx = col_idx + order * state_space_props.parts[col_dom_lbl][\"orig_size\"]\n a_mat[v_idx: v_idx + cop_mat.shape[0], h_idx: h_idx + cop_mat.shape[1]] = cop_mat\n\n a_matrices.update({p: a_mat})\n\n # build new state input matrices\n b_matrices = {}\n for name, dom_ss in dominant_state_spaces.items():\n for order, order_mats in dom_ss.B.items():\n b_order_mats = b_matrices.get(order, {})\n for p, power_mat in order_mats.items():\n b_power_mat = b_order_mats.get(p, np.zeros((state_space_props.size, state_space_props.dim_u)))\n\n # add entry to the last \"row\"\n r_idx = state_space_props.parts[name][\"start\"] # - state_space_props.parts[name][\"orig_size\"]\n b_power_mat[r_idx: r_idx + power_mat.shape[0], :power_mat.shape[1]] = power_mat\n\n b_order_mats.update({p: b_power_mat})\n b_matrices.update({order: b_order_mats})\n\n # build observer feedback handle\n def observer_feedback(**kwargs):\n res = np.zeros(state_space_props.size)\n for ce in canonical_equations:\n for fb in ce._static_form._observer_feedback:\n idx_a = (state_space_props.parts[ce.dominant_lbl][\"start\"] +\n state_space_props.parts[ce.dominant_lbl][\"orig_size\"] *\n state_space_props.parts[ce.dominant_lbl][\"order\"])\n idx_b = (idx_a +\n state_space_props.parts[ce.dominant_lbl][\"orig_size\"])\n\n kwargs.update(obs_weight_lbl=ce.dominant_lbl)\n res[idx_a: idx_b] += ce.dominant_form.e_n_pb_inv @ np.squeeze(\n fb._calc_output(**kwargs)[\"output\"], 1)\n\n kwargs.pop(\"obs_weight_lbl\")\n\n return res\n\n dom_ss = StateSpace(a_matrices, b_matrices, base_lbl=new_name,\n input_handle=state_space_props.input,\n obs_fb_handle=observer_feedback)\n return dom_ss\n\n\ndef parse_weak_formulation(weak_form, finalize=False, is_observer=False):\n r\"\"\"\n Parses a :py:class:`.WeakFormulation` that has been derived by projecting a\n partial differential equation an a set of test-functions. Within this\n process, the separating approximation\n :math:`x^n(z, t) = \\sum_{i=1}^n c_i^n(t) \\varphi_i^n(z)` is plugged into\n the equation and the separated spatial terms are evaluated, leading to a\n ordinary equation system for the weights :math:`c_i^n(t)`.\n\n Args:\n weak_form: Weak formulation of the pde.\n finalize (bool): Default: False. If you have already defined the\n dominant labels of the weak formulations you can set this to True.\n See :py:meth:`.CanonicalEquation.finalize`\n\n\n Return:\n :py:class:`.CanonicalEquation`: The spatially approximated equation in\n a canonical form.\n \"\"\"\n\n if not isinstance(weak_form, WeakFormulation):\n raise TypeError(\"Only able to parse WeakFormulation\")\n\n ce = CanonicalEquation(weak_form.name, weak_form.dominant_lbl)\n\n # handle each term\n for term in weak_form.terms:\n # extract Placeholders\n placeholders = dict(\n scalars=term.arg.get_arg_by_class(Scalars),\n functions=term.arg.get_arg_by_class(TestFunction),\n field_variables=term.arg.get_arg_by_class(FieldVariable),\n observer_fb=term.arg.get_arg_by_class(ObserverGain),\n inputs=term.arg.get_arg_by_class(Input))\n\n if is_observer:\n if placeholders[\"observer_fb\"]:\n raise ValueError(\n \"The weak formulation for an observer gain can not hold \\n\"\n \"the 'Placeholder' ObserverGain.\")\n if placeholders[\"field_variables\"]:\n raise ValueError(\n \"The weak formulation for an observer gain can not hold \\n\"\n \"the 'Placeholder' FieldVariable.\")\n if placeholders[\"scalars\"]:\n if any([plh.target_term[\"name\"] == 'E'\n for plh in placeholders[\"scalars\"]]):\n raise ValueError(\n \"The weak formulation for an observer gain can not \\n\"\n \"hold a 'Placeholder' Scalars with target_term == 'E'.\")\n\n # field variable terms: sort into E_np, E_n-1p, ..., E_0p\n if placeholders[\"field_variables\"]:\n assert isinstance(term, IntegralTerm)\n\n if len(placeholders[\"field_variables\"]) != 1:\n raise NotImplementedError\n\n field_var = placeholders[\"field_variables\"][0]\n if not field_var.simulation_compliant:\n msg = \"Shape- and test-function labels of FieldVariable must \" \\\n \"match for simulation purposes.\"\n raise ValueError(msg)\n\n temp_order = field_var.order[0]\n exponent = field_var.data[\"exponent\"]\n term_info = dict(name=\"E\", order=temp_order, exponent=exponent)\n base = get_base(field_var.data[\"func_lbl\"]).derive(field_var.order[1])\n shape_funcs = base.raise_to(exponent)\n\n if placeholders[\"inputs\"]:\n # essentially, this means that parts of the state-transition\n # matrix will be time dependent\n raise NotImplementedError\n\n if placeholders[\"functions\"]:\n # is the integrand a product?\n if len(placeholders[\"functions\"]) != 1:\n raise NotImplementedError\n func1 = placeholders[\"functions\"][0]\n base1 = get_base(func1.data[\"func_lbl\"]).derive(func1.order[1])\n result = calculate_scalar_product_matrix(base1, shape_funcs)\n else:\n # extract constant term and compute integral\n part1 = []\n for func1 in shape_funcs.fractions:\n from pyinduct.core import ComposedFunctionVector\n if isinstance(func1, ComposedFunctionVector):\n res = 0\n for f in func1.members[\"funcs\"]:\n area = domain_intersection(term.limits, f.nonzero)\n r, err = integrate_function(f, area)\n res += r\n for s in func1.members[\"scalars\"]:\n res += s\n else:\n area = domain_intersection(term.limits, func1.nonzero)\n res, err = integrate_function(func1, area)\n part1.append(res)\n\n a = Scalars(np.atleast_2d(part1))\n\n if placeholders[\"scalars\"]:\n b = placeholders[\"scalars\"][0]\n result = _compute_product_of_scalars([a, b])\n else:\n result = a.data\n\n ce.add_to(weight_label=field_var.data[\"weight_lbl\"],\n term=term_info,\n val=result * term.scale)\n continue\n\n # TestFunctions or pre evaluated terms, those can end up in E, f or G\n if placeholders[\"functions\"]:\n if not 1 <= len(placeholders[\"functions\"]) <= 2:\n raise NotImplementedError\n func1 = placeholders[\"functions\"][0]\n base1 = get_base(func1.data[\"func_lbl\"]).derive(func1.order[1])\n prod = base1.scalar_product_hint()\n\n if len(placeholders[\"functions\"]) == 1:\n # product of one function and something else, solve integral\n # first by faking 2nd factor\n base2 = [f.mul_neutral_element() for f in base1]\n else:\n func2 = placeholders[\"functions\"][1]\n base2 = get_base(func2.data[\"func_lbl\"]).derive(func2.order[1])\n\n # resolve equation term\n if isinstance(term, ScalarProductTerm):\n int_res = vectorize_scalar_product(base1, base2, prod)\n elif isinstance(term, IntegralTerm):\n from pyinduct.core import Base, ComposedFunctionVector\n # create base with multiplied fractions\n s_base = Base([f1.scale(f2) for f1, f2 in zip(base1, base2)])\n\n int_res = []\n for frac in s_base:\n # WARN I don't think that this case actually makes sense.\n if isinstance(frac, ComposedFunctionVector):\n res = 0\n for f in frac.members[\"funcs\"]:\n area = domain_intersection(term.limits, f.nonzero)\n r, err = integrate_function(f, area)\n res += r\n for s in frac.members[\"scalars\"]:\n res += s\n else:\n area = domain_intersection(term.limits, frac.nonzero)\n res, err = integrate_function(frac, area)\n int_res.append(res)\n else:\n raise NotImplementedError()\n\n # create column vector\n int_res = np.atleast_2d(int_res).T * term.scale\n\n # integral of the product of two functions\n if len(placeholders[\"functions\"]) == 2:\n term_info = dict(name=\"f\", exponent=0)\n ce.add_to(weight_label=None,\n term=term_info, val=int_res)\n continue\n\n if placeholders[\"scalars\"]:\n a = placeholders[\"scalars\"][0]\n b = Scalars(int_res)\n result = _compute_product_of_scalars([a, b])\n ce.add_to(weight_label=a.target_form,\n term=get_common_target(placeholders[\"scalars\"]),\n val=result)\n continue\n\n if placeholders[\"inputs\"]:\n if len(placeholders[\"inputs\"]) != 1:\n raise NotImplementedError\n input_var = placeholders[\"inputs\"][0]\n input_func = input_var.data[\"input\"]\n input_index = input_var.data[\"index\"]\n input_exp = input_var.data[\"exponent\"]\n input_order = input_var.order[0]\n term_info = dict(name=\"G\", order=input_order, exponent=input_exp)\n\n ce.add_to(weight_label=None,\n term=term_info,\n val=int_res,\n column=input_index)\n ce.set_input_function(input_func)\n continue\n\n if is_observer:\n result = np.vstack([integrate_function(func, func.nonzero)[0]\n for func in base1])\n ce.add_to(weight_label=func1.data[\"appr_lbl\"],\n term=dict(name=\"E\", order=0, exponent=1),\n val=result * term.scale)\n continue\n\n # pure scalar terms, sort into corresponding matrices\n if placeholders[\"scalars\"]:\n assert isinstance(term, ScalarTerm)\n\n result = _compute_product_of_scalars(placeholders[\"scalars\"])\n target = get_common_target(placeholders[\"scalars\"])\n target_form = get_common_form(placeholders)\n\n if placeholders[\"inputs\"]:\n input_var = placeholders[\"inputs\"][0]\n input_func = input_var.data[\"input\"]\n input_index = input_var.data[\"index\"]\n input_exp = input_var.data[\"exponent\"]\n input_order = input_var.order[0]\n\n term_info = dict(name=\"G\",\n order=input_order,\n exponent=input_exp)\n\n if target[\"name\"] == \"E\":\n # this would mean that the input term should appear in a\n # matrix like E1 or E2, again leading to a time dependant\n # state transition matrix\n raise NotImplementedError\n\n ce.add_to(weight_label=None, term=term_info,\n val=result * term.scale, column=input_index)\n ce.set_input_function(input_func)\n continue\n\n if is_observer:\n ce.add_to(\n weight_label=placeholders[\"scalars\"][0].target_term[\"test_appr_lbl\"],\n term=dict(name=\"E\", order=0, exponent=1),\n val=result * term.scale)\n else:\n ce.add_to(weight_label=target_form, term=target, val=result * term.scale)\n continue\n\n if placeholders[\"observer_fb\"]:\n ce.add_to(weight_label=None,\n term=dict(name=\"L\"),\n val=placeholders[\"observer_fb\"][0].data[\"obs_fb\"])\n continue\n\n # inform object that the parsing process is complete\n if finalize:\n ce.finalize()\n\n return ce\n\n\ndef parse_weak_formulations(weak_forms):\n \"\"\"\n Convenience wrapper for :py:func:`.parse_weak_formulation`.\n\n Args:\n weak_forms: List of :py:class:`.WeakFormulation`'s.\n\n Returns:\n List of :py:class:`.CanonicalEquation`'s.\n \"\"\"\n canonical_equations = list()\n for form in weak_forms:\n print(\">>> parse formulation {}\".format(form.name))\n ce = parse_weak_formulation(form)\n if ce.name in [ceq.name for ceq in canonical_equations]:\n raise ValueError((\"Name {} for CanonicalEquation already assigned, \"\n \"names must be unique.\").format(form.name))\n canonical_equations.append(ce)\n\n return canonical_equations\n\n\ndef _compute_product_of_scalars(scalars):\n \"\"\"\n Compute products for scalar terms while paying attention to some caveats\n\n Depending on how the data (coefficients for the lumped equations) of the\n terms were generated, it is either a column or a row vector.\n Special cases contain a simple scaling of all equations shape = (1, 1)\n and products of row and column vectors if two terms are provided.\n\n Args:\n scalars:\n\n Returns:\n\n \"\"\"\n data_shape1 = scalars[0].data.shape\n if len(scalars) < 1 or len(scalars) > 2:\n raise NotImplementedError()\n if len(scalars) == 1:\n # simple scaling of all terms\n if sum(data_shape1) > (max(data_shape1) + 1):\n # print(\"Workaround 1: Summing up all entries\")\n res = np.sum(scalars[0].data, axis=0, keepdims=True).T\n else:\n assert data_shape1[0] == 1 or data_shape1[1] == 1\n res = scalars[0].data\n return res\n\n # two arguments\n data_shape2 = scalars[1].data.shape\n if data_shape1 == data_shape2 and data_shape2[1] == 1:\n # element wise multiplication\n res = np.prod(np.array([scalars[0].data, scalars[1].data]), axis=0)\n elif data_shape1 == (1, 1) or data_shape2 == (1, 1):\n # a lumped term is present\n res = scalars[0].data * scalars[1].data\n else:\n # dyadic product\n try:\n if data_shape1[1] == 1:\n res = scalars[0].data @ scalars[1].data\n elif data_shape2[1] == 1:\n res = scalars[1].data @ scalars[0].data\n # TODO: handle dyadic product ComposedFunctionVector and Base in the same way\n elif data_shape1[1] == data_shape2[0]:\n # print(\"Workaround 2: Matrix product\")\n res = np.transpose(scalars[1].data) @ np.transpose(scalars[0].data)\n else:\n raise NotImplementedError\n except ValueError as e:\n raise ValueError(\"provided entries do not form a dyadic product\")\n\n return res\n\n\ndef simulate_state_space(state_space, initial_state, temp_domain, settings=None):\n r\"\"\"\n Wrapper to simulate a system given in state space form:\n\n .. math:: \\dot{q} = A_pq^p + A_{p-1}q^{p-1} + \\dotsb + A_0q + Bu.\n\n Args:\n state_space (:py:class:`.StateSpace`): State space formulation of the\n system.\n initial_state: Initial state vector of the system.\n temp_domain (:py:class:`.Domain`): Temporal domain object.\n settings (dict): Parameters to pass to the :py:func:`set_integrator`\n method of the :class:`scipy.ode` class, with the integrator name\n included under the key :obj:`name`.\n\n Return:\n tuple: Time :py:class:`.Domain` object and weights matrix.\n \"\"\"\n # if not isinstance(state_space, StateSpace):\n # raise TypeError\n\n q = [initial_state]\n t = [temp_domain[0]]\n\n r = ode(state_space.rhs)\n\n # TODO check for complex-valued matrices and use 'zvode'\n if settings:\n r.set_integrator(settings.pop(\"name\"), **settings)\n else:\n # use some sane defaults\n r.set_integrator(\n \"vode\",\n max_step=temp_domain.step,\n method=\"adams\",\n nsteps=1e3\n )\n\n r.set_initial_value(q[0], t[0])\n\n for t_step in temp_domain[1:]:\n qn = r.integrate(t_step)\n if not r.successful():\n warnings.warn(\"*** Error: Simulation aborted at t={} ***\".format(r.t))\n break\n\n t.append(r.t)\n q.append(qn)\n\n # create results\n q = np.array(q)\n\n return Domain(points=np.array(t), step=temp_domain.step), q\n\n\ndef evaluate_approximation(base_label, weights, temp_domain, spat_domain, spat_order=0, name=\"\"):\n \"\"\"\n Evaluate an approximation given by weights and functions at the points given\n in spatial and temporal steps.\n\n Args:\n weights: 2d np.ndarray where axis 1 is the weight index and axis 0 the\n temporal index.\n base_label (str): Functions to use for back-projection.\n temp_domain (:py:class:`.Domain`): For steps to evaluate at.\n spat_domain (:py:class:`.Domain`): For points to evaluate at (or in).\n spat_order: Spatial derivative order to use.\n name: Name to use.\n\n Return:\n :py:class:`.EvalData`\n \"\"\"\n funcs = get_base(base_label).derive(spat_order).fractions\n if weights.shape[1] != funcs.shape[0]:\n raise ValueError(\"weights (len={0}) have to fit provided functions \"\n \"(len={1})!\".format(weights.shape[1], funcs.size))\n\n # evaluate shape functions at given points\n shape_vals = np.array([func.evaluation_hint(spat_domain)\n for func in funcs]).T\n\n if shape_vals.ndim == 2:\n res = weights @ shape_vals.T\n else:\n # get extra dims to the front in both arrays\n extra_axes = range(1, shape_vals.ndim - 1)\n axes_idxs = np.array(extra_axes)\n b_shape_vals = np.swapaxes(shape_vals, 0, -1)\n b_shape_vals = np.moveaxis(b_shape_vals, axes_idxs, axes_idxs-1)\n w_shape = (*np.array(shape_vals.shape)[axes_idxs], *weights.shape)\n b_weights = np.broadcast_to(weights, w_shape)\n b_res = b_weights @ b_shape_vals\n res = np.moveaxis(b_res, axes_idxs-1, axes_idxs+1)\n\n ed = EvalData([temp_domain.points, spat_domain.points], res,\n name=name, fill_axes=True)\n return ed\n\n\ndef set_dominant_labels(canonical_equations, finalize=True):\n \"\"\"\n Set the dominant label (*dominant_lbl*) member of all given canonical\n equations and check if the problem formulation is valid (see background\n section: http://pyinduct.readthedocs.io/en/latest/).\n\n If the dominant label of one or more :py:class:`.CanonicalEquation`\n is already defined, the function raise a UserWarning if the (pre)defined\n dominant label(s) are not valid.\n\n Args:\n canonical_equations: List of :py:class:`.CanonicalEquation` instances.\n finalize (bool): Finalize the equations? Default: True.\n \"\"\"\n if isinstance(canonical_equations, CanonicalEquation):\n canonical_equations = [canonical_equations]\n\n # collect all involved labels\n labels = set(\n chain(*[list(ce.dynamic_forms.keys()) for ce in canonical_equations]))\n\n if len(labels) != len(canonical_equations):\n raise ValueError(\"The N defined canonical equations (weak forms)\\n\"\n \"must hold exactly N different weight labels!\\n\"\n \"But your {} canonical equation(s) (weak form(s))\\n\"\n \"hold {} weight label(s)!\"\n \"\".format(len(canonical_equations),\n len(labels)))\n\n max_orders = dict()\n for ce in canonical_equations:\n ce.finalize_dynamic_forms()\n for lbl in list(ce.dynamic_forms.keys()):\n max_order = dict(\n ((\"max_order\", ce.dynamic_forms[lbl].max_temp_order),\n (\"can_eqs\", [ce])))\n if lbl not in max_orders or \\\n max_orders[lbl][\"max_order\"] < max_order[\"max_order\"]:\n max_orders[lbl] = max_order\n elif max_orders[lbl][\"max_order\"] == max_order[\"max_order\"]:\n max_orders[lbl][\"can_eqs\"].append(\n max_order[\"can_eqs\"][0])\n\n non_valid1 = [(lbl, max_orders[lbl])\n for lbl in labels if len(max_orders[lbl][\"can_eqs\"]) > 1]\n if non_valid1:\n raise ValueError(\"The highest time derivative from a certain weight\\n\"\n \"label may only occur in one canonical equation. But\\n\"\n \"each of the canonical equations {} holds the\\n\"\n \"weight label '{}' with order {} in time.\"\n \"\".format(non_valid1[0][1][\"can_eqs\"][0].name,\n non_valid1[0][0],\n non_valid1[0][1][\"max_order\"]))\n\n non_valid2 = [lbl for lbl in labels if max_orders[lbl][\"max_order\"] == 0]\n if non_valid2:\n raise ValueError(\"The defined problem leads to an differential\\n\"\n \"algebraic equation, since there is no time\\n\"\n \"derivative for the weights {}. Such problems are\\n\"\n \"not considered in pyinduct, yet.\"\n \"\".format(non_valid2))\n\n # set/check dominant labels\n for lbl in labels:\n pre_lbl = max_orders[lbl][\"can_eqs\"][0].dominant_lbl\n max_orders[lbl][\"can_eqs\"][0].dominant_lbl = lbl\n\n if pre_lbl is not None and pre_lbl != lbl:\n warnings.warn(\"\\n Predefined dominant label '{}' from\\n\"\n \"canonical equation / weak form '{}' not valid!\\n\"\n \"It will be overwritten with the label '{}'.\"\n \"\".format(pre_lbl,\n max_orders[lbl][\"can_eqs\"][0].name,\n lbl),\n UserWarning)\n\n if finalize:\n for ce in canonical_equations:\n ce.finalize()\n\n\nclass SimulationInputVector(SimulationInput):\n \"\"\"\n A simulation input which combines :py:class:`.SimulationInput` objects into\n a column vector.\n\n Args:\n input_vector (array_like): Simulation inputs to stack.\n \"\"\"\n\n def __init__(self, input_vector):\n SimulationInput.__init__(self)\n self._input_vector = self._sanitize_input_vector(input_vector)\n\n def _sanitize_input_vector(self, input_vector):\n if hasattr(input_vector, \"__len__\") and len(input_vector) == 0:\n return list()\n else:\n return sanitize_input(input_vector, SimulationInput)\n\n def __iter__(self):\n return iter(self._input_vector)\n\n def __getitem__(self, item):\n return self._input_vector[item]\n\n def append(self, input_vector):\n \"\"\"\n Add an input to the vector.\n \"\"\"\n inputs = self._sanitize_input_vector(input_vector)\n self._input_vector = np.hstack((self._input_vector, inputs))\n\n def _calc_output(self, **kwargs):\n output = list()\n for input in self._input_vector:\n output.append(input(**kwargs))\n\n return dict(output=output)\n\n"
] |
[
[
"numpy.real_if_close",
"numpy.imag",
"numpy.abs",
"numpy.linspace",
"numpy.eye",
"numpy.roots",
"numpy.exp",
"numpy.real",
"numpy.vectorize",
"scipy.integrate.quad",
"numpy.array",
"numpy.testing.assert_array_almost_equal"
],
[
"numpy.linalg.matrix_rank",
"numpy.all",
"numpy.zeros_like",
"numpy.moveaxis",
"numpy.hstack",
"numpy.swapaxes",
"numpy.eye",
"numpy.atleast_1d",
"scipy.interpolate.interp1d",
"numpy.apply_along_axis",
"numpy.zeros",
"numpy.power",
"numpy.isnan",
"numpy.linalg.inv",
"numpy.atleast_2d",
"numpy.transpose",
"numpy.array",
"numpy.sum",
"numpy.broadcast_to",
"scipy.integrate.ode"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"1.3",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
Kanikamiglani31/tensorflow
|
[
"428cdeda09aef81e958eeb274b83d27ad635b57b"
] |
[
"tensorflow/python/keras/engine/training.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\"\"\"Training-related part of the Keras engine.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\nimport itertools\n\nfrom tensorflow.python.autograph.lang import directives\nfrom tensorflow.python.distribute import distribute_coordinator as dc\nfrom tensorflow.python.distribute import distribute_coordinator_context as dc_context\nfrom tensorflow.python.distribute import distribution_strategy_context as ds_context\nfrom tensorflow.python.distribute import parameter_server_strategy\nfrom tensorflow.python.distribute import values as ds_values\nfrom tensorflow.python.eager import backprop\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.eager import monitoring\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.keras import callbacks as callbacks_module\nfrom tensorflow.python.keras import optimizers\nfrom tensorflow.python.keras.distribute import distributed_training_utils as dist_utils\nfrom tensorflow.python.keras.engine import compile_utils\nfrom tensorflow.python.keras.engine import data_adapter\nfrom tensorflow.python.keras.engine import network\nfrom tensorflow.python.keras.engine import training_utils\nfrom tensorflow.python.keras.mixed_precision.experimental import loss_scale_optimizer as lso\nfrom tensorflow.python.keras.saving.saved_model import model_serialization\nfrom tensorflow.python.keras.utils import tf_utils\nfrom tensorflow.python.keras.utils import version_utils\nfrom tensorflow.python.keras.utils.mode_keys import ModeKeys\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.ops import summary_ops_v2\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.ops.ragged import ragged_concat_ops\nfrom tensorflow.python.ops.ragged import ragged_tensor\nfrom tensorflow.python.profiler import trace\nfrom tensorflow.python.training.tracking import base as trackable\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util import tf_decorator\nfrom tensorflow.python.util.tf_export import keras_export\n\n\n_keras_api_gauge = monitoring.BoolGauge('/tensorflow/api/keras',\n 'keras api usage', 'method')\n\n\ndef enable_multi_worker(method):\n \"\"\"Decorator that handles running `method` with multi-worker strategy.\"\"\"\n\n def _method_wrapper(self, *args, **kwargs):\n if not self._in_multi_worker_mode(): # pylint: disable=protected-access\n return method(self, *args, **kwargs)\n\n # Running inside `run_distribute_coordinator` already.\n if dc_context.get_current_worker_context():\n return method(self, *args, **kwargs)\n\n return dc.run_distribute_coordinator(\n lambda _: method(self, *args, **kwargs),\n self.distribute_strategy,\n mode=dc.CoordinatorMode.INDEPENDENT_WORKER)\n\n return tf_decorator.make_decorator(\n target=method, decorator_func=_method_wrapper)\n\n\ndef disable_multi_worker(method):\n \"\"\"Decorator that disallows multi-worker use of `method`.\"\"\"\n\n def _method_wrapper(self, *args, **kwargs):\n if self._in_multi_worker_mode(): # pylint: disable=protected-access\n raise ValueError('{} is not supported in multi-worker mode.'.format(\n method.__name__))\n return method(self, *args, **kwargs)\n\n return tf_decorator.make_decorator(\n target=method, decorator_func=_method_wrapper)\n\n\n@keras_export('keras.Model', 'keras.models.Model')\nclass Model(network.Network, version_utils.ModelVersionSelector):\n \"\"\"`Model` groups layers into an object with training and inference features.\n\n Arguments:\n inputs: The input(s) of the model: a `keras.Input` object or list of\n `keras.Input` objects.\n outputs: The output(s) of the model. See Functional API example below.\n name: String, the name of the model.\n\n There are two ways to instantiate a `Model`:\n\n 1 - With the \"Functional API\", where you start from `Input`,\n you chain layer calls to specify the model's forward pass,\n and finally you create your model from inputs and outputs:\n\n ```python\n import tensorflow as tf\n\n inputs = tf.keras.Input(shape=(3,))\n x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)\n outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)\n model = tf.keras.Model(inputs=inputs, outputs=outputs)\n ```\n\n 2 - By subclassing the `Model` class: in that case, you should define your\n layers in `__init__` and you should implement the model's forward pass\n in `call`.\n\n ```python\n import tensorflow as tf\n\n class MyModel(tf.keras.Model):\n\n def __init__(self):\n super(MyModel, self).__init__()\n self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)\n self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)\n\n def call(self, inputs):\n x = self.dense1(inputs)\n return self.dense2(x)\n\n model = MyModel()\n ```\n\n If you subclass `Model`, you can optionally have\n a `training` argument (boolean) in `call`, which you can use to specify\n a different behavior in training and inference:\n\n ```python\n import tensorflow as tf\n\n class MyModel(tf.keras.Model):\n\n def __init__(self):\n super(MyModel, self).__init__()\n self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)\n self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)\n self.dropout = tf.keras.layers.Dropout(0.5)\n\n def call(self, inputs, training=False):\n x = self.dense1(inputs)\n if training:\n x = self.dropout(x, training=training)\n return self.dense2(x)\n\n model = MyModel()\n ```\n\n Once the model is created, you can config the model with losses and metrics\n with `model.compile()`, train the model with `model.fit()`, or use the model\n to do prediction with `model.predict()`.\n \"\"\"\n _TF_MODULE_IGNORED_PROPERTIES = frozenset(\n itertools.chain(('_train_counter', '_test_counter', '_predict_counter',\n '_steps_per_execution'),\n network.Network._TF_MODULE_IGNORED_PROPERTIES)) # pylint: disable=protected-access\n\n def __init__(self, *args, **kwargs):\n super(Model, self).__init__(*args, **kwargs)\n _keras_api_gauge.get_cell('model').set(True)\n # Model must be created under scope of DistStrat it will be trained with.\n if ds_context.has_strategy():\n self._distribution_strategy = ds_context.get_strategy()\n else:\n self._distribution_strategy = None\n # Defaults to value of `tf.config.experimental_functions_run_eagerly`.\n self._run_eagerly = None\n self.stop_training = False\n # Initialize cache attrs.\n self._reset_compile_cache()\n\n # Fault-tolerance handler. Set in `ModelCheckpoint`.\n self._training_state = None\n self.history = None\n\n # These objects are used in the default `Model.compile`. They are not\n # guaranteed to be set after `Model.compile` is called, as users can\n # override compile with custom logic.\n self.compiled_loss = None\n self.compiled_metrics = None\n\n self._steps_per_execution = None\n\n self._init_batch_counters()\n\n @trackable.no_automatic_dependency_tracking\n def _init_batch_counters(self):\n # Untracked Variables, used to keep track of mini-batches seen in `fit`,\n # `evaluate`, and `predict`.\n agg = variables.VariableAggregationV2.ONLY_FIRST_REPLICA\n self._train_counter = variables.Variable(0, dtype='int64', aggregation=agg)\n self._test_counter = variables.Variable(0, dtype='int64', aggregation=agg)\n self._predict_counter = variables.Variable(\n 0, dtype='int64', aggregation=agg)\n\n def get_weights(self):\n \"\"\"Retrieves the weights of the model.\n\n Returns:\n A flat list of Numpy arrays.\n \"\"\"\n with self.distribute_strategy.scope():\n return super(Model, self).get_weights()\n\n def load_weights(self, filepath, by_name=False, skip_mismatch=False):\n \"\"\"Loads all layer weights, either from a TensorFlow or an HDF5 weight file.\n\n If `by_name` is False weights are loaded based on the network's\n topology. This means the architecture should be the same as when the weights\n were saved. Note that layers that don't have weights are not taken into\n account in the topological ordering, so adding or removing layers is fine as\n long as they don't have weights.\n\n If `by_name` is True, weights are loaded into layers only if they share the\n same name. This is useful for fine-tuning or transfer-learning models where\n some of the layers have changed.\n\n Only topological loading (`by_name=False`) is supported when loading weights\n from the TensorFlow format. Note that topological loading differs slightly\n between TensorFlow and HDF5 formats for user-defined classes inheriting from\n `tf.keras.Model`: HDF5 loads based on a flattened list of weights, while the\n TensorFlow format loads based on the object-local names of attributes to\n which layers are assigned in the `Model`'s constructor.\n\n Arguments:\n filepath: String, path to the weights file to load. For weight files in\n TensorFlow format, this is the file prefix (the same as was passed\n to `save_weights`).\n by_name: Boolean, whether to load weights by name or by topological\n order. Only topological loading is supported for weight files in\n TensorFlow format.\n skip_mismatch: Boolean, whether to skip loading of layers where there is\n a mismatch in the number of weights, or a mismatch in the shape of\n the weight (only valid when `by_name=True`).\n\n Returns:\n When loading a weight file in TensorFlow format, returns the same status\n object as `tf.train.Checkpoint.restore`. When graph building, restore\n ops are run automatically as soon as the network is built (on first call\n for user-defined classes inheriting from `Model`, immediately if it is\n already built).\n\n When loading weights in HDF5 format, returns `None`.\n\n Raises:\n ImportError: If h5py is not available and the weight file is in HDF5\n format.\n ValueError: If `skip_mismatch` is set to `True` when `by_name` is\n `False`.\n \"\"\"\n if dist_utils.is_tpu_strategy(self._distribution_strategy):\n if (self._distribution_strategy.extended.steps_per_run > 1 and\n (not network._is_hdf5_filepath(filepath))): # pylint: disable=protected-access\n raise ValueError('Load weights is not yet supported with TPUStrategy '\n 'with steps_per_run greater than 1.')\n return super(Model, self).load_weights(filepath, by_name, skip_mismatch)\n\n def compile(self,\n optimizer='rmsprop',\n loss=None,\n metrics=None,\n loss_weights=None,\n weighted_metrics=None,\n run_eagerly=None,\n **kwargs):\n \"\"\"Configures the model for training.\n\n Arguments:\n optimizer: String (name of optimizer) or optimizer instance. See\n `tf.keras.optimizers`.\n loss: String (name of objective function), objective function or\n `tf.keras.losses.Loss` instance. See `tf.keras.losses`. An objective\n function is any callable with the signature `loss = fn(y_true,\n y_pred)`, where y_true = ground truth values with shape =\n `[batch_size, d0, .. dN]`, except sparse loss functions such as sparse\n categorical crossentropy where shape = `[batch_size, d0, .. dN-1]`.\n y_pred = predicted values with shape = `[batch_size, d0, .. dN]`. It\n returns a weighted loss float tensor. If a custom `Loss` instance is\n used and reduction is set to NONE, return value has the shape\n [batch_size, d0, .. dN-1] ie. per-sample or per-timestep loss values;\n otherwise, it is a scalar. If the model has multiple outputs, you can\n use a different loss on each output by passing a dictionary or a list\n of losses. The loss value that will be minimized by the model will\n then be the sum of all individual losses.\n metrics: List of metrics to be evaluated by the model during training\n and testing. Each of this can be a string (name of a built-in\n function), function or a `tf.keras.metrics.Metric` instance. See\n `tf.keras.metrics`. Typically you will use `metrics=['accuracy']`. A\n function is any callable with the signature `result = fn(y_true,\n y_pred)`. To specify different metrics for different outputs of a\n multi-output model, you could also pass a dictionary, such as\n `metrics={'output_a': 'accuracy', 'output_b': ['accuracy', 'mse']}`.\n You can also pass a list (len = len(outputs)) of lists of metrics\n such as `metrics=[['accuracy'], ['accuracy', 'mse']]` or\n `metrics=['accuracy', ['accuracy', 'mse']]`. When you pass the\n strings 'accuracy' or 'acc', we convert this to one of\n `tf.keras.metrics.BinaryAccuracy`,\n `tf.keras.metrics.CategoricalAccuracy`,\n `tf.keras.metrics.SparseCategoricalAccuracy` based on the loss\n function used and the model output shape. We do a similar\n conversion for the strings 'crossentropy' and 'ce' as well.\n loss_weights: Optional list or dictionary specifying scalar coefficients\n (Python floats) to weight the loss contributions of different model\n outputs. The loss value that will be minimized by the model will then\n be the *weighted sum* of all individual losses, weighted by the\n `loss_weights` coefficients.\n If a list, it is expected to have a 1:1 mapping to the model's\n outputs. If a dict, it is expected to map output names (strings)\n to scalar coefficients.\n weighted_metrics: List of metrics to be evaluated and weighted by\n sample_weight or class_weight during training and testing.\n run_eagerly: Bool. Defaults to `False`. If `True`, this `Model`'s\n logic will not be wrapped in a `tf.function`. Recommended to leave\n this as `None` unless your `Model` cannot be run inside a\n `tf.function`.\n **kwargs: Any additional arguments. Supported arguments:\n - `experimental_steps_per_execution`: Int. The number of batches to\n run during each `tf.function` call. Running multiple batches\n inside a single `tf.function` call can greatly improve performance\n on TPUs or small models with a large Python overhead. Note that if\n this value is set to `N`, `Callback.on_batch` methods will only be\n called every `N` batches. This currently defaults to `1`. At most,\n one full epoch will be run each execution. If a number larger than\n the size of the epoch is passed, the execution will be truncated\n to the size of the epoch.\n - `sample_weight_mode` for backward compatibility.\n\n Raises:\n ValueError: In case of invalid arguments for\n `optimizer`, `loss` or `metrics`.\n \"\"\"\n _keras_api_gauge.get_cell('compile').set(True)\n with self.distribute_strategy.scope():\n self._validate_compile(optimizer, metrics, **kwargs)\n self._run_eagerly = run_eagerly\n\n self.optimizer = self._get_optimizer(optimizer)\n self.compiled_loss = compile_utils.LossesContainer(\n loss, loss_weights, output_names=self.output_names)\n self.compiled_metrics = compile_utils.MetricsContainer(\n metrics, weighted_metrics, output_names=self.output_names)\n\n experimental_steps_per_execution = kwargs.pop(\n 'experimental_steps_per_execution', 1)\n self._configure_steps_per_execution(experimental_steps_per_execution)\n\n # Initializes attrs that are reset each time `compile` is called.\n self._reset_compile_cache()\n self._is_compiled = True\n\n self.loss = loss or {} # Backwards compat.\n\n def _get_optimizer(self, optimizer):\n \"\"\"Wraps `optimizer` in `LossScaleOptimizer` if necessary.\"\"\"\n\n def _get_single_optimizer(opt):\n opt = optimizers.get(opt)\n if (self._dtype_policy.loss_scale is not None and\n not isinstance(opt, lso.LossScaleOptimizer)):\n opt = lso.LossScaleOptimizer(opt, self._dtype_policy.loss_scale)\n return opt\n\n return nest.map_structure(_get_single_optimizer, optimizer)\n\n @trackable.no_automatic_dependency_tracking\n def _reset_compile_cache(self):\n self.train_function = None\n self.test_function = None\n self.predict_function = None\n\n # Used to cache `trainable` attr of `Layer`s for `fit`.\n self._compiled_trainable_state = self._get_trainable_state()\n\n @trackable.no_automatic_dependency_tracking\n def _configure_steps_per_execution(self, steps_per_execution):\n self._steps_per_execution = variables.Variable(\n steps_per_execution,\n dtype='int64',\n aggregation=variables.VariableAggregationV2.ONLY_FIRST_REPLICA)\n\n @property\n def metrics(self):\n \"\"\"Returns the model's metrics added using `compile`, `add_metric` APIs.\n\n Note: Metrics passed to `compile()` are available only after a `keras.Model`\n has been trained/evaluated on actual data.\n\n Examples:\n\n >>> inputs = tf.keras.layers.Input(shape=(3,))\n >>> outputs = tf.keras.layers.Dense(2)(inputs)\n >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)\n >>> model.compile(optimizer=\"Adam\", loss=\"mse\", metrics=[\"mae\"])\n >>> [m.name for m in model.metrics]\n []\n\n >>> x = np.random.random((2, 3))\n >>> y = np.random.randint(0, 2, (2, 2))\n >>> model.fit(x, y)\n >>> [m.name for m in model.metrics]\n ['loss', 'mae']\n\n >>> inputs = tf.keras.layers.Input(shape=(3,))\n >>> d = tf.keras.layers.Dense(2, name='out')\n >>> output_1 = d(inputs)\n >>> output_2 = d(inputs)\n >>> model = tf.keras.models.Model(\n ... inputs=inputs, outputs=[output_1, output_2])\n >>> model.add_metric(\n ... tf.reduce_sum(output_2), name='mean', aggregation='mean')\n >>> model.compile(optimizer=\"Adam\", loss=\"mse\", metrics=[\"mae\", \"acc\"])\n >>> model.fit(x, (y, y))\n >>> [m.name for m in model.metrics]\n ['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',\n 'out_1_acc', 'mean']\n\n \"\"\"\n metrics = []\n if self._is_compiled:\n # TODO(omalleyt): Track `LossesContainer` and `MetricsContainer` objects\n # so that attr names are not load-bearing.\n if self.compiled_loss is not None:\n metrics += self.compiled_loss.metrics\n if self.compiled_metrics is not None:\n metrics += self.compiled_metrics.metrics\n\n all_layers = self._gather_unique_layers()\n for l in all_layers:\n metrics.extend(l._metrics) # pylint: disable=protected-access\n return metrics\n\n @property\n def metrics_names(self):\n \"\"\"Returns the model's display labels for all outputs.\n\n Note: `metrics_names` are available only after a `keras.Model` has been\n trained/evaluated on actual data.\n\n Examples:\n\n >>> inputs = tf.keras.layers.Input(shape=(3,))\n >>> outputs = tf.keras.layers.Dense(2)(inputs)\n >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)\n >>> model.compile(optimizer=\"Adam\", loss=\"mse\", metrics=[\"mae\"])\n >>> model.metrics_names\n []\n\n >>> x = np.random.random((2, 3))\n >>> y = np.random.randint(0, 2, (2, 2))\n >>> model.fit(x, y)\n >>> model.metrics_names\n ['loss', 'mae']\n\n >>> inputs = tf.keras.layers.Input(shape=(3,))\n >>> d = tf.keras.layers.Dense(2, name='out')\n >>> output_1 = d(inputs)\n >>> output_2 = d(inputs)\n >>> model = tf.keras.models.Model(\n ... inputs=inputs, outputs=[output_1, output_2])\n >>> model.compile(optimizer=\"Adam\", loss=\"mse\", metrics=[\"mae\", \"acc\"])\n >>> model.fit(x, (y, y))\n >>> model.metrics_names\n ['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',\n 'out_1_acc']\n\n \"\"\"\n\n # This property includes all output names including `loss` and per-output\n # losses for backward compatibility.\n return [m.name for m in self.metrics]\n\n @property\n def distribute_strategy(self):\n \"\"\"The `tf.distribute.Strategy` this model was created under.\"\"\"\n return self._distribution_strategy or ds_context.get_strategy()\n\n @property\n def run_eagerly(self):\n \"\"\"Settable attribute indicating whether the model should run eagerly.\n\n Running eagerly means that your model will be run step by step,\n like Python code. Your model might run slower, but it should become easier\n for you to debug it by stepping into individual layer calls.\n\n By default, we will attempt to compile your model to a static graph to\n deliver the best execution performance.\n\n Returns:\n Boolean, whether the model should run eagerly.\n \"\"\"\n if self._run_eagerly is True and not context.executing_eagerly():\n raise ValueError('You can only set `run_eagerly=True` if eager execution '\n 'is enabled.')\n if not self.dynamic:\n if self._run_eagerly is None:\n # Respect `tf.config.experimental_run_functions_eagerly` unless\n # `run_eagerly` was explicitly passed to `compile`.\n return def_function.RUN_FUNCTIONS_EAGERLY\n else:\n return self._run_eagerly\n else:\n if not context.executing_eagerly():\n raise ValueError('Your model contains layers that can only be '\n 'successfully run in eager execution (layers '\n 'constructed with `dynamic=True`). '\n 'You must enable eager execution with '\n '`tf.enable_eager_execution()`.')\n if self._run_eagerly is False:\n # TODO(fchollet): consider using py_func to enable this.\n raise ValueError('Your model contains layers that can only be '\n 'successfully run in eager execution (layers '\n 'constructed with `dynamic=True`). '\n 'You cannot set `run_eagerly=False`.')\n return context.executing_eagerly()\n\n @run_eagerly.setter\n def run_eagerly(self, value):\n self._run_eagerly = value\n\n def train_step(self, data):\n \"\"\"The logic for one training step.\n\n This method can be overridden to support custom training logic.\n This method is called by `Model.make_train_function`.\n\n This method should contain the mathemetical logic for one step of training.\n This typically includes the forward pass, loss calculation, backpropagation,\n and metric updates.\n\n Configuration details for *how* this logic is run (e.g. `tf.function` and\n `tf.distribute.Strategy` settings), should be left to\n `Model.make_train_function`, which can also be overridden.\n\n Arguments:\n data: A nested structure of `Tensor`s.\n\n Returns:\n A `dict` containing values that will be passed to\n `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the\n values of the `Model`'s metrics are returned. Example:\n `{'loss': 0.2, 'accuracy': 0.7}`.\n\n \"\"\"\n # These are the only transformations `Model.fit` applies to user-input\n # data when a `tf.data.Dataset` is provided. These utilities will be exposed\n # publicly.\n data = data_adapter.expand_1d(data)\n x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)\n\n with backprop.GradientTape() as tape:\n y_pred = self(x, training=True)\n loss = self.compiled_loss(\n y, y_pred, sample_weight, regularization_losses=self.losses)\n # For custom training steps, users can just write:\n # trainable_variables = self.trainable_variables\n # gradients = tape.gradient(loss, trainable_variables)\n # self.optimizer.apply_gradients(zip(gradients, trainable_variables))\n # The _minimize call does a few extra steps unnecessary in most cases,\n # such as loss scaling and gradient clipping.\n _minimize(self.distribute_strategy, tape, self.optimizer, loss,\n self.trainable_variables)\n\n self.compiled_metrics.update_state(y, y_pred, sample_weight)\n return {m.name: m.result() for m in self.metrics}\n\n def make_train_function(self):\n \"\"\"Creates a function that executes one step of training.\n\n This method can be overridden to support custom training logic.\n This method is called by `Model.fit` and `Model.train_on_batch`.\n\n Typically, this method directly controls `tf.function` and\n `tf.distribute.Strategy` settings, and delegates the actual training\n logic to `Model.train_step`.\n\n This function is cached the first time `Model.fit` or\n `Model.train_on_batch` is called. The cache is cleared whenever\n `Model.compile` is called.\n\n Returns:\n Function. The function created by this method should accept a\n `tf.data.Iterator`, and return a `dict` containing values that will\n be passed to `tf.keras.Callbacks.on_train_batch_end`, such as\n `{'loss': 0.2, 'accuracy': 0.7}`.\n \"\"\"\n if self.train_function is not None:\n return self.train_function\n\n def step_function(model, iterator):\n \"\"\"Runs a single training step.\"\"\"\n\n def run_step(data):\n outputs = model.train_step(data)\n # Ensure counter is updated only if `train_step` succeeds.\n with ops.control_dependencies(_minimum_control_deps(outputs)):\n model._train_counter.assign_add(1) # pylint: disable=protected-access\n return outputs\n\n data = next(iterator)\n outputs = model.distribute_strategy.run(run_step, args=(data,))\n outputs = reduce_per_replica(\n outputs, self.distribute_strategy, reduction='first')\n write_scalar_summaries(outputs, step=model._train_counter) # pylint: disable=protected-access\n return outputs\n\n if self._steps_per_execution.numpy().item() == 1:\n\n def train_function(iterator):\n \"\"\"Runs a training execution with one step.\"\"\"\n return step_function(self, iterator)\n\n else:\n\n def train_function(iterator):\n \"\"\"Runs a training execution with multiple steps.\"\"\"\n outputs = step_function(self, iterator)\n for _ in math_ops.range(self._steps_per_execution - 1):\n outputs = step_function(self, iterator)\n return outputs\n\n if not self.run_eagerly:\n train_function = def_function.function(\n train_function, experimental_relax_shapes=True)\n\n self.train_function = train_function\n return self.train_function\n\n @enable_multi_worker\n def fit(self,\n x=None,\n y=None,\n batch_size=None,\n epochs=1,\n verbose=1,\n callbacks=None,\n validation_split=0.,\n validation_data=None,\n shuffle=True,\n class_weight=None,\n sample_weight=None,\n initial_epoch=0,\n steps_per_epoch=None,\n validation_steps=None,\n validation_batch_size=None,\n validation_freq=1,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n **kwargs):\n \"\"\"Trains the model for a fixed number of epochs (iterations on a dataset).\n\n Arguments:\n x: Input data. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A dict mapping input names to the corresponding array/tensors,\n if the model has named inputs.\n - A `tf.data` dataset. Should return a tuple\n of either `(inputs, targets)` or\n `(inputs, targets, sample_weights)`.\n - A generator or `keras.utils.Sequence` returning `(inputs, targets)`\n or `(inputs, targets, sample_weights)`.\n A more detailed description of unpacking behavior for iterator types\n (Dataset, generator, Sequence) is given below.\n y: Target data. Like the input data `x`,\n it could be either Numpy array(s) or TensorFlow tensor(s).\n It should be consistent with `x` (you cannot have Numpy inputs and\n tensor targets, or inversely). If `x` is a dataset, generator,\n or `keras.utils.Sequence` instance, `y` should\n not be specified (since targets will be obtained from `x`).\n batch_size: Integer or `None`.\n Number of samples per gradient update.\n If unspecified, `batch_size` will default to 32.\n Do not specify the `batch_size` if your data is in the\n form of datasets, generators, or `keras.utils.Sequence` instances\n (since they generate batches).\n epochs: Integer. Number of epochs to train the model.\n An epoch is an iteration over the entire `x` and `y`\n data provided.\n Note that in conjunction with `initial_epoch`,\n `epochs` is to be understood as \"final epoch\".\n The model is not trained for a number of iterations\n given by `epochs`, but merely until the epoch\n of index `epochs` is reached.\n verbose: 0, 1, or 2. Verbosity mode.\n 0 = silent, 1 = progress bar, 2 = one line per epoch.\n Note that the progress bar is not particularly useful when\n logged to a file, so verbose=2 is recommended when not running\n interactively (eg, in a production environment).\n callbacks: List of `keras.callbacks.Callback` instances.\n List of callbacks to apply during training.\n See `tf.keras.callbacks`.\n validation_split: Float between 0 and 1.\n Fraction of the training data to be used as validation data.\n The model will set apart this fraction of the training data,\n will not train on it, and will evaluate\n the loss and any model metrics\n on this data at the end of each epoch.\n The validation data is selected from the last samples\n in the `x` and `y` data provided, before shuffling. This argument is\n not supported when `x` is a dataset, generator or\n `keras.utils.Sequence` instance.\n validation_data: Data on which to evaluate\n the loss and any model metrics at the end of each epoch.\n The model will not be trained on this data. Thus, note the fact\n that the validation loss of data provided using `validation_split`\n or `validation_data` is not affected by regularization layers like\n noise and dropuout.\n `validation_data` will override `validation_split`.\n `validation_data` could be:\n - tuple `(x_val, y_val)` of Numpy arrays or tensors\n - tuple `(x_val, y_val, val_sample_weights)` of Numpy arrays\n - dataset\n\n For the first two cases, `batch_size` must be provided.\n For the last case, `validation_steps` could be provided.\n Note that `validation_data` does not support all the data types that\n are supported in `x`, eg, dict, generator or `keras.utils.Sequence`.\n shuffle: Boolean (whether to shuffle the training data\n before each epoch) or str (for 'batch'). This argument is ignored\n when `x` is a generator. 'batch' is a special option for dealing\n with the limitations of HDF5 data; it shuffles in batch-sized\n chunks. Has no effect when `steps_per_epoch` is not `None`.\n class_weight: Optional dictionary mapping class indices (integers)\n to a weight (float) value, used for weighting the loss function\n (during training only).\n This can be useful to tell the model to\n \"pay more attention\" to samples from\n an under-represented class.\n sample_weight: Optional Numpy array of weights for\n the training samples, used for weighting the loss function\n (during training only). You can either pass a flat (1D)\n Numpy array with the same length as the input samples\n (1:1 mapping between weights and samples),\n or in the case of temporal data,\n you can pass a 2D array with shape\n `(samples, sequence_length)`,\n to apply a different weight to every timestep of every sample. This\n argument is not supported when `x` is a dataset, generator, or\n `keras.utils.Sequence` instance, instead provide the sample_weights\n as the third element of `x`.\n initial_epoch: Integer.\n Epoch at which to start training\n (useful for resuming a previous training run).\n steps_per_epoch: Integer or `None`.\n Total number of steps (batches of samples)\n before declaring one epoch finished and starting the\n next epoch. When training with input tensors such as\n TensorFlow data tensors, the default `None` is equal to\n the number of samples in your dataset divided by\n the batch size, or 1 if that cannot be determined. If x is a\n `tf.data` dataset, and 'steps_per_epoch'\n is None, the epoch will run until the input dataset is exhausted.\n When passing an infinitely repeating dataset, you must specify the\n `steps_per_epoch` argument. This argument is not supported with\n array inputs.\n validation_steps: Only relevant if `validation_data` is provided and\n is a `tf.data` dataset. Total number of steps (batches of\n samples) to draw before stopping when performing validation\n at the end of every epoch. If 'validation_steps' is None, validation\n will run until the `validation_data` dataset is exhausted. In the\n case of an infinitely repeated dataset, it will run into an\n infinite loop. If 'validation_steps' is specified and only part of\n the dataset will be consumed, the evaluation will start from the\n beginning of the dataset at each epoch. This ensures that the same\n validation samples are used every time.\n validation_batch_size: Integer or `None`.\n Number of samples per validation batch.\n If unspecified, will default to `batch_size`.\n Do not specify the `validation_batch_size` if your data is in the\n form of datasets, generators, or `keras.utils.Sequence` instances\n (since they generate batches).\n validation_freq: Only relevant if validation data is provided. Integer\n or `collections_abc.Container` instance (e.g. list, tuple, etc.).\n If an integer, specifies how many training epochs to run before a\n new validation run is performed, e.g. `validation_freq=2` runs\n validation every 2 epochs. If a Container, specifies the epochs on\n which to run validation, e.g. `validation_freq=[1, 2, 10]` runs\n validation at the end of the 1st, 2nd, and 10th epochs.\n max_queue_size: Integer. Used for generator or `keras.utils.Sequence`\n input only. Maximum size for the generator queue.\n If unspecified, `max_queue_size` will default to 10.\n workers: Integer. Used for generator or `keras.utils.Sequence` input\n only. Maximum number of processes to spin up\n when using process-based threading. If unspecified, `workers`\n will default to 1. If 0, will execute the generator on the main\n thread.\n use_multiprocessing: Boolean. Used for generator or\n `keras.utils.Sequence` input only. If `True`, use process-based\n threading. If unspecified, `use_multiprocessing` will default to\n `False`. Note that because this implementation relies on\n multiprocessing, you should not pass non-picklable arguments to\n the generator as they can't be passed easily to children processes.\n **kwargs: Used for backwards compatibility.\n\n Unpacking behavior for iterator-like inputs:\n A common pattern is to pass a tf.data.Dataset, generator, or\n tf.keras.utils.Sequence to the `x` argument of fit, which will in fact\n yield not only features (x) but optionally targets (y) and sample weights.\n Keras requires that the output of such iterator-likes be unambiguous. The\n iterator should return a tuple of length 1, 2, or 3, where the optional\n second and third elements will be used for y and sample_weight\n respectively. Any other type provided will be wrapped in a length one\n tuple, effectively treating everything as 'x'. When yielding dicts, they\n should still adhere to the top-level tuple structure.\n e.g. `({\"x0\": x0, \"x1\": x1}, y)`. Keras will not attempt to separate\n features, targets, and weights from the keys of a single dict.\n A notable unsupported data type is the namedtuple. The reason is that\n it behaves like both an ordered datatype (tuple) and a mapping\n datatype (dict). So given a namedtuple of the form:\n `namedtuple(\"example_tuple\", [\"y\", \"x\"])`\n it is ambiguous whether to reverse the order of the elements when\n interpreting the value. Even worse is a tuple of the form:\n `namedtuple(\"other_tuple\", [\"x\", \"y\", \"z\"])`\n where it is unclear if the tuple was intended to be unpacked into x, y,\n and sample_weight or passed through as a single element to `x`. As a\n result the data processing code will simply raise a ValueError if it\n encounters a namedtuple. (Along with instructions to remedy the issue.)\n\n Returns:\n A `History` object. Its `History.history` attribute is\n a record of training loss values and metrics values\n at successive epochs, as well as validation loss values\n and validation metrics values (if applicable).\n\n Raises:\n RuntimeError: If the model was never compiled.\n ValueError: In case of mismatch between the provided input data\n and what the model expects.\n \"\"\"\n _keras_api_gauge.get_cell('fit').set(True)\n # Legacy graph support is contained in `training_v1.Model`.\n version_utils.disallow_legacy_graph('Model', 'fit')\n self._assert_compile_was_called()\n self._check_call_args('fit')\n _disallow_inside_tf_function('fit')\n\n if validation_split:\n # Create the validation data using the training data. Only supported for\n # `Tensor` and `NumPy` input.\n (x, y, sample_weight), validation_data = (\n data_adapter.train_validation_split((x, y, sample_weight),\n validation_split=validation_split,\n shuffle=False))\n\n with self.distribute_strategy.scope(), \\\n training_utils.RespectCompiledTrainableState(self):\n # Creates a `tf.data.Dataset` and handles batch and epoch iteration.\n data_handler = data_adapter.DataHandler(\n x=x,\n y=y,\n sample_weight=sample_weight,\n batch_size=batch_size,\n steps_per_epoch=steps_per_epoch,\n initial_epoch=initial_epoch,\n epochs=epochs,\n shuffle=shuffle,\n class_weight=class_weight,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing,\n model=self,\n steps_per_execution=self._steps_per_execution)\n\n # Container that configures and calls `tf.keras.Callback`s.\n if not isinstance(callbacks, callbacks_module.CallbackList):\n callbacks = callbacks_module.CallbackList(\n callbacks,\n add_history=True,\n add_progbar=verbose != 0,\n model=self,\n verbose=verbose,\n epochs=epochs,\n steps=data_handler.inferred_steps)\n\n self.stop_training = False\n train_function = self.make_train_function()\n self._train_counter.assign(0)\n callbacks.on_train_begin()\n training_logs = None\n # Handle fault-tolerance for multi-worker.\n # TODO(omalleyt): Fix the ordering issues that mean this has to\n # happen after `callbacks.on_train_begin`.\n data_handler._initial_epoch = ( # pylint: disable=protected-access\n self._maybe_load_initial_epoch_from_ckpt(initial_epoch))\n for epoch, iterator in data_handler.enumerate_epochs():\n self.reset_metrics()\n callbacks.on_epoch_begin(epoch)\n with data_handler.catch_stop_iteration():\n for step in data_handler.steps():\n with trace.Trace(\n 'TraceContext',\n graph_type='train',\n epoch_num=epoch,\n step_num=step,\n batch_size=batch_size):\n callbacks.on_train_batch_begin(step)\n tmp_logs = train_function(iterator)\n if data_handler.should_sync:\n context.async_wait()\n logs = tmp_logs # No error, now safe to assign to logs.\n end_step = step + data_handler.step_increment\n callbacks.on_train_batch_end(end_step, logs)\n epoch_logs = copy.copy(logs)\n\n # Run validation.\n if validation_data and self._should_eval(epoch, validation_freq):\n val_x, val_y, val_sample_weight = (\n data_adapter.unpack_x_y_sample_weight(validation_data))\n val_logs = self.evaluate(\n x=val_x,\n y=val_y,\n sample_weight=val_sample_weight,\n batch_size=validation_batch_size or batch_size,\n steps=validation_steps,\n callbacks=callbacks,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing,\n return_dict=True)\n val_logs = {'val_' + name: val for name, val in val_logs.items()}\n epoch_logs.update(val_logs)\n\n callbacks.on_epoch_end(epoch, epoch_logs)\n training_logs = epoch_logs\n if self.stop_training:\n break\n\n callbacks.on_train_end(logs=training_logs)\n return self.history\n\n def test_step(self, data):\n \"\"\"The logic for one evaluation step.\n\n This method can be overridden to support custom evaluation logic.\n This method is called by `Model.make_test_function`.\n\n This function should contain the mathemetical logic for one step of\n evaluation.\n This typically includes the forward pass, loss calculation, and metrics\n updates.\n\n Configuration details for *how* this logic is run (e.g. `tf.function` and\n `tf.distribute.Strategy` settings), should be left to\n `Model.make_test_function`, which can also be overridden.\n\n Arguments:\n data: A nested structure of `Tensor`s.\n\n Returns:\n A `dict` containing values that will be passed to\n `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the\n values of the `Model`'s metrics are returned.\n \"\"\"\n data = data_adapter.expand_1d(data)\n x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)\n\n y_pred = self(x, training=False)\n # Updates stateful loss metrics.\n self.compiled_loss(\n y, y_pred, sample_weight, regularization_losses=self.losses)\n\n self.compiled_metrics.update_state(y, y_pred, sample_weight)\n return {m.name: m.result() for m in self.metrics}\n\n def make_test_function(self):\n \"\"\"Creates a function that executes one step of evaluation.\n\n This method can be overridden to support custom evaluation logic.\n This method is called by `Model.evaluate` and `Model.test_on_batch`.\n\n Typically, this method directly controls `tf.function` and\n `tf.distribute.Strategy` settings, and delegates the actual evaluation\n logic to `Model.test_step`.\n\n This function is cached the first time `Model.evaluate` or\n `Model.test_on_batch` is called. The cache is cleared whenever\n `Model.compile` is called.\n\n Returns:\n Function. The function created by this method should accept a\n `tf.data.Iterator`, and return a `dict` containing values that will\n be passed to `tf.keras.Callbacks.on_test_batch_end`.\n \"\"\"\n if self.test_function is not None:\n return self.test_function\n\n def step_function(model, iterator):\n \"\"\"Runs a single evaluation step.\"\"\"\n\n def run_step(data):\n outputs = model.test_step(data)\n # Ensure counter is updated only if `test_step` succeeds.\n with ops.control_dependencies(_minimum_control_deps(outputs)):\n model._test_counter.assign_add(1) # pylint: disable=protected-access\n return outputs\n\n data = next(iterator)\n outputs = model.distribute_strategy.run(run_step, args=(data,))\n outputs = reduce_per_replica(\n outputs, self.distribute_strategy, reduction='first')\n return outputs\n\n if self._steps_per_execution.numpy().item() == 1:\n\n def test_function(iterator):\n \"\"\"Runs an evaluation execution with one step.\"\"\"\n return step_function(self, iterator)\n\n else:\n\n def test_function(iterator):\n \"\"\"Runs an evaluation execution with multiple steps.\"\"\"\n outputs = step_function(self, iterator)\n for _ in math_ops.range(self._steps_per_execution - 1):\n outputs = step_function(self, iterator)\n return outputs\n\n if not self.run_eagerly:\n test_function = def_function.function(\n test_function, experimental_relax_shapes=True)\n\n self.test_function = test_function\n return self.test_function\n\n @enable_multi_worker\n def evaluate(self,\n x=None,\n y=None,\n batch_size=None,\n verbose=1,\n sample_weight=None,\n steps=None,\n callbacks=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n return_dict=False):\n \"\"\"Returns the loss value & metrics values for the model in test mode.\n\n Computation is done in batches (see the `batch_size` arg.)\n\n Arguments:\n x: Input data. It could be: - A Numpy array (or array-like), or a list\n of arrays (in case the model has multiple inputs). - A TensorFlow\n tensor, or a list of tensors (in case the model has multiple inputs).\n - A dict mapping input names to the corresponding array/tensors, if\n the model has named inputs. - A `tf.data` dataset. - A generator or\n `keras.utils.Sequence` instance. A more detailed description of\n unpacking behavior for iterator types (Dataset, generator, Sequence)\n is given in the `Unpacking behavior for iterator-like inputs` section\n of `Model.fit`.\n y: Target data. Like the input data `x`, it could be either Numpy\n array(s) or TensorFlow tensor(s). It should be consistent with `x`\n (you cannot have Numpy inputs and tensor targets, or inversely). If\n `x` is a dataset, generator or `keras.utils.Sequence` instance, `y`\n should not be specified (since targets will be obtained from the\n iterator/dataset).\n batch_size: Integer or `None`. Number of samples per batch of\n computation. If unspecified, `batch_size` will default to 32. Do not\n specify the `batch_size` if your data is in the form of a dataset,\n generators, or `keras.utils.Sequence` instances (since they generate\n batches).\n verbose: 0 or 1. Verbosity mode. 0 = silent, 1 = progress bar.\n sample_weight: Optional Numpy array of weights for the test samples,\n used for weighting the loss function. You can either pass a flat (1D)\n Numpy array with the same length as the input samples\n (1:1 mapping between weights and samples), or in the case of\n temporal data, you can pass a 2D array with shape `(samples,\n sequence_length)`, to apply a different weight to every timestep\n of every sample. This argument is not supported when `x` is a\n dataset, instead pass sample weights as the third element of `x`.\n steps: Integer or `None`. Total number of steps (batches of samples)\n before declaring the evaluation round finished. Ignored with the\n default value of `None`. If x is a `tf.data` dataset and `steps` is\n None, 'evaluate' will run until the dataset is exhausted. This\n argument is not supported with array inputs.\n callbacks: List of `keras.callbacks.Callback` instances. List of\n callbacks to apply during evaluation. See\n [callbacks](/api_docs/python/tf/keras/callbacks).\n max_queue_size: Integer. Used for generator or `keras.utils.Sequence`\n input only. Maximum size for the generator queue. If unspecified,\n `max_queue_size` will default to 10.\n workers: Integer. Used for generator or `keras.utils.Sequence` input\n only. Maximum number of processes to spin up when using process-based\n threading. If unspecified, `workers` will default to 1. If 0, will\n execute the generator on the main thread.\n use_multiprocessing: Boolean. Used for generator or\n `keras.utils.Sequence` input only. If `True`, use process-based\n threading. If unspecified, `use_multiprocessing` will default to\n `False`. Note that because this implementation relies on\n multiprocessing, you should not pass non-picklable arguments to the\n generator as they can't be passed easily to children processes.\n return_dict: If `True`, loss and metric results are returned as a dict,\n with each key being the name of the metric. If `False`, they are\n returned as a list.\n\n See the discussion of `Unpacking behavior for iterator-like inputs` for\n `Model.fit`.\n\n Returns:\n Scalar test loss (if the model has a single output and no metrics)\n or list of scalars (if the model has multiple outputs\n and/or metrics). The attribute `model.metrics_names` will give you\n the display labels for the scalar outputs.\n\n Raises:\n ValueError: in case of invalid arguments.\n \"\"\"\n _keras_api_gauge.get_cell('evaluate').set(True)\n version_utils.disallow_legacy_graph('Model', 'evaluate')\n self._assert_compile_was_called()\n self._check_call_args('evaluate')\n _disallow_inside_tf_function('evaluate')\n\n with self.distribute_strategy.scope():\n # Creates a `tf.data.Dataset` and handles batch and epoch iteration.\n data_handler = data_adapter.DataHandler(\n x=x,\n y=y,\n sample_weight=sample_weight,\n batch_size=batch_size,\n steps_per_epoch=steps,\n initial_epoch=0,\n epochs=1,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing,\n model=self,\n steps_per_execution=self._steps_per_execution)\n\n # Container that configures and calls `tf.keras.Callback`s.\n if not isinstance(callbacks, callbacks_module.CallbackList):\n callbacks = callbacks_module.CallbackList(\n callbacks,\n add_history=True,\n add_progbar=verbose != 0,\n model=self,\n verbose=verbose,\n epochs=1,\n steps=data_handler.inferred_steps)\n\n test_function = self.make_test_function()\n self._test_counter.assign(0)\n callbacks.on_test_begin()\n for _, iterator in data_handler.enumerate_epochs(): # Single epoch.\n self.reset_metrics()\n with data_handler.catch_stop_iteration():\n for step in data_handler.steps():\n with trace.Trace('TraceContext', graph_type='test', step_num=step):\n callbacks.on_test_batch_begin(step)\n tmp_logs = test_function(iterator)\n if data_handler.should_sync:\n context.async_wait()\n logs = tmp_logs # No error, now safe to assign to logs.\n end_step = step + data_handler.step_increment\n callbacks.on_test_batch_end(end_step, logs)\n logs = tf_utils.to_numpy_or_python_type(logs)\n callbacks.on_test_end(logs=logs)\n\n if return_dict:\n return logs\n else:\n results = [logs.get(name, None) for name in self.metrics_names]\n if len(results) == 1:\n return results[0]\n return results\n\n def predict_step(self, data):\n \"\"\"The logic for one inference step.\n\n This method can be overridden to support custom inference logic.\n This method is called by `Model.make_predict_function`.\n\n This method should contain the mathemetical logic for one step of inference.\n This typically includes the forward pass.\n\n Configuration details for *how* this logic is run (e.g. `tf.function` and\n `tf.distribute.Strategy` settings), should be left to\n `Model.make_predict_function`, which can also be overridden.\n\n Arguments:\n data: A nested structure of `Tensor`s.\n\n Returns:\n The result of one inference step, typically the output of calling the\n `Model` on data.\n \"\"\"\n data = data_adapter.expand_1d(data)\n x, _, _ = data_adapter.unpack_x_y_sample_weight(data)\n return self(x, training=False)\n\n def make_predict_function(self):\n \"\"\"Creates a function that executes one step of inference.\n\n This method can be overridden to support custom inference logic.\n This method is called by `Model.predict` and `Model.predict_on_batch`.\n\n Typically, this method directly controls `tf.function` and\n `tf.distribute.Strategy` settings, and delegates the actual evaluation\n logic to `Model.predict_step`.\n\n This function is cached the first time `Model.predict` or\n `Model.predict_on_batch` is called. The cache is cleared whenever\n `Model.compile` is called.\n\n Returns:\n Function. The function created by this method should accept a\n `tf.data.Iterator`, and return the outputs of the `Model`.\n \"\"\"\n if self.predict_function is not None:\n return self.predict_function\n\n def step_function(model, iterator):\n \"\"\"Runs a single evaluation step.\"\"\"\n\n def run_step(data):\n outputs = model.predict_step(data)\n # Ensure counter is updated only if `test_step` succeeds.\n with ops.control_dependencies(_minimum_control_deps(outputs)):\n model._predict_counter.assign_add(1) # pylint: disable=protected-access\n return outputs\n\n data = next(iterator)\n outputs = model.distribute_strategy.run(run_step, args=(data,))\n outputs = reduce_per_replica(\n outputs, self.distribute_strategy, reduction='concat')\n return outputs\n\n if (self._steps_per_execution is None or\n self._steps_per_execution.numpy().item() == 1):\n\n def predict_function(iterator):\n \"\"\"Runs an evaluation execution with one step.\"\"\"\n return step_function(self, iterator)\n\n else:\n\n def predict_function(iterator):\n \"\"\"Runs an evaluation execution with multiple steps.\"\"\"\n outputs = step_function(self, iterator)\n for _ in math_ops.range(self._steps_per_execution - 1):\n directives.set_loop_options(\n shape_invariants=[(\n t, tf_utils.get_tensor_spec(t, dynamic_batch=True).shape)\n for t in nest.flatten(outputs)])\n step_outputs = step_function(self, iterator)\n outputs = nest.map_structure(lambda t1, t2: concat([t1, t2]), outputs,\n step_outputs)\n return outputs\n\n if not self.run_eagerly:\n predict_function = def_function.function(\n predict_function, experimental_relax_shapes=True)\n\n self.predict_function = predict_function\n return self.predict_function\n\n @disable_multi_worker\n def predict(self,\n x,\n batch_size=None,\n verbose=0,\n steps=None,\n callbacks=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False):\n \"\"\"Generates output predictions for the input samples.\n\n Computation is done in batches. This method is designed for performance in\n large scale inputs. For small amount of inputs that fit in one batch,\n directly using `__call__` is recommended for faster execution, e.g.,\n `model(x)`, or `model(x, training=False)` if you have layers such as\n `tf.keras.layers.BatchNormalization` that behaves differently during\n inference. Also, note the fact that test loss is not affected by\n regularization layers like noise and dropout.\n\n Arguments:\n x: Input samples. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A `tf.data` dataset.\n - A generator or `keras.utils.Sequence` instance.\n A more detailed description of unpacking behavior for iterator types\n (Dataset, generator, Sequence) is given in the `Unpacking behavior\n for iterator-like inputs` section of `Model.fit`.\n batch_size: Integer or `None`.\n Number of samples per batch.\n If unspecified, `batch_size` will default to 32.\n Do not specify the `batch_size` if your data is in the\n form of dataset, generators, or `keras.utils.Sequence` instances\n (since they generate batches).\n verbose: Verbosity mode, 0 or 1.\n steps: Total number of steps (batches of samples)\n before declaring the prediction round finished.\n Ignored with the default value of `None`. If x is a `tf.data`\n dataset and `steps` is None, `predict` will\n run until the input dataset is exhausted.\n callbacks: List of `keras.callbacks.Callback` instances.\n List of callbacks to apply during prediction.\n See [callbacks](/api_docs/python/tf/keras/callbacks).\n max_queue_size: Integer. Used for generator or `keras.utils.Sequence`\n input only. Maximum size for the generator queue.\n If unspecified, `max_queue_size` will default to 10.\n workers: Integer. Used for generator or `keras.utils.Sequence` input\n only. Maximum number of processes to spin up when using\n process-based threading. If unspecified, `workers` will default\n to 1. If 0, will execute the generator on the main thread.\n use_multiprocessing: Boolean. Used for generator or\n `keras.utils.Sequence` input only. If `True`, use process-based\n threading. If unspecified, `use_multiprocessing` will default to\n `False`. Note that because this implementation relies on\n multiprocessing, you should not pass non-picklable arguments to\n the generator as they can't be passed easily to children processes.\n\n See the discussion of `Unpacking behavior for iterator-like inputs` for\n `Model.fit`. Note that Model.predict uses the same interpretation rules as\n `Model.fit` and `Model.evaluate`, so inputs must be unambiguous for all\n three methods.\n\n Returns:\n Numpy array(s) of predictions.\n\n Raises:\n ValueError: In case of mismatch between the provided\n input data and the model's expectations,\n or in case a stateful model receives a number of samples\n that is not a multiple of the batch size.\n \"\"\"\n _keras_api_gauge.get_cell('predict').set(True)\n version_utils.disallow_legacy_graph('Model', 'predict')\n self._check_call_args('predict')\n _disallow_inside_tf_function('predict')\n\n outputs = None\n with self.distribute_strategy.scope():\n # Creates a `tf.data.Dataset` and handles batch and epoch iteration.\n data_handler = data_adapter.DataHandler(\n x=x,\n batch_size=batch_size,\n steps_per_epoch=steps,\n initial_epoch=0,\n epochs=1,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing,\n model=self,\n steps_per_execution=self._steps_per_execution)\n\n # Container that configures and calls `tf.keras.Callback`s.\n if not isinstance(callbacks, callbacks_module.CallbackList):\n callbacks = callbacks_module.CallbackList(\n callbacks,\n add_history=True,\n add_progbar=verbose != 0,\n model=self,\n verbose=verbose,\n epochs=1,\n steps=data_handler.inferred_steps)\n\n predict_function = self.make_predict_function()\n self._predict_counter.assign(0)\n callbacks.on_predict_begin()\n for _, iterator in data_handler.enumerate_epochs(): # Single epoch.\n with data_handler.catch_stop_iteration():\n for step in data_handler.steps():\n callbacks.on_predict_batch_begin(step)\n tmp_batch_outputs = predict_function(iterator)\n if data_handler.should_sync:\n context.async_wait()\n batch_outputs = tmp_batch_outputs # No error, now safe to assign.\n if outputs is None:\n outputs = nest.map_structure(lambda batch_output: [batch_output],\n batch_outputs)\n else:\n nest.map_structure_up_to(\n batch_outputs,\n lambda output, batch_output: output.append(batch_output),\n outputs, batch_outputs)\n end_step = step + data_handler.step_increment\n callbacks.on_predict_batch_end(end_step, {'outputs': batch_outputs})\n callbacks.on_predict_end()\n all_outputs = nest.map_structure_up_to(batch_outputs, concat, outputs)\n return tf_utils.to_numpy_or_python_type(all_outputs)\n\n def reset_metrics(self):\n \"\"\"Resets the state of all the metrics in the model.\n\n Examples:\n\n >>> inputs = tf.keras.layers.Input(shape=(3,))\n >>> outputs = tf.keras.layers.Dense(2)(inputs)\n >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)\n >>> model.compile(optimizer=\"Adam\", loss=\"mse\", metrics=[\"mae\"])\n\n >>> x = np.random.random((2, 3))\n >>> y = np.random.randint(0, 2, (2, 2))\n >>> _ = model.fit(x, y, verbose=0)\n >>> assert all(float(m.result()) for m in model.metrics)\n\n >>> model.reset_metrics()\n >>> assert all(float(m.result()) == 0 for m in model.metrics)\n\n \"\"\"\n for m in self.metrics:\n m.reset_states()\n\n def train_on_batch(self,\n x,\n y=None,\n sample_weight=None,\n class_weight=None,\n reset_metrics=True,\n return_dict=False):\n \"\"\"Runs a single gradient update on a single batch of data.\n\n Arguments:\n x: Input data. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A dict mapping input names to the corresponding array/tensors,\n if the model has named inputs.\n y: Target data. Like the input data `x`, it could be either Numpy\n array(s) or TensorFlow tensor(s). It should be consistent with `x`\n (you cannot have Numpy inputs and tensor targets, or inversely).\n sample_weight: Optional array of the same length as x, containing\n weights to apply to the model's loss for each sample. In the case of\n temporal data, you can pass a 2D array with shape (samples,\n sequence_length), to apply a different weight to every timestep of\n every sample.\n class_weight: Optional dictionary mapping class indices (integers) to a\n weight (float) to apply to the model's loss for the samples from this\n class during training. This can be useful to tell the model to \"pay\n more attention\" to samples from an under-represented class.\n reset_metrics: If `True`, the metrics returned will be only for this\n batch. If `False`, the metrics will be statefully accumulated across\n batches.\n return_dict: If `True`, loss and metric results are returned as a dict,\n with each key being the name of the metric. If `False`, they are\n returned as a list.\n\n Returns:\n Scalar training loss\n (if the model has a single output and no metrics)\n or list of scalars (if the model has multiple outputs\n and/or metrics). The attribute `model.metrics_names` will give you\n the display labels for the scalar outputs.\n\n Raises:\n ValueError: In case of invalid user-provided arguments.\n \"\"\"\n self._assert_compile_was_called()\n self._check_call_args('train_on_batch')\n _disallow_inside_tf_function('train_on_batch')\n with self.distribute_strategy.scope(), \\\n training_utils.RespectCompiledTrainableState(self):\n iterator = data_adapter.single_batch_iterator(self.distribute_strategy, x,\n y, sample_weight,\n class_weight)\n train_function = self.make_train_function()\n logs = train_function(iterator)\n\n if reset_metrics:\n self.reset_metrics()\n logs = tf_utils.to_numpy_or_python_type(logs)\n if return_dict:\n return logs\n else:\n results = [logs.get(name, None) for name in self.metrics_names]\n if len(results) == 1:\n return results[0]\n return results\n\n def test_on_batch(self,\n x,\n y=None,\n sample_weight=None,\n reset_metrics=True,\n return_dict=False):\n \"\"\"Test the model on a single batch of samples.\n\n Arguments:\n x: Input data. It could be: - A Numpy array (or array-like), or a list\n of arrays (in case the model has multiple inputs). - A TensorFlow\n tensor, or a list of tensors (in case the model has multiple inputs).\n - A dict mapping input names to the corresponding array/tensors, if\n the model has named inputs.\n y: Target data. Like the input data `x`, it could be either Numpy\n array(s) or TensorFlow tensor(s). It should be consistent with `x`\n (you cannot have Numpy inputs and tensor targets, or inversely).\n sample_weight: Optional array of the same length as x, containing\n weights to apply to the model's loss for each sample. In the case of\n temporal data, you can pass a 2D array with shape (samples,\n sequence_length), to apply a different weight to every timestep of\n every sample.\n reset_metrics: If `True`, the metrics returned will be only for this\n batch. If `False`, the metrics will be statefully accumulated across\n batches.\n return_dict: If `True`, loss and metric results are returned as a dict,\n with each key being the name of the metric. If `False`, they are\n returned as a list.\n\n Returns:\n Scalar test loss (if the model has a single output and no metrics)\n or list of scalars (if the model has multiple outputs\n and/or metrics). The attribute `model.metrics_names` will give you\n the display labels for the scalar outputs.\n\n Raises:\n ValueError: In case of invalid user-provided arguments.\n \"\"\"\n self._assert_compile_was_called()\n self._check_call_args('test_on_batch')\n _disallow_inside_tf_function('test_on_batch')\n with self.distribute_strategy.scope():\n iterator = data_adapter.single_batch_iterator(self.distribute_strategy, x,\n y, sample_weight)\n test_function = self.make_test_function()\n logs = test_function(iterator)\n\n if reset_metrics:\n self.reset_metrics()\n logs = tf_utils.to_numpy_or_python_type(logs)\n if return_dict:\n return logs\n else:\n results = [logs.get(name, None) for name in self.metrics_names]\n if len(results) == 1:\n return results[0]\n return results\n\n def predict_on_batch(self, x):\n \"\"\"Returns predictions for a single batch of samples.\n\n Arguments:\n x: Input data. It could be: - A Numpy array (or array-like), or a list\n of arrays (in case the model has multiple inputs). - A TensorFlow\n tensor, or a list of tensors (in case the model has multiple inputs).\n\n Returns:\n Numpy array(s) of predictions.\n\n Raises:\n ValueError: In case of mismatch between given number of inputs and\n expectations of the model.\n \"\"\"\n self._check_call_args('predict_on_batch')\n _disallow_inside_tf_function('predict_on_batch')\n with self.distribute_strategy.scope():\n iterator = data_adapter.single_batch_iterator(self.distribute_strategy, x)\n predict_function = self.make_predict_function()\n outputs = predict_function(iterator)\n return tf_utils.to_numpy_or_python_type(outputs)\n\n @deprecation.deprecated(\n None, 'Please use Model.fit, which supports generators.')\n def fit_generator(self,\n generator,\n steps_per_epoch=None,\n epochs=1,\n verbose=1,\n callbacks=None,\n validation_data=None,\n validation_steps=None,\n validation_freq=1,\n class_weight=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n shuffle=True,\n initial_epoch=0):\n \"\"\"Fits the model on data yielded batch-by-batch by a Python generator.\n\n DEPRECATED:\n `Model.fit` now supports generators, so there is no longer any need to use\n this endpoint.\n \"\"\"\n _keras_api_gauge.get_cell('fit_generator').set(True)\n return self.fit(\n generator,\n steps_per_epoch=steps_per_epoch,\n epochs=epochs,\n verbose=verbose,\n callbacks=callbacks,\n validation_data=validation_data,\n validation_steps=validation_steps,\n validation_freq=validation_freq,\n class_weight=class_weight,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing,\n shuffle=shuffle,\n initial_epoch=initial_epoch)\n\n @deprecation.deprecated(\n None, 'Please use Model.evaluate, which supports generators.')\n def evaluate_generator(self,\n generator,\n steps=None,\n callbacks=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n verbose=0):\n \"\"\"Evaluates the model on a data generator.\n\n DEPRECATED:\n `Model.evaluate` now supports generators, so there is no longer any need\n to use this endpoint.\n \"\"\"\n _keras_api_gauge.get_cell('evaluate_generator').set(True)\n self._check_call_args('evaluate_generator')\n\n return self.evaluate(\n generator,\n steps=steps,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing,\n verbose=verbose,\n callbacks=callbacks)\n\n @deprecation.deprecated(\n None, 'Please use Model.predict, which supports generators.')\n def predict_generator(self,\n generator,\n steps=None,\n callbacks=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n verbose=0):\n \"\"\"Generates predictions for the input samples from a data generator.\n\n DEPRECATED:\n `Model.predict` now supports generators, so there is no longer any need\n to use this endpoint.\n \"\"\"\n _keras_api_gauge.get_cell('predict_generator').set(True)\n return self.predict(\n generator,\n steps=steps,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing,\n verbose=verbose,\n callbacks=callbacks)\n\n def _check_call_args(self, method_name):\n \"\"\"Check that `call` has only one positional arg.\"\"\"\n # Always allow first arg, regardless of arg name.\n fullargspec = self._call_full_argspec\n if fullargspec.defaults:\n positional_args = fullargspec.args[:-len(fullargspec.defaults)]\n else:\n positional_args = fullargspec.args\n if 'training' in positional_args:\n positional_args.remove('training')\n\n # self and first arg can be positional.\n if len(positional_args) > 2:\n extra_args = positional_args[2:]\n raise ValueError(\n 'Models passed to `' + method_name + '` can only have `training` '\n 'and the first argument in `call` as positional arguments, '\n 'found: ' + str(extra_args) + '.')\n\n def _validate_compile(self, optimizer, metrics, **kwargs):\n \"\"\"Performs validation checks for the default `compile`.\"\"\"\n if any(\n isinstance(opt, optimizers.Optimizer)\n for opt in nest.flatten(optimizer)):\n raise ValueError(\n '`tf.compat.v1.keras` Optimizer (', optimizer, ') is '\n 'not supported when eager execution is enabled. Use a '\n '`tf.keras` Optimizer instead, or disable eager '\n 'execution.')\n\n kwargs.pop('cloning', None) # Legacy DistStrat argument, never used.\n kwargs.pop('experimental_run_tf_function', None) # Always `True`.\n if kwargs.pop('distribute', None) is not None:\n raise ValueError(\n 'Distribute argument in compile is not available in TF 2.0 please '\n 'create the model under the distribution strategy scope.')\n if kwargs.pop('target_tensors', None) is not None:\n raise ValueError(\n 'target_tensors argument is not supported when executing eagerly.')\n invalid_kwargs = set(kwargs) - {\n 'experimental_steps_per_execution', 'sample_weight_mode'\n }\n if invalid_kwargs:\n raise TypeError('Invalid keyword argument(s) in `compile`: %s' %\n (invalid_kwargs,))\n\n # Model must be created and compiled with the same DistStrat.\n if self.built and ds_context.has_strategy():\n strategy = ds_context.get_strategy()\n for v in self.variables:\n if not strategy.extended.variable_created_in_scope(v):\n raise ValueError(\n 'Variable (%s) was not created in the distribution strategy '\n 'scope of (%s). It is most likely due to not all layers or '\n 'the model or optimizer being created outside the distribution '\n 'strategy scope. Try to make sure your code looks similar '\n 'to the following.\\n'\n 'with strategy.scope():\\n'\n ' model=_create_model()\\n'\n ' model.compile(...)' % (v, strategy))\n\n # Model metrics must be created in the same distribution strategy scope\n # as the model.\n strategy = self._get_distribution_strategy()\n for metric in nest.flatten(metrics):\n for v in getattr(metric, 'variables', []):\n if not strategy.extended.variable_created_in_scope(v):\n raise ValueError(\n 'Metric (%s) passed to model.compile was created inside of a '\n 'different distribution strategy scope than the model. All '\n 'metrics must be created in the same distribution strategy '\n 'scope as the model (in this case %s). If you pass in a string '\n 'identifier for a metric to compile the metric will '\n 'automatically be created in the correct distribution '\n 'strategy scope.' % (metric, strategy)\n )\n\n def _maybe_load_initial_epoch_from_ckpt(self, initial_epoch):\n \"\"\"Maybe load initial epoch from ckpt considering possible worker recovery.\n\n Refer to tensorflow/python/keras/distribute/multi_worker_training_state.py\n for more information.\n\n Arguments:\n initial_epoch: The original initial_epoch user passes in in `fit()`.\n\n Returns:\n If the training is recovering from previous failure under multi-worker\n training setting, return the epoch the training is supposed to continue\n at. Otherwise, return the `initial_epoch` the user passes in.\n \"\"\"\n if self._training_state is not None:\n return self._training_state.maybe_load_initial_epoch_from_ckpt(\n initial_epoch, mode=ModeKeys.TRAIN)\n return initial_epoch\n\n def _assert_compile_was_called(self):\n # Checks whether `compile` has been called. If it has been called,\n # then the optimizer is set. This is different from whether the\n # model is compiled\n # (i.e. whether the model is built and its inputs/outputs are set).\n if not self._is_compiled:\n raise RuntimeError('You must compile your model before '\n 'training/testing. '\n 'Use `model.compile(optimizer, loss)`.')\n\n def _set_inputs(self, inputs, outputs=None, training=None):\n \"\"\"This method is for compat with Modelv1. Only inputs are needed here.\"\"\"\n self._set_save_spec(inputs)\n\n @property\n def _trackable_saved_model_saver(self):\n return model_serialization.ModelSavedModelSaver(self)\n\n def _list_functions_for_serialization(self, serialization_cache):\n # SavedModel needs to ignore the execution functions.\n train_function = self.train_function\n test_function = self.test_function\n predict_function = self.predict_function\n self.train_function = None\n self.test_function = None\n self.predict_function = None\n functions = super(\n Model, self)._list_functions_for_serialization(serialization_cache)\n self.train_function = train_function\n self.test_function = test_function\n self.predict_function = predict_function\n return functions\n\n def _should_eval(self, epoch, validation_freq):\n epoch = epoch + 1 # one-index the user-facing epoch.\n if isinstance(validation_freq, int):\n return epoch % validation_freq == 0\n elif isinstance(validation_freq, list):\n return epoch in validation_freq\n else:\n raise ValueError('Expected `validation_freq` to be a list or int.')\n\n ######################################################################\n # Functions below exist only as v1 / v2 compatibility shims.\n ######################################################################\n\n def _get_compile_args(self):\n \"\"\"Used for saving or cloning a Model.\"\"\"\n self._assert_compile_was_called()\n # pylint: disable=protected-access\n compile_args = {\n 'optimizer': self.optimizer,\n 'loss': self.compiled_loss._user_losses,\n 'metrics': self.compiled_metrics._user_metrics,\n 'weighted_metrics': self.compiled_metrics._user_weighted_metrics,\n 'loss_weights': self.compiled_loss._user_loss_weights,\n }\n # pylint: enable=protected-access\n return compile_args\n\n def _get_callback_model(self):\n return self\n\n def _in_multi_worker_mode(self):\n return self.distribute_strategy.extended._in_multi_worker_mode() # pylint: disable=protected-access\n\n def _get_distribution_strategy(self):\n return self.distribute_strategy\n\n @property\n def _compile_was_called(self):\n return self._is_compiled\n\n\ndef reduce_per_replica(values, strategy, reduction='first'):\n \"\"\"Reduce PerReplica objects.\n\n Arguments:\n values: Structure of `PerReplica` objects or `Tensor`s. `Tensor`s are\n returned as-is.\n strategy: `tf.distribute.Strategy` object.\n reduction: One of 'first', 'concat'.\n\n Returns:\n Structure of `Tensor`s.\n \"\"\"\n\n def _reduce(v):\n \"\"\"Reduce a single `PerReplica` object.\"\"\"\n if not isinstance(v, ds_values.PerReplica):\n return v\n elif reduction == 'first':\n return strategy.unwrap(v)[0]\n elif reduction == 'concat':\n if _is_tpu_multi_host(strategy):\n return _tpu_multi_host_concat(v, strategy)\n else:\n return concat(strategy.unwrap(v))\n else:\n raise ValueError('`reduction` must be \"first\" or \"concat\".')\n\n return nest.map_structure(_reduce, values)\n\n\ndef concat(tensors, axis=0):\n \"\"\"Concats `tensor`s along `axis`.\"\"\"\n if isinstance(tensors[0], sparse_tensor.SparseTensor):\n return sparse_ops.sparse_concat_v2(axis=axis, sp_inputs=tensors)\n if isinstance(tensors[0], ragged_tensor.RaggedTensor):\n return ragged_concat_ops.concat(tensors, axis=axis)\n return array_ops.concat(tensors, axis=axis)\n\n\ndef _is_tpu_multi_host(strategy):\n return (dist_utils.is_tpu_strategy(strategy) and\n strategy.extended.num_hosts > 1)\n\n\ndef _tpu_multi_host_concat(v, strategy):\n \"\"\"Correctly order TPU PerReplica objects.\"\"\"\n replicas = strategy.unwrap(v)\n # When distributed datasets are created from Tensors / NumPy,\n # TPUStrategy.experimental_distribute_dataset shards data in\n # (Replica, Host) order, and TPUStrategy.unwrap returns it in\n # (Host, Replica) order.\n # TODO(b/150317897): Figure out long-term plan here.\n num_replicas_per_host = strategy.extended.num_replicas_per_host\n ordered_replicas = []\n for replica_id in range(num_replicas_per_host):\n ordered_replicas += replicas[replica_id::num_replicas_per_host]\n return concat(ordered_replicas)\n\n\ndef _minimize(strategy, tape, optimizer, loss, trainable_variables):\n \"\"\"Minimizes loss for one step by updating `trainable_variables`.\n\n This is roughly equivalent to\n\n ```python\n gradients = tape.gradient(loss, trainable_variables)\n self.optimizer.apply_gradients(zip(gradients, trainable_variables))\n ```\n\n However, this function also applies gradient clipping and loss scaling if the\n optimizer is a LossScaleOptimizer.\n\n Args:\n strategy: `tf.distribute.Strategy`.\n tape: A gradient tape. The loss must have been computed under this tape.\n optimizer: The optimizer used to minimize the loss.\n loss: The loss tensor.\n trainable_variables: The variables that will be updated in order to minimize\n the loss.\n \"\"\"\n\n with tape:\n if isinstance(optimizer, lso.LossScaleOptimizer):\n loss = optimizer.get_scaled_loss(loss)\n\n gradients = tape.gradient(loss, trainable_variables)\n\n # Whether to aggregate gradients outside of optimizer. This requires support\n # of the optimizer and doesn't work with ParameterServerStrategy and\n # CentralStroageStrategy.\n aggregate_grads_outside_optimizer = (\n optimizer._HAS_AGGREGATE_GRAD and # pylint: disable=protected-access\n not isinstance(strategy.extended,\n parameter_server_strategy.ParameterServerStrategyExtended))\n\n if aggregate_grads_outside_optimizer:\n # We aggregate gradients before unscaling them, in case a subclass of\n # LossScaleOptimizer all-reduces in fp16. All-reducing in fp16 can only be\n # done on scaled gradients, not unscaled gradients, for numeric stability.\n gradients = optimizer._aggregate_gradients(zip(gradients, # pylint: disable=protected-access\n trainable_variables))\n if isinstance(optimizer, lso.LossScaleOptimizer):\n gradients = optimizer.get_unscaled_gradients(gradients)\n gradients = optimizer._clip_gradients(gradients) # pylint: disable=protected-access\n if trainable_variables:\n if aggregate_grads_outside_optimizer:\n optimizer.apply_gradients(\n zip(gradients, trainable_variables),\n experimental_aggregate_gradients=False)\n else:\n optimizer.apply_gradients(zip(gradients, trainable_variables))\n\n\ndef _is_scalar(x):\n return isinstance(x, (ops.Tensor, variables.Variable)) and x.shape.rank == 0\n\n\ndef write_scalar_summaries(logs, step):\n for name, value in logs.items():\n if _is_scalar(value):\n summary_ops_v2.scalar('batch_' + name, value, step=step)\n\n\ndef _minimum_control_deps(outputs):\n \"\"\"Returns the minimum control dependencies to ensure step succeeded.\"\"\"\n if context.executing_eagerly():\n return [] # Control dependencies not needed.\n outputs = nest.flatten(outputs, expand_composites=True)\n for out in outputs:\n # Variables can't be control dependencies.\n if not isinstance(out, variables.Variable):\n return [out] # Return first Tensor or Op from outputs.\n return [] # No viable Tensor or Op to use for control deps.\n\n\ndef _disallow_inside_tf_function(method_name):\n if ops.inside_function():\n error_msg = (\n 'Detected a call to `Model.{method_name}` inside a `tf.function`. '\n '`Model.{method_name} is a high-level endpoint that manages its own '\n '`tf.function`. Please move the call to `Model.{method_name}` outside '\n 'of all enclosing `tf.function`s. Note that you can call a `Model` '\n 'directly on `Tensor`s inside a `tf.function` like: `model(x)`.'\n ).format(method_name=method_name)\n raise RuntimeError(error_msg)\n"
] |
[
[
"tensorflow.python.keras.distribute.distributed_training_utils.is_tpu_strategy",
"tensorflow.python.keras.saving.saved_model.model_serialization.ModelSavedModelSaver",
"tensorflow.python.eager.context.async_wait",
"tensorflow.python.util.tf_decorator.make_decorator",
"tensorflow.python.distribute.distribution_strategy_context.has_strategy",
"tensorflow.python.ops.variables.Variable",
"tensorflow.python.eager.backprop.GradientTape",
"tensorflow.python.ops.ragged.ragged_concat_ops.concat",
"tensorflow.python.keras.engine.data_adapter.expand_1d",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.keras.optimizers.get",
"tensorflow.python.keras.engine.data_adapter.unpack_x_y_sample_weight",
"tensorflow.python.keras.engine.data_adapter.DataHandler",
"tensorflow.python.framework.ops.inside_function",
"tensorflow.python.eager.monitoring.BoolGauge",
"tensorflow.python.util.tf_export.keras_export",
"tensorflow.python.ops.summary_ops_v2.scalar",
"tensorflow.python.keras.mixed_precision.experimental.loss_scale_optimizer.LossScaleOptimizer",
"tensorflow.python.keras.engine.training_utils.RespectCompiledTrainableState",
"tensorflow.python.util.nest.map_structure",
"tensorflow.python.util.deprecation.deprecated",
"tensorflow.python.eager.def_function.function",
"tensorflow.python.ops.sparse_ops.sparse_concat_v2",
"tensorflow.python.util.nest.map_structure_up_to",
"tensorflow.python.keras.engine.network._is_hdf5_filepath",
"tensorflow.python.keras.callbacks.CallbackList",
"tensorflow.python.distribute.distribution_strategy_context.get_strategy",
"tensorflow.python.keras.engine.data_adapter.train_validation_split",
"tensorflow.python.keras.engine.data_adapter.single_batch_iterator",
"tensorflow.python.keras.engine.compile_utils.LossesContainer",
"tensorflow.python.keras.utils.version_utils.disallow_legacy_graph",
"tensorflow.python.ops.math_ops.range",
"tensorflow.python.ops.array_ops.concat",
"tensorflow.python.profiler.trace.Trace",
"tensorflow.python.distribute.distribute_coordinator_context.get_current_worker_context",
"tensorflow.python.keras.utils.tf_utils.to_numpy_or_python_type",
"tensorflow.python.keras.utils.tf_utils.get_tensor_spec",
"tensorflow.python.util.nest.flatten",
"tensorflow.python.keras.engine.compile_utils.MetricsContainer"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.3",
"2.4"
]
}
] |
NeelayS/realtime_hand
|
[
"219c772b9b7df60c390edac7da23f9cdddebca4d",
"219c772b9b7df60c390edac7da23f9cdddebca4d"
] |
[
"realtime_hand_3d/segmentation/models/espnet.py",
"realtime_hand_3d/segmentation/utils/metrics.py"
] |
[
"import torch\nimport torch.nn as nn\n\nfrom .retrieve import SEG_MODELS_REGISTRY\n\n\nclass CBR(nn.Module):\n \"\"\"\n This class defines the convolution layer with batch normalization and PReLU activation\n \"\"\"\n\n def __init__(self, nIn, nOut, kSize, stride=1):\n \"\"\"\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel size\n :param stride: stride rate for down-sampling. Default is 1\n \"\"\"\n super().__init__()\n padding = int((kSize - 1) / 2)\n # self.conv = nn.Conv2d(nIn, nOut, kSize, stride=stride, padding=padding, bias=False)\n self.conv = nn.Conv2d(\n nIn,\n nOut,\n (kSize, kSize),\n stride=stride,\n padding=(padding, padding),\n bias=False,\n )\n # self.conv1 = nn.Conv2d(nOut, nOut, (1, kSize), stride=1, padding=(0, padding), bias=False)\n self.bn = nn.BatchNorm2d(nOut, eps=1e-03)\n self.act = nn.PReLU(nOut)\n\n def forward(self, input):\n \"\"\"\n :param input: input feature map\n :return: transformed feature map\n \"\"\"\n output = self.conv(input)\n # output = self.conv1(output)\n output = self.bn(output)\n output = self.act(output)\n return output\n\n\nclass BR(nn.Module):\n \"\"\"\n This class groups the batch normalization and PReLU activation\n \"\"\"\n\n def __init__(self, nOut):\n \"\"\"\n :param nOut: output feature maps\n \"\"\"\n super().__init__()\n self.bn = nn.BatchNorm2d(nOut, eps=1e-03)\n self.act = nn.PReLU(nOut)\n\n def forward(self, input):\n \"\"\"\n :param input: input feature map\n :return: normalized and thresholded feature map\n \"\"\"\n output = self.bn(input)\n output = self.act(output)\n return output\n\n\nclass CB(nn.Module):\n \"\"\"\n This class groups the convolution and batch normalization\n \"\"\"\n\n def __init__(self, nIn, nOut, kSize, stride=1):\n \"\"\"\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel size\n :param stride: optinal stide for down-sampling\n \"\"\"\n super().__init__()\n padding = int((kSize - 1) / 2)\n self.conv = nn.Conv2d(\n nIn,\n nOut,\n (kSize, kSize),\n stride=stride,\n padding=(padding, padding),\n bias=False,\n )\n self.bn = nn.BatchNorm2d(nOut, eps=1e-03)\n\n def forward(self, input):\n \"\"\"\n :param input: input feature map\n :return: transformed feature map\n \"\"\"\n output = self.conv(input)\n output = self.bn(output)\n return output\n\n\nclass C(nn.Module):\n \"\"\"\n This class is for a convolutional layer.\n \"\"\"\n\n def __init__(self, nIn, nOut, kSize, stride=1):\n \"\"\"\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel size\n :param stride: optional stride rate for down-sampling\n \"\"\"\n super().__init__()\n padding = int((kSize - 1) / 2)\n self.conv = nn.Conv2d(\n nIn,\n nOut,\n (kSize, kSize),\n stride=stride,\n padding=(padding, padding),\n bias=False,\n )\n\n def forward(self, input):\n \"\"\"\n :param input: input feature map\n :return: transformed feature map\n \"\"\"\n output = self.conv(input)\n return output\n\n\nclass CDilated(nn.Module):\n \"\"\"\n This class defines the dilated convolution.\n \"\"\"\n\n def __init__(self, nIn, nOut, kSize, stride=1, d=1):\n \"\"\"\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param kSize: kernel size\n :param stride: optional stride rate for down-sampling\n :param d: optional dilation rate\n \"\"\"\n super().__init__()\n padding = int((kSize - 1) / 2) * d\n self.conv = nn.Conv2d(\n nIn,\n nOut,\n (kSize, kSize),\n stride=stride,\n padding=(padding, padding),\n bias=False,\n dilation=d,\n )\n\n def forward(self, input):\n \"\"\"\n :param input: input feature map\n :return: transformed feature map\n \"\"\"\n output = self.conv(input)\n return output\n\n\nclass DownSamplerB(nn.Module):\n def __init__(self, nIn, nOut):\n super().__init__()\n n = int(nOut / 5)\n n1 = nOut - 4 * n\n self.c1 = C(nIn, n, 3, 2)\n self.d1 = CDilated(n, n1, 3, 1, 1)\n self.d2 = CDilated(n, n, 3, 1, 2)\n self.d4 = CDilated(n, n, 3, 1, 4)\n self.d8 = CDilated(n, n, 3, 1, 8)\n self.d16 = CDilated(n, n, 3, 1, 16)\n self.bn = nn.BatchNorm2d(nOut, eps=1e-3)\n self.act = nn.PReLU(nOut)\n\n def forward(self, input):\n output1 = self.c1(input)\n d1 = self.d1(output1)\n d2 = self.d2(output1)\n d4 = self.d4(output1)\n d8 = self.d8(output1)\n d16 = self.d16(output1)\n\n add1 = d2\n add2 = add1 + d4\n add3 = add2 + d8\n add4 = add3 + d16\n\n combine = torch.cat([d1, add1, add2, add3, add4], 1)\n # combine_in_out = input + combine\n output = self.bn(combine)\n output = self.act(output)\n return output\n\n\nclass DilatedParllelResidualBlockB(nn.Module):\n \"\"\"\n This class defines the ESP block, which is based on the following principle\n Reduce ---> Split ---> Transform --> Merge\n \"\"\"\n\n def __init__(self, nIn, nOut, add=True):\n \"\"\"\n :param nIn: number of input channels\n :param nOut: number of output channels\n :param add: if true, add a residual connection through identity operation. You can use projection too as\n in ResNet paper, but we avoid to use it if the dimensions are not the same because we do not want to\n increase the module complexity\n \"\"\"\n super().__init__()\n n = int(nOut / 5)\n n1 = nOut - 4 * n\n self.c1 = C(nIn, n, 1, 1)\n self.d1 = CDilated(n, n1, 3, 1, 1) # dilation rate of 2^0\n self.d2 = CDilated(n, n, 3, 1, 2) # dilation rate of 2^1\n self.d4 = CDilated(n, n, 3, 1, 4) # dilation rate of 2^2\n self.d8 = CDilated(n, n, 3, 1, 8) # dilation rate of 2^3\n self.d16 = CDilated(n, n, 3, 1, 16) # dilation rate of 2^4\n self.bn = BR(nOut)\n self.add = add\n\n def forward(self, input):\n \"\"\"\n :param input: input feature map\n :return: transformed feature map\n \"\"\"\n # reduce\n output1 = self.c1(input)\n # split and transform\n d1 = self.d1(output1)\n d2 = self.d2(output1)\n d4 = self.d4(output1)\n d8 = self.d8(output1)\n d16 = self.d16(output1)\n\n # heirarchical fusion for de-gridding\n add1 = d2\n add2 = add1 + d4\n add3 = add2 + d8\n add4 = add3 + d16\n\n # merge\n combine = torch.cat([d1, add1, add2, add3, add4], 1)\n\n # if residual version\n if self.add:\n combine = input + combine\n output = self.bn(combine)\n return output\n\n\nclass InputProjectionA(nn.Module):\n \"\"\"\n This class projects the input image to the same spatial dimensions as the feature map.\n For example, if the input image is 512 x512 x3 and spatial dimensions of feature map size are 56x56xF, then\n this class will generate an output of 56x56x3\n \"\"\"\n\n def __init__(self, samplingTimes):\n \"\"\"\n :param samplingTimes: The rate at which you want to down-sample the image\n \"\"\"\n super().__init__()\n self.pool = nn.ModuleList()\n for i in range(0, samplingTimes):\n # pyramid-based approach for down-sampling\n self.pool.append(nn.AvgPool2d(3, stride=2, padding=1))\n\n def forward(self, input):\n \"\"\"\n :param input: Input RGB Image\n :return: down-sampled image (pyramid-based approach)\n \"\"\"\n for pool in self.pool:\n input = pool(input)\n return input\n\n\nclass ESPNet_Encoder(nn.Module):\n def __init__(self, in_channels=1, n_classes=3, p=5, q=3):\n super().__init__()\n\n self.level1 = CBR(in_channels, 16, 3, 2)\n self.sample1 = InputProjectionA(1)\n self.sample2 = InputProjectionA(2)\n\n self.b1 = BR(16 + 3)\n self.level2_0 = DownSamplerB(16 + 3, 64)\n\n self.level2 = nn.ModuleList()\n for i in range(0, p):\n self.level2.append(DilatedParllelResidualBlockB(64, 64))\n self.b2 = BR(128 + 3)\n\n self.level3_0 = DownSamplerB(128 + 3, 128)\n self.level3 = nn.ModuleList()\n for i in range(0, q):\n self.level3.append(DilatedParllelResidualBlockB(128, 128))\n self.b3 = BR(256)\n\n self.classifier = C(256, n_classes, 1, 1)\n\n def forward(self, input):\n\n output0 = self.level1(input)\n inp1 = self.sample1(input)\n inp2 = self.sample2(input)\n\n output0_cat = self.b1(torch.cat([output0, inp1], 1))\n output1_0 = self.level2_0(output0_cat) # down-sampled\n\n for i, layer in enumerate(self.level2):\n if i == 0:\n output1 = layer(output1_0)\n else:\n output1 = layer(output1)\n\n output1_cat = self.b2(torch.cat([output1, output1_0, inp2], 1))\n\n output2_0 = self.level3_0(output1_cat) # down-sampled\n for i, layer in enumerate(self.level3):\n if i == 0:\n output2 = layer(output2_0)\n else:\n output2 = layer(output2)\n\n output2_cat = self.b3(torch.cat([output2_0, output2], 1))\n\n classifier = self.classifier(output2_cat)\n\n return classifier\n\n\n@SEG_MODELS_REGISTRY.register()\nclass ESPNet(nn.Module):\n def __init__(self, in_channels=1, n_classes=3, p=2, q=3, encoderFile=None):\n super().__init__()\n\n self.encoder = ESPNet_Encoder(in_channels, n_classes, p, q)\n if encoderFile != None:\n self.encoder.load_state_dict(torch.load(encoderFile))\n print(\"Encoder loaded!\")\n # load the encoder modules\n self.modules = []\n for i, m in enumerate(self.encoder.children()):\n self.modules.append(m)\n\n # light-weight decoder\n self.level3_C = C(128 + 3, n_classes, 1, 1)\n self.br = nn.BatchNorm2d(n_classes, eps=1e-03)\n self.conv = CBR(19 + n_classes, n_classes, 3, 1)\n\n self.up_l3 = nn.Sequential(\n nn.ConvTranspose2d(\n n_classes,\n n_classes,\n 2,\n stride=2,\n padding=0,\n output_padding=0,\n bias=False,\n )\n )\n self.combine_l2_l3 = nn.Sequential(\n BR(2 * n_classes),\n DilatedParllelResidualBlockB(2 * n_classes, n_classes, add=False),\n )\n\n self.up_l2 = nn.Sequential(\n nn.ConvTranspose2d(\n n_classes,\n n_classes,\n 2,\n stride=2,\n padding=0,\n output_padding=0,\n bias=False,\n ),\n BR(n_classes),\n )\n\n self.classifier = nn.ConvTranspose2d(\n n_classes, n_classes, 2, stride=2, padding=0, output_padding=0, bias=False\n )\n\n def forward(self, input):\n\n output0 = self.modules[0](input)\n inp1 = self.modules[1](input)\n inp2 = self.modules[2](input)\n\n output0_cat = self.modules[3](torch.cat([output0, inp1], 1))\n output1_0 = self.modules[4](output0_cat) # down-sampled\n\n for i, layer in enumerate(self.modules[5]):\n if i == 0:\n output1 = layer(output1_0)\n else:\n output1 = layer(output1)\n\n output1_cat = self.modules[6](torch.cat([output1, output1_0, inp2], 1))\n\n output2_0 = self.modules[7](output1_cat) # down-sampled\n for i, layer in enumerate(self.modules[8]):\n if i == 0:\n output2 = layer(output2_0)\n else:\n output2 = layer(output2)\n\n output2_cat = self.modules[9](\n torch.cat([output2_0, output2], 1)\n ) # concatenate for feature map width expansion\n\n output2_c = self.up_l3(self.br(self.modules[10](output2_cat))) # RUM\n\n output1_C = self.level3_C(output1_cat) # project to C-dimensional space\n comb_l2_l3 = self.up_l2(\n self.combine_l2_l3(torch.cat([output1_C, output2_c], 1))\n ) # RUM\n\n concat_features = self.conv(torch.cat([comb_l2_l3, output0_cat], 1))\n\n classifier = self.classifier(concat_features)\n\n out = []\n out.append(classifier)\n\n return out\n",
"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\ndef compute_iou(pred, target, is_idx=None):\n\n n_classes = len(np.unique(target.cpu().data.numpy()))\n\n if n_classes == 1:\n pred_unique_np = np.unique(pred.cpu().data.numpy())\n if len(pred_unique_np) == 1 and pred_unique_np[0] == 0:\n return np.array([1.0])\n else:\n return np.array([0.0])\n\n ious = []\n if not pred.shape[2] == target.shape[1]:\n pred = nn.functional.interpolate(\n pred,\n size=(target.shape[1], target.shape[2]),\n mode=\"bilinear\",\n align_corners=True,\n )\n\n if not is_idx:\n pred = torch.argmax(pred, dim=1)\n\n pred = pred.view(-1)\n target = target.view(-1)\n\n for cls in range(1, n_classes):\n pred_inds = pred == cls\n target_inds = target == cls\n intersection = (pred_inds[target_inds]).long().sum().data.cpu().item()\n union = (\n pred_inds.long().sum().data.cpu().item()\n + target_inds.long().sum().data.cpu().item()\n - intersection\n )\n if union == 0:\n ious.append(1.0)\n else:\n ious.append(float(intersection) / float(union))\n\n return np.array(ious)\n"
] |
[
[
"torch.nn.ConvTranspose2d",
"torch.cat",
"torch.load",
"torch.nn.PReLU",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.nn.AvgPool2d",
"torch.nn.BatchNorm2d"
],
[
"numpy.array",
"torch.nn.functional.interpolate",
"torch.argmax"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
FrederikWarburg/NLSPN_ECCV20
|
[
"2db2d4eb269c7d27e16c8ff4f4fb3331778ef6b6",
"2db2d4eb269c7d27e16c8ff4f4fb3331778ef6b6"
] |
[
"src/main.py",
"src/model/unetmodel.py"
] |
[
"\"\"\"\n Non-Local Spatial Propagation Network for Depth Completion\n Jinsun Park, Kyungdon Joo, Zhe Hu, Chi-Kuei Liu and In So Kweon\n\n European Conference on Computer Vision (ECCV), Aug 2020\n\n Project Page : https://github.com/zzangjinsun/NLSPN_ECCV20\n Author : Jinsun Park ([email protected])\n\n ======================================================================\n\n main script for training and testing.\n\"\"\"\n\n\nfrom config import args as args_config\nimport time\nimport random\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = args_config.gpus\nos.environ[\"MASTER_ADDR\"] = 'localhost'\nos.environ[\"MASTER_PORT\"] = args_config.port\n\nimport json\nimport numpy as np\nfrom tqdm import tqdm\n\nimport torch\nfrom torch import nn\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.distributed import DistributedSampler\n\nimport utility\nfrom model import get as get_model\nfrom data import get as get_data\nfrom loss import get as get_loss\nfrom summary import get as get_summary\nfrom metric import get as get_metric\n\n# Multi-GPU and Mixed precision supports\n# NOTE : Only 1 process per GPU is supported now\nimport torch.multiprocessing as mp\nimport torch.distributed as dist\nimport apex\nfrom apex.parallel import DistributedDataParallel as DDP\nfrom apex import amp\n\n# Minimize randomness\ntorch.manual_seed(args_config.seed)\nnp.random.seed(args_config.seed)\nrandom.seed(args_config.seed)\ntorch.cuda.manual_seed_all(args_config.seed)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\n\n\ndef check_args(args):\n if args.batch_size < args.num_gpus:\n print(\"batch_size changed : {} -> {}\".format(args.batch_size,\n args.num_gpus))\n args.batch_size = args.num_gpus\n\n new_args = args\n if args.pretrain is not None:\n assert os.path.exists(args.pretrain), \\\n \"file not found: {}\".format(args.pretrain)\n\n if args.resume:\n print(\"resume\")\n checkpoint = torch.load(args.pretrain)\n\n new_args = checkpoint['args']\n new_args.test_only = args.test_only\n new_args.pretrain = args.pretrain\n new_args.dir_data = args.dir_data\n new_args.resume = args.resume\n\n return new_args\n\n\ndef train(gpu, args):\n # Initialize workers\n # NOTE : the worker with gpu=0 will do logging\n dist.init_process_group(backend='nccl', init_method='env://',\n world_size=args.num_gpus, rank=gpu)\n torch.cuda.set_device(gpu)\n\n # Prepare dataset\n data = get_data(args)\n\n data_train = data(args, 'train')\n data_val = data(args, 'val')\n\n sampler_train = DistributedSampler(\n data_train, num_replicas=args.num_gpus, rank=gpu)\n sampler_val = DistributedSampler(\n data_val, num_replicas=args.num_gpus, rank=gpu)\n\n batch_size = args.batch_size // args.num_gpus\n\n loader_train = DataLoader(\n dataset=data_train, batch_size=batch_size, shuffle=False,\n num_workers=args.num_threads, pin_memory=True, sampler=sampler_train,\n drop_last=True)\n loader_val = DataLoader(\n dataset=data_val, batch_size=batch_size, shuffle=False,\n num_workers=args.num_threads, pin_memory=True, sampler=sampler_val,\n drop_last=False)\n\n # Network\n model = get_model(args)\n net = model(args)\n net.cuda(gpu)\n\n if gpu == 0:\n if args.pretrain is not None:\n assert os.path.exists(args.pretrain), \\\n \"file not found: {}\".format(args.pretrain)\n\n checkpoint = torch.load(args.pretrain)\n net.load_state_dict(checkpoint['net'])\n\n print('Load network parameters from : {}'.format(args.pretrain))\n\n # Loss\n loss = get_loss(args)\n loss = loss(args)\n loss.cuda(gpu)\n\n # Optimizer\n optimizer, scheduler = utility.make_optimizer_scheduler(args, net)\n\n net = apex.parallel.convert_syncbn_model(net)\n net, optimizer = amp.initialize(net, optimizer, opt_level=args.opt_level,\n verbosity=0)\n\n if gpu == 0:\n if args.pretrain is not None:\n if args.resume:\n try:\n optimizer.load_state_dict(checkpoint['optimizer'])\n scheduler.load_state_dict(checkpoint['scheduler'])\n amp.load_state_dict(checkpoint['amp'])\n\n print('Resume optimizer, scheduler and amp '\n 'from : {}'.format(args.pretrain))\n except KeyError:\n print('State dicts for resume are not saved. '\n 'Use --save_full argument')\n\n del checkpoint\n\n net = DDP(net)\n\n metric = get_metric(args)\n metric = metric(args)\n summary = get_summary(args)\n\n if args.debug:\n if gpu == 0:\n utility.backup_source_code(args.save_dir + '/code')\n try:\n os.makedirs(args.save_dir, exist_ok=True)\n os.makedirs(args.save_dir + '/train', exist_ok=True)\n os.makedirs(args.save_dir + '/val', exist_ok=True)\n except OSError:\n pass\n else:\n print(\"DEBUG MODE\")\n\n if gpu == 0:\n writer_train = summary(args.save_dir, 'train', args,\n loss.loss_name, metric.metric_name)\n writer_val = summary(args.save_dir, 'val', args,\n loss.loss_name, metric.metric_name)\n\n with open(args.save_dir + '/args.json', 'w') as args_json:\n json.dump(args.__dict__, args_json, indent=4)\n\n if args.warm_up:\n warm_up_cnt = 0.0\n warm_up_max_cnt = len(loader_train)+1.0\n\n for epoch in range(1, args.epochs+1):\n # Train\n net.train()\n\n sampler_train.set_epoch(epoch)\n\n if gpu == 0:\n current_time = time.strftime('%y%m%d@%H:%M:%S')\n\n list_lr = []\n for g in optimizer.param_groups:\n list_lr.append(g['lr'])\n\n print('=== Epoch {:5d} / {:5d} | Lr : {} | {} | {} ==='.format(\n epoch, args.epochs, list_lr, current_time, args.save_dir\n ))\n\n num_sample = len(loader_train) * loader_train.batch_size * args.num_gpus\n\n if gpu == 0:\n pbar = tqdm(total=num_sample)\n log_cnt = 0.0\n log_loss = 0.0\n\n for batch, sample in enumerate(loader_train):\n sample = {key: val.cuda(gpu) for key, val in sample.items()\n if val is not None}\n\n if epoch == 1 and args.warm_up:\n warm_up_cnt += 1\n\n for param_group in optimizer.param_groups:\n lr_warm_up = param_group['initial_lr'] \\\n * warm_up_cnt / warm_up_max_cnt\n param_group['lr'] = lr_warm_up\n\n optimizer.zero_grad()\n\n output = net(sample)\n\n loss_sum, loss_val = loss(sample, output)\n \n # Divide by batch size\n loss_sum = loss_sum / loader_train.batch_size\n loss_val = loss_val / loader_train.batch_size\n\n with amp.scale_loss(loss_sum, optimizer) as scaled_loss:\n scaled_loss.backward()\n\n optimizer.step()\n\n if gpu == 0:\n metric_val = metric.evaluate(sample, output, 'train')\n writer_train.add(loss_val, metric_val)\n\n log_cnt += 1\n log_loss += loss_sum.item()\n\n current_time = time.strftime('%y%m%d@%H:%M:%S')\n error_str = '{:<10s}| {} | Loss = {:.4f}'.format(\n 'Train', current_time, log_loss / log_cnt)\n\n if epoch == 1 and args.warm_up:\n list_lr = []\n for g in optimizer.param_groups:\n list_lr.append(round(g['lr'], 6))\n error_str = '{} | Lr Warm Up : {}'.format(error_str,\n list_lr)\n\n pbar.set_description(error_str)\n pbar.update(loader_train.batch_size * args.num_gpus)\n \n if gpu == 0:\n pbar.close()\n\n writer_train.update(epoch, sample, output)\n\n if args.save_full or epoch == args.epochs:\n state = {\n 'net': net.module.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'scheduler': scheduler.state_dict(),\n 'amp': amp.state_dict(),\n 'args': args\n }\n else:\n state = {\n 'net': net.module.state_dict(),\n 'args': args\n }\n\n torch.save(state, '{}/model_{:05d}.pt'.format(args.save_dir, epoch))\n\n # update loss function epoch counter\n loss.epoch_num += 1\n\n # Val\n torch.set_grad_enabled(False)\n net.eval()\n\n num_sample = len(loader_val) * loader_val.batch_size * args.num_gpus\n\n if gpu == 0:\n pbar = tqdm(total=num_sample)\n log_cnt = 0.0\n log_loss = 0.0\n\n for batch, sample in enumerate(loader_val):\n sample = {key: val.cuda(gpu) for key, val in sample.items()\n if val is not None}\n\n output = net(sample)\n\n loss_sum, loss_val = loss(sample, output)\n\n # Divide by batch size\n loss_sum = loss_sum / loader_val.batch_size\n loss_val = loss_val / loader_val.batch_size\n\n if gpu == 0:\n metric_val = metric.evaluate(sample, output, 'train')\n writer_val.add(loss_val, metric_val)\n\n log_cnt += 1\n log_loss += loss_sum.item()\n\n current_time = time.strftime('%y%m%d@%H:%M:%S')\n error_str = '{:<10s}| {} | Loss = {:.4f}'.format(\n 'Val', current_time, log_loss / log_cnt)\n pbar.set_description(error_str)\n pbar.update(loader_val.batch_size * args.num_gpus)\n\n if gpu == 0:\n pbar.close()\n\n writer_val.update(epoch, sample, output)\n print('')\n\n writer_val.save(epoch, batch, sample, output)\n\n torch.set_grad_enabled(True)\n\n scheduler.step()\n\n\ndef test(args):\n # Prepare dataset\n data = get_data(args)\n\n data_test = data(args, 'test')\n\n loader_test = DataLoader(dataset=data_test, batch_size=args.batch_size,\n shuffle=False, num_workers=args.num_threads)\n\n # Network\n model = get_model(args)\n net = model(args)\n net.cuda()\n\n if args.pretrain is not None:\n assert os.path.exists(args.pretrain), \\\n \"file not found: {}\".format(args.pretrain)\n\n checkpoint = torch.load(args.pretrain)\n key_m, key_u = net.load_state_dict(checkpoint['net'], strict=False)\n\n if key_u:\n print('Unexpected keys :')\n print(key_u)\n\n if key_m:\n print('Missing keys :')\n print(key_m)\n raise KeyError\n\n net = nn.DataParallel(net)\n\n metric = get_metric(args)\n metric = metric(args)\n summary = get_summary(args)\n\n try:\n os.makedirs(args.save_dir, exist_ok=True)\n os.makedirs(args.save_dir + '/test', exist_ok=True)\n except OSError:\n pass\n\n writer_test = summary(args.save_dir, 'test', args, None, metric.metric_name)\n\n net.eval()\n\n num_sample = len(loader_test)*loader_test.batch_size\n\n pbar = tqdm(total=num_sample)\n\n t_total = 0\n\n with torch.no_grad():\n for batch, sample in enumerate(loader_test):\n sample = {key: val.cuda() for key, val in sample.items()\n if val is not None}\n\n t0 = time.time()\n output = net(sample)\n t1 = time.time()\n\n t_total += (t1 - t0)\n\n metric_val = metric.evaluate(sample, output, 'train')\n\n writer_test.add(None, metric_val)\n\n # Save data for analysis\n if args.save_image:\n writer_test.save(args.epochs, batch, sample, output)\n\n current_time = time.strftime('%y%m%d@%H:%M:%S')\n error_str = '{} | Test'.format(current_time)\n pbar.set_description(error_str)\n pbar.update(loader_test.batch_size)\n\n pbar.close()\n\n writer_test.update(args.epochs, sample, output)\n\n t_avg = t_total / num_sample\n print('Elapsed time : {} sec, '\n 'Average processing time : {} sec'.format(t_total, t_avg))\n\n with open(os.path.join(args.save_dir, 'test', 'test_time.txt'), 'w+') as f:\n f.write('Elapsed time : {} sec, '\n 'Average processing time : {} sec'.format(t_total, t_avg))\n\n\ndef main(args):\n if not args.test_only:\n if args.no_multiprocessing:\n train(0, args)\n else:\n assert args.num_gpus > 0\n\n spawn_context = mp.spawn(train, nprocs=args.num_gpus, args=(args,),\n join=False)\n\n while not spawn_context.join():\n pass\n\n for process in spawn_context.processes:\n if process.is_alive():\n process.terminate()\n process.join()\n\n args.pretrain = '{}/model_{:05d}.pt'.format(args.save_dir,\n args.epochs)\n\n test(args)\n\n\nif __name__ == '__main__':\n args_main = check_args(args_config)\n\n print('\\n\\n=== Arguments ===')\n cnt = 0\n for key in sorted(vars(args_main)):\n print(key, ':', getattr(args_main, key), end=' | ')\n cnt += 1\n if (cnt + 1) % 5 == 0:\n print('')\n print('\\n')\n\n main(args_main)\n",
"\n\nimport torch\nfrom torch import nn\nfrom .visualtransformer import VisualTransformer\nfrom .common import get_resnet18, get_resnet34, _remove_extra_pad\nfrom torchvision.models.resnet import BasicBlock\nfrom torchvision import models\nimport math\nfrom .attention_module.simple_attention import build_simple_attention_module\n\ndef _concat(fd, fe, vt=None, aggregate='cat', dim=1):\n \n fd = _remove_extra_pad(fd, fe)\n\n if vt is None:\n if aggregate == 'cat':\n f = torch.cat((fd, fe), dim=dim)\n elif aggregate == 'sum':\n f = fd + fe\n else:\n if aggregate == 'cat':\n f = torch.cat((fd, fe, vt), dim=dim)\n elif aggregate == 'sum':\n f = fd + fe + vt \n\n return f\n\n\ndef _upsampling(ch_in, ch_out, bn=True, relu=True, upsampling = 'learnable'):\n\n layers = []\n if upsampling == 'learnable':\n layers.append(nn.ConvTranspose2d(ch_in, ch_out, kernel=3, stride=2, padding=0, output_padding=0))\n else:\n layers.append(nn.Upsample(mode='bilinear', scale_factor=2, align_corners=False))\n layers.append(nn.Conv2d(ch_in, ch_out, kernel_size=1, stride=1))\n \n if bn:\n layers.append(nn.BatchNorm2d(ch_out))\n if relu:\n layers.append(nn.LeakyReLU(0.2, inplace=True))\n\n layers = nn.Sequential(*layers)\n\n return layers\n\ndef conv_bn_relu(ch_in, ch_out, kernel, stride=1, padding=0, bn=True, relu=True, maxpool=False):\n\n layers = []\n layers.append(nn.Conv2d(ch_in, ch_out, kernel, stride, padding, bias=not bn))\n if bn:\n layers.append(nn.BatchNorm2d(ch_out))\n if relu:\n layers.append(nn.LeakyReLU(0.2, inplace=True))\n if maxpool:\n layers.append(nn.MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False))\n\n layers = nn.Sequential(*layers)\n\n return layers\n\n\ndef double_conv(ch_in, ch_mid, ch_out, bn=True, relu=True):\n\n layers = []\n\n layers.append(conv_bn_relu(ch_in, ch_mid, kernel=3, stride=1, padding=1, bn=relu, relu=relu))\n layers.append(conv_bn_relu(ch_mid, ch_out, kernel=3, stride=1, padding=1, bn=relu, relu=relu))\n\n layers = nn.Sequential(*layers)\n\n return layers\n\n\nclass Upsample(nn.Module):\n def __init__(self, ch_in1, ch_in2, ch_out, bn=True, relu=True, upsampling = 'learnable', aggregate = 'cat'):\n super(Upsample, self).__init__()\n\n self.aggregate = aggregate\n\n self.upsampling = _upsampling(ch_in1, ch_in1, bn=bn, relu=relu, upsampling = upsampling)\n self.conv = double_conv(ch_in1+ch_in2, (ch_in1+ch_in2)//2, ch_out, bn=bn, relu=relu)\n\n def forward(self, x, x1 = None):\n \n x = self.upsampling(x)\n if x1 is not None:\n x = _concat(x, x1, aggregate=self.aggregate, dim=1)\n x = self.conv(x)\n\n return x\n\nclass Guide(nn.Module):\n def __init__(self, ch_in1, ch_in2, ch_out, vt = None, bn=True, relu=True, aggregate = 'cat'):\n super(Guide, self).__init__()\n\n self.aggregate = aggregate\n\n self.conv1 = conv_bn_relu(ch_in1, ch_out, kernel=1, stride=1, padding=0, bn=bn, relu=relu, maxpool=False)\n self.conv2 = conv_bn_relu(ch_in2, ch_out, kernel=1, stride=1, padding=0, bn=bn, relu=relu, maxpool=False)\n self.vt = vt\n\n def forward(self, fe_dep, fd_rgb):\n\n fd_rgb = self.conv1(fd_rgb)\n if self.vt is not None:\n proj_ = self.vt(fd_rgb, fe_dep)\n if self.aggregate == 'vt_only':\n x = _concat(proj_, fe_dep, aggregate='cat') \n else: \n x = _concat(fd_rgb, fe_dep, proj_, aggregate=self.aggregate)\n else:\n x = _concat(fd_rgb, fe_dep, aggregate=self.aggregate)\n\n x = self.conv2(x)\n\n return x\n\nclass UNETModel(nn.Module):\n def __init__(self, args = None):\n super(UNETModel, self).__init__()\n\n self.args = args\n\n self.network = self.args.network\n self.aggregate = self.args.aggregate\n self.guide = self.args.guide\n self.upsampling = 'not_learnable' #'leanable' # not_learnable\n self.attention_type = self.args.attention_type\n self.supervision = self.args.supervision\n self.num_tokens = [int(l) for l in self.args.num_tokens.split(\"+\")]\n self.token_size = [int(l) for l in self.args.token_size.split(\"+\")]\n self.num_heads = [int(l) for l in self.args.num_heads.split(\"+\")]\n self.groups = [int(l) for l in self.args.groups.split(\"+\")]\n self.kqv_groups = [int(l) for l in self.args.kqv_groups.split(\"+\")]\n\n\n if self.guide == 'cat':\n self.D_guide = 2\n elif self.guide == 'sum':\n self.D_guide = 1\n elif self.guide == 'none':\n self.D_guide = 1 \n else:\n raise NotImplementedError \n\n if self.aggregate == 'cat':\n self.D_skip = 1\n elif self.aggregate == 'sum':\n self.D_skip = 0\n else:\n raise NotImplementedError \n \n if self.network == 'resnet18':\n net = get_resnet18(False)\n elif self.network == 'resnet34':\n net = get_resnet34(False)\n else:\n raise NotImplementedError\n\n ####\n # RGB Stream\n ####\n\n\n # Encoder\n self.conv1_rgb = torch.nn.Sequential(*[net.conv1, net.bn1, net.relu]) #1/2\n self.conv2_rgb = net.layer1 #1/2\n self.conv3_rgb = net.layer2 #1/4\n self.conv4_rgb = net.layer3 #1/8\n self.conv5_rgb = net.layer4 #1/16\n \n self.bottleneck1 = conv_bn_relu(512, 1024, kernel=3, stride=2, padding=1, bn=True, relu=True) # 1/32\n self.bottleneck2 = conv_bn_relu(1024, 512, kernel=3, stride=1, padding=1, bn=True, relu=True) # 1/32\n\n # Decoder\n self.dec5_rgb = Upsample(512, self.D_skip * 512, 256, upsampling=self.upsampling, aggregate=self.aggregate) # 1/8\n self.dec4_rgb = Upsample(256, self.D_skip * 256, 128, upsampling=self.upsampling, aggregate=self.aggregate) # 1/4\n self.dec3_rgb = Upsample(128, self.D_skip * 128, 64, upsampling=self.upsampling, aggregate=self.aggregate) # 1/2\n self.dec2_rgb = Upsample(64, self.D_skip * 64, 64, upsampling=self.upsampling, aggregate=self.aggregate) # 1/2\n\n self.guide1 = Guide(64, self.D_guide * 64, 64, None, aggregate=self.guide)\n self.guide2 = Guide(64, self.D_guide * 128, 128, None, aggregate=self.guide)\n self.guide3 = Guide(128, self.D_guide * 256, 256, None, aggregate=self.guide)\n self.guide4 = Guide(256, self.D_guide * 512, 512, None, aggregate=self.guide)\n \n ####\n # Depth Stream\n ####\n \n # Encoder\n self.conv1_dep = conv_bn_relu(1, 64, kernel=7, stride=2, padding=3, bn=True, relu=True, maxpool=False) # 1/2\n self.conv2_dep = net.layer1 # 1/2\n self.conv3_dep = net.layer2 # 1/4\n self.conv4_dep = net.layer3 # 1/8\n self.conv5_dep = net.layer4 # 1/16\n\n self.bottleneck1_dep = conv_bn_relu(512, 1024, kernel=3, stride=2, padding=1, bn=True, relu=True) # 1/32\n self.bottleneck2_dep = conv_bn_relu(1024, 512, kernel=3, stride=1, padding=1, bn=True, relu=True) # 1/32\n\n # Decoder\n self.dec5_dep = Upsample(512, self.D_skip * 512, 256, upsampling=self.upsampling, aggregate=self.aggregate) # 1/16\n self.dec4_dep = Upsample(256, self.D_skip * 256, 128, upsampling=self.upsampling, aggregate=self.aggregate) # 1/8\n self.dec3_dep = Upsample(128, self.D_skip * 128, 64, upsampling=self.upsampling, aggregate=self.aggregate) # 1/4\n self.dec2_dep = Upsample(64, self.D_skip * 64, 64, upsampling=self.upsampling, aggregate=self.aggregate) # 1/2\n self.dec1_dep = Upsample(64, 0, 64, upsampling=self.upsampling, bn=False) # 1/1\n\n # Depth Branch\n self.id_dec1 = conv_bn_relu(64, 64, kernel=3, stride=1, padding=1, bn=False, relu=True) # 1/1\n self.id_dec0 = conv_bn_relu(64, 1, kernel=3, stride=1, padding=1, bn=False, relu=True, maxpool=False)\n\n if 'confidence' in self.supervision:\n # Confidence Branch\n self.cf_dec1 = conv_bn_relu(64, 64, kernel=3, stride=1, padding=1, bn=False, relu=True) # 1/1\n self.cf_dec0 = nn.Sequential(\n nn.Conv2d(64, 1, kernel_size=3, stride=1, padding=1),\n nn.Softplus()\n )\n\n def forward(self, sample):\n\n rgb = sample['rgb']\n dep = sample['dep']\n output = {}\n \n # Encoding RGB\n fe1_rgb = self.conv1_rgb(rgb)\n fe2_rgb = self.conv2_rgb(fe1_rgb)\n fe3_rgb = self.conv3_rgb(fe2_rgb)\n fe4_rgb = self.conv4_rgb(fe3_rgb)\n fe5_rgb = self.conv5_rgb(fe4_rgb)\n\n # bottleneck\n bottleneck1_rgb = self.bottleneck1(fe5_rgb)\n bottleneck2_rgb = self.bottleneck2(bottleneck1_rgb)\n\n # Decoding RGB\n fd5_rgb = self.dec5_rgb(bottleneck2_rgb, fe5_rgb)\n fd4_rgb = self.dec4_rgb(fd5_rgb, fe4_rgb)\n fd3_rgb = self.dec3_rgb(fd4_rgb, fe3_rgb)\n fd2_rgb = self.dec2_rgb(fd3_rgb, fe2_rgb)\n\n ###\n # DEPTH UNET\n ###\n \n # Encoding Depth\n fe1_dep = self.conv1_dep(dep)\n\n fe2_dep = self.conv2_dep(fe1_dep)\n fe2_dep = self.guide1(fe2_dep, fd2_rgb)\n\n fe3_dep = self.conv3_dep(fe2_dep)\n fe3_dep = self.guide2(fe3_dep, fd3_rgb)\n\n fe4_dep = self.conv4_dep(fe3_dep)\n fe4_dep = self.guide3(fe4_dep, fd4_rgb)\n\n fe5_dep = self.conv5_dep(fe4_dep)\n fe5_dep = self.guide4(fe5_dep, fd5_rgb)\n\n # bottleneck\n bottleneck1_dep = self.bottleneck1_dep(fe5_dep)\n bottleneck2_dep = self.bottleneck2_dep(bottleneck1_dep)\n\n # Decoding Depth\n fd5_dep = self.dec5_dep(bottleneck2_dep, fe5_dep)\n fd4_dep = self.dec4_dep(fd5_dep, fe4_dep)\n fd3_dep = self.dec3_dep(fd4_dep, fe3_dep)\n fd2_dep = self.dec2_dep(fd3_dep, fe2_dep)\n fd1_dep = self.dec1_dep(fd2_dep)\n\n ###\n # PREDICTION HEADS\n ###\n\n # Depth Decoding\n id_fd1 = self.id_dec1(fd1_dep)\n pred = self.id_dec0(id_fd1)\n pred = _remove_extra_pad(pred, dep)\n output['pred'] = pred\n\n # Confidence Decoding\n if 'confidence' in self.supervision:\n cf_fd1 = self.cf_dec1(fd1_dep)\n confidence = self.cf_dec0(cf_fd1)\n confidence = _remove_extra_pad(confidence, dep)\n output['confidence'] = confidence\n\n return output\n\nif __name__ == \"__main__\":\n \n rgb = torch.FloatTensor(torch.randn((1,3, 1216,300)))\n dep = torch.FloatTensor(torch.randn((1,1, 1216,300)))\n\n sample = {'rgb':rgb,'dep':dep}\n\n model = UNETModel()\n\n out = model(sample)\n print(out['pred'].shape)\n"
] |
[
[
"torch.distributed.init_process_group",
"torch.cuda.set_device",
"numpy.random.seed",
"torch.utils.data.distributed.DistributedSampler",
"torch.manual_seed",
"torch.load",
"torch.multiprocessing.spawn",
"torch.utils.data.DataLoader",
"torch.set_grad_enabled",
"torch.no_grad",
"torch.cuda.manual_seed_all",
"torch.nn.DataParallel"
],
[
"torch.nn.Sequential",
"torch.nn.Softplus",
"torch.nn.ConvTranspose2d",
"torch.cat",
"torch.randn",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.Upsample",
"torch.nn.LeakyReLU",
"torch.nn.BatchNorm2d"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
s19282/PAD
|
[
"ca9fe4e199927db0a62314f7b8464f70c96aacd3"
] |
[
"cw05/z1_2_3.py"
] |
[
"import pandas as pd\n\ncustomers = pd.read_csv('customers.csv', delimiter=\",\")\norders = pd.read_csv('orders.csv', delimiter=\",\")\n# z1\nprint(orders.describe())\nprint(orders.info())\nprint(orders.head())\n# a\norders['order_date'] = pd.to_datetime(orders['order_date'], format='%Y/%m/%d')\n# b\nprint(orders['tshirt_category'].unique())\nprint(orders['tshirt_category'].unique().size)\n# c\norders['tshirt_category'] = orders['tshirt_category'].apply(lambda x: x.replace('Wh ', 'White '))\norders['tshirt_category'] = orders['tshirt_category'].apply(lambda x: x.replace('Bl ', 'Black '))\norders['tshirt_category'] = orders['tshirt_category'].apply(lambda x: x.replace('Tshirt ', 'T-Shirt '))\n\nprint(orders['tshirt_category'].unique())\n\n\n# d\ndef tshirt_type(type_):\n for el in type_:\n if el in ['T-Shirt', 'Hoodie', 'Tennis Shirt']:\n return el\n return 'No data'\n\n\ndef tshirt_size(size_):\n for el in size_:\n if el in ['M', 'F']:\n return el\n return 'No data'\n\n\ndef tshirt_colour(colour_):\n for el in colour_:\n if el in ['White', 'Black']:\n return el\n return 'No data'\n\n\norders['tshirt_type'] = orders['tshirt_category'].str.split().apply(lambda x: tshirt_type(x))\norders['tshirt_size'] = orders['tshirt_category'].str.split().apply(lambda x: tshirt_size(x))\norders['tshirt_colour'] = orders['tshirt_category'].str.split().apply(lambda x: tshirt_colour(x))\n# e\nprint(orders[orders.order_date.between('2014-12-31', '2016-08-02')])\n\n# z2\n\n# a\nprint(customers.info())\n# b\nprint(\"customers \", customers.shape, \"orders \", orders.shape)\n# c\ncustomers.rename(columns={'customerID': 'customer_id'}, inplace=True)\n# d\nresult = pd.merge(customers, orders, on='customer_id', how='inner')\n# Wybrałem metodę merge i inner join co spowoduje zignorowanie zamówień bez klienta i klientów którzy nic nie zamówili\n# z3\nresult.to_csv('out.csv', index=False)\n"
] |
[
[
"pandas.merge",
"pandas.read_csv",
"pandas.to_datetime"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
leozhoujf/scikit-plot
|
[
"2dd3e6a76df77edcbd724c4db25575f70abb57cb",
"2dd3e6a76df77edcbd724c4db25575f70abb57cb"
] |
[
"scikitplot/tests/test_decomposition.py",
"scikitplot/metrics.py"
] |
[
"from __future__ import absolute_import\nimport unittest\n\nfrom sklearn.datasets import load_iris as load_data\nfrom sklearn.decomposition import PCA\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom scikitplot.decomposition import plot_pca_component_variance\nfrom scikitplot.decomposition import plot_pca_2d_projection\n\n\nclass TestPlotPCAComponentVariance(unittest.TestCase):\n\n def setUp(self):\n np.random.seed(0)\n self.X, self.y = load_data(return_X_y=True)\n p = np.random.permutation(len(self.X))\n self.X, self.y = self.X[p], self.y[p]\n\n def tearDown(self):\n plt.close(\"all\")\n\n def test_target_explained_variance(self):\n np.random.seed(0)\n clf = PCA()\n clf.fit(self.X)\n plot_pca_component_variance(clf, target_explained_variance=0)\n plot_pca_component_variance(clf, target_explained_variance=0.5)\n plot_pca_component_variance(clf, target_explained_variance=1)\n plot_pca_component_variance(clf, target_explained_variance=1.5)\n\n def test_fitted(self):\n np.random.seed(0)\n clf = PCA()\n self.assertRaises(TypeError, plot_pca_component_variance, clf)\n\n def test_ax(self):\n np.random.seed(0)\n clf = PCA()\n clf.fit(self.X)\n fig, ax = plt.subplots(1, 1)\n out_ax = plot_pca_component_variance(clf)\n assert ax is not out_ax\n out_ax = plot_pca_component_variance(clf, ax=ax)\n assert ax is out_ax\n\n\nclass TestPlotPCA2DProjection(unittest.TestCase):\n\n def setUp(self):\n np.random.seed(0)\n self.X, self.y = load_data(return_X_y=True)\n p = np.random.permutation(len(self.X))\n self.X, self.y = self.X[p], self.y[p]\n\n def tearDown(self):\n plt.close(\"all\")\n\n def test_ax(self):\n np.random.seed(0)\n clf = PCA()\n clf.fit(self.X)\n fig, ax = plt.subplots(1, 1)\n out_ax = plot_pca_2d_projection(clf, self.X, self.y)\n assert ax is not out_ax\n out_ax = plot_pca_2d_projection(clf, self.X, self.y, ax=ax)\n assert ax is out_ax\n\n def test_cmap(self):\n np.random.seed(0)\n clf = PCA()\n clf.fit(self.X)\n plot_pca_2d_projection(clf, self.X, self.y, cmap='Spectral')\n plot_pca_2d_projection(clf, self.X, self.y, cmap=plt.cm.Spectral)\n\n def test_biplot(self):\n np.random.seed(0)\n clf = PCA()\n clf.fit(self.X)\n ax = plot_pca_2d_projection(clf, self.X, self.y, biplot=True,\n feature_labels=load_data().feature_names)\n",
"\"\"\"\nThe :mod:`scikitplot.metrics` module includes plots for machine learning\nevaluation metrics e.g. confusion matrix, silhouette scores, etc.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, \\\n unicode_literals\n\nimport itertools\n\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.preprocessing import label_binarize\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import auc\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import average_precision_score\nfrom sklearn.utils.multiclass import unique_labels\nfrom sklearn.metrics import silhouette_score\nfrom sklearn.metrics import silhouette_samples\nfrom sklearn.calibration import calibration_curve\nfrom sklearn.utils import deprecated\n\nfrom scipy import interp\n\nfrom scikitplot.helpers import binary_ks_curve, validate_labels\nfrom scikitplot.helpers import cumulative_gain_curve\n\n\ndef plot_confusion_matrix(y_true, y_pred, labels=None, true_labels=None,\n pred_labels=None, title=None, normalize=False,\n hide_zeros=False, hide_counts=False, x_tick_rotation=0, ax=None,\n figsize=None, cmap='Blues', title_fontsize=\"large\",\n text_fontsize=\"medium\"):\n \"\"\"Generates confusion matrix plot from predictions and true labels\n\n Args:\n y_true (array-like, shape (n_samples)):\n Ground truth (correct) target values.\n\n y_pred (array-like, shape (n_samples)):\n Estimated targets as returned by a classifier.\n\n labels (array-like, shape (n_classes), optional): List of labels to\n index the matrix. This may be used to reorder or select a subset\n of labels. If none is given, those that appear at least once in\n ``y_true`` or ``y_pred`` are used in sorted order. (new in v0.2.5)\n\n true_labels (array-like, optional): The true labels to display.\n If none is given, then all of the labels are used.\n\n pred_labels (array-like, optional): The predicted labels to display.\n If none is given, then all of the labels are used.\n\n title (string, optional): Title of the generated plot. Defaults to\n \"Confusion Matrix\" if `normalize` is True. Else, defaults to\n \"Normalized Confusion Matrix.\n\n normalize (bool, optional): If True, normalizes the confusion matrix\n before plotting. Defaults to False.\n\n hide_zeros (bool, optional): If True, does not plot cells containing a\n value of zero. Defaults to False.\n\n hide_counts (bool, optional): If True, doe not overlay counts.\n Defaults to False.\n\n x_tick_rotation (int, optional): Rotates x-axis tick labels by the\n specified angle. This is useful in cases where there are numerous\n categories and the labels overlap each other.\n\n ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to\n plot the curve. If None, the plot is drawn on a new set of axes.\n\n figsize (2-tuple, optional): Tuple denoting figure size of the plot\n e.g. (6, 6). Defaults to ``None``.\n\n cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):\n Colormap used for plotting the projection. View Matplotlib Colormap\n documentation for available options.\n https://matplotlib.org/users/colormaps.html\n\n title_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"large\".\n\n text_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"medium\".\n\n Returns:\n ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was\n drawn.\n\n Example:\n >>> import scikitplot as skplt\n >>> rf = RandomForestClassifier()\n >>> rf = rf.fit(X_train, y_train)\n >>> y_pred = rf.predict(X_test)\n >>> skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n <matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>\n >>> plt.show()\n\n .. image:: _static/examples/plot_confusion_matrix.png\n :align: center\n :alt: Confusion matrix\n \"\"\"\n y_true = np.asarray(y_true)\n y_pred = np.asarray(y_pred)\n\n if ax is None:\n fig, ax = plt.subplots(1, 1, figsize=figsize)\n\n cm = confusion_matrix(y_true, y_pred, labels=labels)\n if labels is None:\n classes = unique_labels(y_true, y_pred)\n else:\n classes = np.asarray(labels)\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n cm = np.around(cm, decimals=2)\n cm[np.isnan(cm)] = 0.0\n\n if true_labels is None:\n true_classes = classes\n else:\n validate_labels(classes, true_labels, \"true_labels\")\n\n true_label_indexes = np.in1d(classes, true_labels)\n\n true_classes = classes[true_label_indexes]\n cm = cm[true_label_indexes]\n\n if pred_labels is None:\n pred_classes = classes\n else:\n validate_labels(classes, pred_labels, \"pred_labels\")\n\n pred_label_indexes = np.in1d(classes, pred_labels)\n\n pred_classes = classes[pred_label_indexes]\n cm = cm[:, pred_label_indexes]\n\n if title:\n ax.set_title(title, fontsize=title_fontsize)\n elif normalize:\n ax.set_title('Normalized Confusion Matrix', fontsize=title_fontsize)\n else:\n ax.set_title('Confusion Matrix', fontsize=title_fontsize)\n\n image = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.get_cmap(cmap))\n plt.colorbar(mappable=image)\n x_tick_marks = np.arange(len(pred_classes))\n y_tick_marks = np.arange(len(true_classes))\n ax.set_xticks(x_tick_marks)\n ax.set_xticklabels(pred_classes, fontsize=text_fontsize,\n rotation=x_tick_rotation)\n ax.set_yticks(y_tick_marks)\n ax.set_yticklabels(true_classes, fontsize=text_fontsize)\n\n thresh = cm.max() / 2.\n\n if not hide_counts:\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n if not (hide_zeros and cm[i, j] == 0):\n ax.text(j, i, cm[i, j],\n horizontalalignment=\"center\",\n verticalalignment=\"center\",\n fontsize=text_fontsize,\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n ax.set_ylabel('True label', fontsize=text_fontsize)\n ax.set_xlabel('Predicted label', fontsize=text_fontsize)\n ax.grid(False)\n\n return ax\n\n\n@deprecated('This will be removed in v0.5.0. Please use '\n 'scikitplot.metrics.plot_roc instead.')\ndef plot_roc_curve(y_true, y_probas, title='ROC Curves',\n curves=('micro', 'macro', 'each_class'),\n ax=None, figsize=None, cmap='nipy_spectral',\n title_fontsize=\"large\", text_fontsize=\"medium\"):\n \"\"\"Generates the ROC curves from labels and predicted scores/probabilities\n\n Args:\n y_true (array-like, shape (n_samples)):\n Ground truth (correct) target values.\n\n y_probas (array-like, shape (n_samples, n_classes)):\n Prediction probabilities for each class returned by a classifier.\n\n title (string, optional): Title of the generated plot. Defaults to\n \"ROC Curves\".\n\n curves (array-like): A listing of which curves should be plotted on the\n resulting plot. Defaults to `(\"micro\", \"macro\", \"each_class\")`\n i.e. \"micro\" for micro-averaged curve, \"macro\" for macro-averaged\n curve\n\n ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to\n plot the curve. If None, the plot is drawn on a new set of axes.\n\n figsize (2-tuple, optional): Tuple denoting figure size of the plot\n e.g. (6, 6). Defaults to ``None``.\n\n cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):\n Colormap used for plotting the projection. View Matplotlib Colormap\n documentation for available options.\n https://matplotlib.org/users/colormaps.html\n\n title_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"large\".\n\n text_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"medium\".\n\n Returns:\n ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was\n drawn.\n\n Example:\n >>> import scikitplot as skplt\n >>> nb = GaussianNB()\n >>> nb = nb.fit(X_train, y_train)\n >>> y_probas = nb.predict_proba(X_test)\n >>> skplt.metrics.plot_roc_curve(y_test, y_probas)\n <matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>\n >>> plt.show()\n\n .. image:: _static/examples/plot_roc_curve.png\n :align: center\n :alt: ROC Curves\n \"\"\"\n y_true = np.array(y_true)\n y_probas = np.array(y_probas)\n\n if 'micro' not in curves and 'macro' not in curves and \\\n 'each_class' not in curves:\n raise ValueError('Invalid argument for curves as it '\n 'only takes \"micro\", \"macro\", or \"each_class\"')\n\n classes = np.unique(y_true)\n probas = y_probas\n\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n for i in range(len(classes)):\n fpr[i], tpr[i], _ = roc_curve(y_true, probas[:, i],\n pos_label=classes[i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n # Compute micro-average ROC curve and ROC area\n micro_key = 'micro'\n i = 0\n while micro_key in fpr:\n i += 1\n micro_key += str(i)\n\n y_true = label_binarize(y_true, classes=classes)\n if len(classes) == 2:\n y_true = np.hstack((1 - y_true, y_true))\n\n fpr[micro_key], tpr[micro_key], _ = roc_curve(y_true.ravel(),\n probas.ravel())\n roc_auc[micro_key] = auc(fpr[micro_key], tpr[micro_key])\n\n # Compute macro-average ROC curve and ROC area\n\n # First aggregate all false positive rates\n all_fpr = np.unique(np.concatenate([fpr[x] for x in range(len(classes))]))\n\n # Then interpolate all ROC curves at this points\n mean_tpr = np.zeros_like(all_fpr)\n for i in range(len(classes)):\n mean_tpr += interp(all_fpr, fpr[i], tpr[i])\n\n # Finally average it and compute AUC\n mean_tpr /= len(classes)\n\n macro_key = 'macro'\n i = 0\n while macro_key in fpr:\n i += 1\n macro_key += str(i)\n fpr[macro_key] = all_fpr\n tpr[macro_key] = mean_tpr\n roc_auc[macro_key] = auc(fpr[macro_key], tpr[macro_key])\n\n if ax is None:\n fig, ax = plt.subplots(1, 1, figsize=figsize)\n\n ax.set_title(title, fontsize=title_fontsize)\n\n if 'each_class' in curves:\n for i in range(len(classes)):\n color = plt.cm.get_cmap(cmap)(float(i) / len(classes))\n ax.plot(fpr[i], tpr[i], lw=2, color=color,\n label='ROC curve of class {0} (area = {1:0.2f})'\n ''.format(classes[i], roc_auc[i]))\n\n if 'micro' in curves:\n ax.plot(fpr[micro_key], tpr[micro_key],\n label='micro-average ROC curve '\n '(area = {0:0.2f})'.format(roc_auc[micro_key]),\n color='deeppink', linestyle=':', linewidth=4)\n\n if 'macro' in curves:\n ax.plot(fpr[macro_key], tpr[macro_key],\n label='macro-average ROC curve '\n '(area = {0:0.2f})'.format(roc_auc[macro_key]),\n color='navy', linestyle=':', linewidth=4)\n\n ax.plot([0, 1], [0, 1], 'k--', lw=2)\n ax.set_xlim([0.0, 1.0])\n ax.set_ylim([0.0, 1.05])\n ax.set_xlabel('False Positive Rate', fontsize=text_fontsize)\n ax.set_ylabel('True Positive Rate', fontsize=text_fontsize)\n ax.tick_params(labelsize=text_fontsize)\n ax.legend(loc='lower right', fontsize=text_fontsize)\n return ax\n\n\ndef plot_roc(y_true, y_probas, title='ROC Curves',\n plot_micro=True, plot_macro=True, classes_to_plot=None,\n ax=None, figsize=None, cmap='nipy_spectral',\n title_fontsize=\"large\", text_fontsize=\"medium\"):\n \"\"\"Generates the ROC curves from labels and predicted scores/probabilities\n\n Args:\n y_true (array-like, shape (n_samples)):\n Ground truth (correct) target values.\n\n y_probas (array-like, shape (n_samples, n_classes)):\n Prediction probabilities for each class returned by a classifier.\n\n title (string, optional): Title of the generated plot. Defaults to\n \"ROC Curves\".\n\n plot_micro (boolean, optional): Plot the micro average ROC curve.\n Defaults to ``True``.\n\n plot_macro (boolean, optional): Plot the macro average ROC curve.\n Defaults to ``True``.\n\n classes_to_plot (list-like, optional): Classes for which the ROC\n curve should be plotted. e.g. [0, 'cold']. If given class does not exist,\n it will be ignored. If ``None``, all classes will be plotted. Defaults to\n ``None``\n\n ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to\n plot the curve. If None, the plot is drawn on a new set of axes.\n\n figsize (2-tuple, optional): Tuple denoting figure size of the plot\n e.g. (6, 6). Defaults to ``None``.\n\n cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):\n Colormap used for plotting the projection. View Matplotlib Colormap\n documentation for available options.\n https://matplotlib.org/users/colormaps.html\n\n title_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"large\".\n\n text_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"medium\".\n\n Returns:\n ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was\n drawn.\n\n Example:\n >>> import scikitplot as skplt\n >>> nb = GaussianNB()\n >>> nb = nb.fit(X_train, y_train)\n >>> y_probas = nb.predict_proba(X_test)\n >>> skplt.metrics.plot_roc(y_test, y_probas)\n <matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>\n >>> plt.show()\n\n .. image:: _static/examples/plot_roc_curve.png\n :align: center\n :alt: ROC Curves\n \"\"\"\n y_true = np.array(y_true)\n y_probas = np.array(y_probas)\n\n classes = np.unique(y_true)\n probas = y_probas\n\n if classes_to_plot is None:\n classes_to_plot = classes\n\n if ax is None:\n fig, ax = plt.subplots(1, 1, figsize=figsize)\n\n ax.set_title(title, fontsize=title_fontsize)\n\n fpr_dict = dict()\n tpr_dict = dict()\n\n indices_to_plot = np.in1d(classes, classes_to_plot)\n for i, to_plot in enumerate(indices_to_plot):\n fpr_dict[i], tpr_dict[i], _ = roc_curve(y_true, probas[:, i],\n pos_label=classes[i])\n if to_plot:\n roc_auc = auc(fpr_dict[i], tpr_dict[i])\n color = plt.cm.get_cmap(cmap)(float(i) / len(classes))\n ax.plot(fpr_dict[i], tpr_dict[i], lw=2, color=color,\n label='ROC curve of class {0} (area = {1:0.2f})'\n ''.format(classes[i], roc_auc))\n\n if plot_micro:\n binarized_y_true = label_binarize(y_true, classes=classes)\n if len(classes) == 2:\n binarized_y_true = np.hstack(\n (1 - binarized_y_true, binarized_y_true))\n fpr, tpr, _ = roc_curve(binarized_y_true.ravel(), probas.ravel())\n roc_auc = auc(fpr, tpr)\n ax.plot(fpr, tpr,\n label='micro-average ROC curve '\n '(area = {0:0.2f})'.format(roc_auc),\n color='deeppink', linestyle=':', linewidth=4)\n\n if plot_macro:\n # Compute macro-average ROC curve and ROC area\n # First aggregate all false positive rates\n all_fpr = np.unique(np.concatenate([fpr_dict[x] for x in range(len(classes))]))\n\n # Then interpolate all ROC curves at this points\n mean_tpr = np.zeros_like(all_fpr)\n for i in range(len(classes)):\n mean_tpr += interp(all_fpr, fpr_dict[i], tpr_dict[i])\n\n # Finally average it and compute AUC\n mean_tpr /= len(classes)\n roc_auc = auc(all_fpr, mean_tpr)\n\n ax.plot(all_fpr, mean_tpr,\n label='macro-average ROC curve '\n '(area = {0:0.2f})'.format(roc_auc),\n color='navy', linestyle=':', linewidth=4)\n\n ax.plot([0, 1], [0, 1], 'k--', lw=2)\n ax.set_xlim([0.0, 1.0])\n ax.set_ylim([0.0, 1.05])\n ax.set_xlabel('False Positive Rate', fontsize=text_fontsize)\n ax.set_ylabel('True Positive Rate', fontsize=text_fontsize)\n ax.tick_params(labelsize=text_fontsize)\n ax.legend(loc='lower right', fontsize=text_fontsize)\n return ax\n\n\ndef plot_ks_statistic(y_true, y_probas, title='KS Statistic Plot',\n ax=None, figsize=None, title_fontsize=\"large\",\n text_fontsize=\"medium\"):\n \"\"\"Generates the KS Statistic plot from labels and scores/probabilities\n\n Args:\n y_true (array-like, shape (n_samples)):\n Ground truth (correct) target values.\n\n y_probas (array-like, shape (n_samples, n_classes)):\n Prediction probabilities for each class returned by a classifier.\n\n title (string, optional): Title of the generated plot. Defaults to\n \"KS Statistic Plot\".\n\n ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to\n plot the learning curve. If None, the plot is drawn on a new set of\n axes.\n\n figsize (2-tuple, optional): Tuple denoting figure size of the plot\n e.g. (6, 6). Defaults to ``None``.\n\n title_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"large\".\n\n text_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"medium\".\n\n Returns:\n ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was\n drawn.\n\n Example:\n >>> import scikitplot as skplt\n >>> lr = LogisticRegression()\n >>> lr = lr.fit(X_train, y_train)\n >>> y_probas = lr.predict_proba(X_test)\n >>> skplt.metrics.plot_ks_statistic(y_test, y_probas)\n <matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>\n >>> plt.show()\n\n .. image:: _static/examples/plot_ks_statistic.png\n :align: center\n :alt: KS Statistic\n \"\"\"\n y_true = np.array(y_true)\n y_probas = np.array(y_probas)\n\n classes = np.unique(y_true)\n if len(classes) != 2:\n raise ValueError('Cannot calculate KS statistic for data with '\n '{} category/ies'.format(len(classes)))\n probas = y_probas\n\n # Compute KS Statistic curves\n thresholds, pct1, pct2, ks_statistic, \\\n max_distance_at, classes = binary_ks_curve(y_true,\n probas[:, 1].ravel())\n\n if ax is None:\n fig, ax = plt.subplots(1, 1, figsize=figsize)\n\n ax.set_title(title, fontsize=title_fontsize)\n\n ax.plot(thresholds, pct1, lw=3, label='Class {}'.format(classes[0]))\n ax.plot(thresholds, pct2, lw=3, label='Class {}'.format(classes[1]))\n idx = np.where(thresholds == max_distance_at)[0][0]\n ax.axvline(max_distance_at, *sorted([pct1[idx], pct2[idx]]),\n label='KS Statistic: {:.3f} at {:.3f}'.format(ks_statistic,\n max_distance_at),\n linestyle=':', lw=3, color='black')\n\n ax.set_xlim([0.0, 1.0])\n ax.set_ylim([0.0, 1.0])\n\n ax.set_xlabel('Threshold', fontsize=text_fontsize)\n ax.set_ylabel('Percentage below threshold', fontsize=text_fontsize)\n ax.tick_params(labelsize=text_fontsize)\n ax.legend(loc='lower right', fontsize=text_fontsize)\n\n return ax\n\n\n@deprecated('This will be removed in v0.5.0. Please use '\n 'scikitplot.metrics.plot_precision_recall instead.')\ndef plot_precision_recall_curve(y_true, y_probas,\n title='Precision-Recall Curve',\n curves=('micro', 'each_class'), ax=None,\n figsize=None, cmap='nipy_spectral',\n title_fontsize=\"large\",\n text_fontsize=\"medium\"):\n \"\"\"Generates the Precision Recall Curve from labels and probabilities\n\n Args:\n y_true (array-like, shape (n_samples)):\n Ground truth (correct) target values.\n\n y_probas (array-like, shape (n_samples, n_classes)):\n Prediction probabilities for each class returned by a classifier.\n\n title (string, optional): Title of the generated plot. Defaults to\n \"Precision-Recall curve\".\n\n curves (array-like): A listing of which curves should be plotted on the\n resulting plot. Defaults to `(\"micro\", \"each_class\")`\n i.e. \"micro\" for micro-averaged curve\n\n ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to\n plot the curve. If None, the plot is drawn on a new set of axes.\n\n figsize (2-tuple, optional): Tuple denoting figure size of the plot\n e.g. (6, 6). Defaults to ``None``.\n\n cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):\n Colormap used for plotting the projection. View Matplotlib Colormap\n documentation for available options.\n https://matplotlib.org/users/colormaps.html\n\n title_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"large\".\n\n text_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"medium\".\n\n Returns:\n ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was\n drawn.\n\n Example:\n >>> import scikitplot as skplt\n >>> nb = GaussianNB()\n >>> nb.fit(X_train, y_train)\n >>> y_probas = nb.predict_proba(X_test)\n >>> skplt.metrics.plot_precision_recall_curve(y_test, y_probas)\n <matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>\n >>> plt.show()\n\n .. image:: _static/examples/plot_precision_recall_curve.png\n :align: center\n :alt: Precision Recall Curve\n \"\"\"\n y_true = np.array(y_true)\n y_probas = np.array(y_probas)\n\n classes = np.unique(y_true)\n probas = y_probas\n\n if 'micro' not in curves and 'each_class' not in curves:\n raise ValueError('Invalid argument for curves as it '\n 'only takes \"micro\" or \"each_class\"')\n\n # Compute Precision-Recall curve and area for each class\n precision = dict()\n recall = dict()\n average_precision = dict()\n for i in range(len(classes)):\n precision[i], recall[i], _ = precision_recall_curve(\n y_true, probas[:, i], pos_label=classes[i])\n\n y_true = label_binarize(y_true, classes=classes)\n if len(classes) == 2:\n y_true = np.hstack((1 - y_true, y_true))\n\n for i in range(len(classes)):\n average_precision[i] = average_precision_score(y_true[:, i],\n probas[:, i])\n\n # Compute micro-average ROC curve and ROC area\n micro_key = 'micro'\n i = 0\n while micro_key in precision:\n i += 1\n micro_key += str(i)\n\n precision[micro_key], recall[micro_key], _ = precision_recall_curve(\n y_true.ravel(), probas.ravel())\n average_precision[micro_key] = average_precision_score(y_true, probas,\n average='micro')\n\n if ax is None:\n fig, ax = plt.subplots(1, 1, figsize=figsize)\n\n ax.set_title(title, fontsize=title_fontsize)\n\n if 'each_class' in curves:\n for i in range(len(classes)):\n color = plt.cm.get_cmap(cmap)(float(i) / len(classes))\n ax.plot(recall[i], precision[i], lw=2,\n label='Precision-recall curve of class {0} '\n '(area = {1:0.3f})'.format(classes[i],\n average_precision[i]),\n color=color)\n\n if 'micro' in curves:\n ax.plot(recall[micro_key], precision[micro_key],\n label='micro-average Precision-recall curve '\n '(area = {0:0.3f})'.format(average_precision[micro_key]),\n color='navy', linestyle=':', linewidth=4)\n\n ax.set_xlim([0.0, 1.0])\n ax.set_ylim([0.0, 1.05])\n ax.set_xlabel('Recall')\n ax.set_ylabel('Precision')\n ax.tick_params(labelsize=text_fontsize)\n ax.legend(loc='best', fontsize=text_fontsize)\n return ax\n\n\ndef plot_precision_recall(y_true, y_probas,\n title='Precision-Recall Curve',\n plot_micro=True,\n classes_to_plot=None, ax=None,\n figsize=None, cmap='nipy_spectral',\n title_fontsize=\"large\",\n text_fontsize=\"medium\"):\n \"\"\"Generates the Precision Recall Curve from labels and probabilities\n\n Args:\n y_true (array-like, shape (n_samples)):\n Ground truth (correct) target values.\n\n y_probas (array-like, shape (n_samples, n_classes)):\n Prediction probabilities for each class returned by a classifier.\n\n title (string, optional): Title of the generated plot. Defaults to\n \"Precision-Recall curve\".\n\n plot_micro (boolean, optional): Plot the micro average ROC curve.\n Defaults to ``True``.\n\n classes_to_plot (list-like, optional): Classes for which the precision-recall\n curve should be plotted. e.g. [0, 'cold']. If given class does not exist,\n it will be ignored. If ``None``, all classes will be plotted. Defaults to\n ``None``.\n\n ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to\n plot the curve. If None, the plot is drawn on a new set of axes.\n\n figsize (2-tuple, optional): Tuple denoting figure size of the plot\n e.g. (6, 6). Defaults to ``None``.\n\n cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):\n Colormap used for plotting the projection. View Matplotlib Colormap\n documentation for available options.\n https://matplotlib.org/users/colormaps.html\n\n title_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"large\".\n\n text_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"medium\".\n\n Returns:\n ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was\n drawn.\n\n Example:\n >>> import scikitplot as skplt\n >>> nb = GaussianNB()\n >>> nb.fit(X_train, y_train)\n >>> y_probas = nb.predict_proba(X_test)\n >>> skplt.metrics.plot_precision_recall(y_test, y_probas)\n <matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>\n >>> plt.show()\n\n .. image:: _static/examples/plot_precision_recall_curve.png\n :align: center\n :alt: Precision Recall Curve\n \"\"\"\n y_true = np.array(y_true)\n y_probas = np.array(y_probas)\n\n classes = np.unique(y_true)\n probas = y_probas\n\n if classes_to_plot is None:\n classes_to_plot = classes\n\n binarized_y_true = label_binarize(y_true, classes=classes)\n if len(classes) == 2:\n binarized_y_true = np.hstack(\n (1 - binarized_y_true, binarized_y_true))\n\n if ax is None:\n fig, ax = plt.subplots(1, 1, figsize=figsize)\n\n ax.set_title(title, fontsize=title_fontsize)\n\n indices_to_plot = np.in1d(classes, classes_to_plot)\n for i, to_plot in enumerate(indices_to_plot):\n if to_plot:\n average_precision = average_precision_score(\n binarized_y_true[:, i],\n probas[:, i])\n precision, recall, _ = precision_recall_curve(\n y_true, probas[:, i], pos_label=classes[i])\n color = plt.cm.get_cmap(cmap)(float(i) / len(classes))\n ax.plot(recall, precision, lw=2,\n label='Precision-recall curve of class {0} '\n '(area = {1:0.3f})'.format(classes[i],\n average_precision),\n color=color)\n\n if plot_micro:\n precision, recall, _ = precision_recall_curve(\n binarized_y_true.ravel(), probas.ravel())\n average_precision = average_precision_score(binarized_y_true,\n probas,\n average='micro')\n ax.plot(recall, precision,\n label='micro-average Precision-recall curve '\n '(area = {0:0.3f})'.format(average_precision),\n color='navy', linestyle=':', linewidth=4)\n\n ax.set_xlim([0.0, 1.0])\n ax.set_ylim([0.0, 1.05])\n ax.set_xlabel('Recall')\n ax.set_ylabel('Precision')\n ax.tick_params(labelsize=text_fontsize)\n ax.legend(loc='best', fontsize=text_fontsize)\n return ax\n\n\ndef plot_silhouette(X, cluster_labels, title='Silhouette Analysis',\n metric='euclidean', copy=True, ax=None, figsize=None,\n cmap='nipy_spectral', title_fontsize=\"large\",\n text_fontsize=\"medium\"):\n \"\"\"Plots silhouette analysis of clusters provided.\n\n Args:\n X (array-like, shape (n_samples, n_features)):\n Data to cluster, where n_samples is the number of samples and\n n_features is the number of features.\n\n cluster_labels (array-like, shape (n_samples,)):\n Cluster label for each sample.\n\n title (string, optional): Title of the generated plot. Defaults to\n \"Silhouette Analysis\"\n\n metric (string or callable, optional): The metric to use when\n calculating distance between instances in a feature array.\n If metric is a string, it must be one of the options allowed by\n sklearn.metrics.pairwise.pairwise_distances. If X is\n the distance array itself, use \"precomputed\" as the metric.\n\n copy (boolean, optional): Determines whether ``fit`` is used on\n **clf** or on a copy of **clf**.\n\n ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to\n plot the curve. If None, the plot is drawn on a new set of axes.\n\n figsize (2-tuple, optional): Tuple denoting figure size of the plot\n e.g. (6, 6). Defaults to ``None``.\n\n cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):\n Colormap used for plotting the projection. View Matplotlib Colormap\n documentation for available options.\n https://matplotlib.org/users/colormaps.html\n\n title_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"large\".\n\n text_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"medium\".\n\n Returns:\n ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was\n drawn.\n\n Example:\n >>> import scikitplot as skplt\n >>> kmeans = KMeans(n_clusters=4, random_state=1)\n >>> cluster_labels = kmeans.fit_predict(X)\n >>> skplt.metrics.plot_silhouette(X, cluster_labels)\n <matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>\n >>> plt.show()\n\n .. image:: _static/examples/plot_silhouette.png\n :align: center\n :alt: Silhouette Plot\n \"\"\"\n cluster_labels = np.asarray(cluster_labels)\n\n le = LabelEncoder()\n cluster_labels_encoded = le.fit_transform(cluster_labels)\n\n n_clusters = len(np.unique(cluster_labels))\n\n silhouette_avg = silhouette_score(X, cluster_labels, metric=metric)\n\n sample_silhouette_values = silhouette_samples(X, cluster_labels,\n metric=metric)\n\n if ax is None:\n fig, ax = plt.subplots(1, 1, figsize=figsize)\n\n ax.set_title(title, fontsize=title_fontsize)\n ax.set_xlim([-0.1, 1])\n\n ax.set_ylim([0, len(X) + (n_clusters + 1) * 10 + 10])\n\n ax.set_xlabel('Silhouette coefficient values', fontsize=text_fontsize)\n ax.set_ylabel('Cluster label', fontsize=text_fontsize)\n\n y_lower = 10\n\n for i in range(n_clusters):\n ith_cluster_silhouette_values = sample_silhouette_values[\n cluster_labels_encoded == i]\n\n ith_cluster_silhouette_values.sort()\n\n size_cluster_i = ith_cluster_silhouette_values.shape[0]\n y_upper = y_lower + size_cluster_i\n\n color = plt.cm.get_cmap(cmap)(float(i) / n_clusters)\n\n ax.fill_betweenx(np.arange(y_lower, y_upper),\n 0, ith_cluster_silhouette_values,\n facecolor=color, edgecolor=color, alpha=0.7)\n\n ax.text(-0.05, y_lower + 0.5 * size_cluster_i, str(le.classes_[i]),\n fontsize=text_fontsize)\n\n y_lower = y_upper + 10\n\n ax.axvline(x=silhouette_avg, color=\"red\", linestyle=\"--\",\n label='Silhouette score: {0:0.3f}'.format(silhouette_avg))\n\n ax.set_yticks([]) # Clear the y-axis labels / ticks\n ax.set_xticks(np.arange(-0.1, 1.0, 0.2))\n\n ax.tick_params(labelsize=text_fontsize)\n ax.legend(loc='best', fontsize=text_fontsize)\n\n return ax\n\n\ndef plot_calibration_curve(y_true, probas_list, clf_names=None, n_bins=10,\n title='Calibration plots (Reliability Curves)',\n ax=None, figsize=None, cmap='nipy_spectral',\n title_fontsize=\"large\", text_fontsize=\"medium\"):\n \"\"\"Plots calibration curves for a set of classifier probability estimates.\n\n Plotting the calibration curves of a classifier is useful for determining\n whether or not you can interpret their predicted probabilities directly as\n as confidence level. For instance, a well-calibrated binary classifier\n should classify the samples such that for samples to which it gave a score\n of 0.8, around 80% should actually be from the positive class.\n\n This function currently only works for binary classification.\n\n Args:\n y_true (array-like, shape (n_samples)):\n Ground truth (correct) target values.\n\n probas_list (list of array-like, shape (n_samples, 2) or (n_samples,)):\n A list containing the outputs of binary classifiers'\n :func:`predict_proba` method or :func:`decision_function` method.\n\n clf_names (list of str, optional): A list of strings, where each string\n refers to the name of the classifier that produced the\n corresponding probability estimates in `probas_list`. If ``None``,\n the names \"Classifier 1\", \"Classifier 2\", etc. will be used.\n\n n_bins (int, optional): Number of bins. A bigger number requires more\n data.\n\n title (string, optional): Title of the generated plot. Defaults to\n \"Calibration plots (Reliabilirt Curves)\"\n\n ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to\n plot the curve. If None, the plot is drawn on a new set of axes.\n\n figsize (2-tuple, optional): Tuple denoting figure size of the plot\n e.g. (6, 6). Defaults to ``None``.\n\n cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):\n Colormap used for plotting the projection. View Matplotlib Colormap\n documentation for available options.\n https://matplotlib.org/users/colormaps.html\n\n title_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"large\".\n\n text_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"medium\".\n\n Returns:\n :class:`matplotlib.axes.Axes`: The axes on which the plot was drawn.\n\n Example:\n >>> import scikitplot as skplt\n >>> rf = RandomForestClassifier()\n >>> lr = LogisticRegression()\n >>> nb = GaussianNB()\n >>> svm = LinearSVC()\n >>> rf_probas = rf.fit(X_train, y_train).predict_proba(X_test)\n >>> lr_probas = lr.fit(X_train, y_train).predict_proba(X_test)\n >>> nb_probas = nb.fit(X_train, y_train).predict_proba(X_test)\n >>> svm_scores = svm.fit(X_train, y_train).decision_function(X_test)\n >>> probas_list = [rf_probas, lr_probas, nb_probas, svm_scores]\n >>> clf_names = ['Random Forest', 'Logistic Regression',\n ... 'Gaussian Naive Bayes', 'Support Vector Machine']\n >>> skplt.metrics.plot_calibration_curve(y_test,\n ... probas_list,\n ... clf_names)\n <matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>\n >>> plt.show()\n\n .. image:: _static/examples/plot_calibration_curve.png\n :align: center\n :alt: Calibration Curves\n \"\"\"\n y_true = np.asarray(y_true)\n if not isinstance(probas_list, list):\n raise ValueError('`probas_list` does not contain a list.')\n\n classes = np.unique(y_true)\n if len(classes) > 2:\n raise ValueError('plot_calibration_curve only '\n 'works for binary classification')\n\n if clf_names is None:\n clf_names = ['Classifier {}'.format(x+1)\n for x in range(len(probas_list))]\n\n if len(clf_names) != len(probas_list):\n raise ValueError('Length {} of `clf_names` does not match length {} of'\n ' `probas_list`'.format(len(clf_names),\n len(probas_list)))\n\n if ax is None:\n fig, ax = plt.subplots(1, 1, figsize=figsize)\n\n ax.plot([0, 1], [0, 1], \"k:\", label=\"Perfectly calibrated\")\n\n for i, probas in enumerate(probas_list):\n probas = np.asarray(probas)\n if probas.ndim > 2:\n raise ValueError('Index {} in probas_list has invalid '\n 'shape {}'.format(i, probas.shape))\n if probas.ndim == 2:\n probas = probas[:, 1]\n\n if probas.shape != y_true.shape:\n raise ValueError('Index {} in probas_list has invalid '\n 'shape {}'.format(i, probas.shape))\n\n probas = (probas - probas.min()) / (probas.max() - probas.min())\n\n fraction_of_positives, mean_predicted_value = \\\n calibration_curve(y_true, probas, n_bins=n_bins)\n\n color = plt.cm.get_cmap(cmap)(float(i) / len(probas_list))\n\n ax.plot(mean_predicted_value, fraction_of_positives, 's-',\n label=clf_names[i], color=color)\n\n ax.set_title(title, fontsize=title_fontsize)\n\n ax.set_xlabel('Mean predicted value', fontsize=text_fontsize)\n ax.set_ylabel('Fraction of positives', fontsize=text_fontsize)\n\n ax.set_ylim([-0.05, 1.05])\n ax.legend(loc='lower right')\n\n return ax\n\n\ndef plot_cumulative_gain(y_true, y_probas, title='Cumulative Gains Curve',\n ax=None, figsize=None, title_fontsize=\"large\",\n text_fontsize=\"medium\"):\n \"\"\"Generates the Cumulative Gains Plot from labels and scores/probabilities\n\n The cumulative gains chart is used to determine the effectiveness of a\n binary classifier. A detailed explanation can be found at\n http://mlwiki.org/index.php/Cumulative_Gain_Chart. The implementation\n here works only for binary classification.\n\n Args:\n y_true (array-like, shape (n_samples)):\n Ground truth (correct) target values.\n\n y_probas (array-like, shape (n_samples, n_classes)):\n Prediction probabilities for each class returned by a classifier.\n\n title (string, optional): Title of the generated plot. Defaults to\n \"Cumulative Gains Curve\".\n\n ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to\n plot the learning curve. If None, the plot is drawn on a new set of\n axes.\n\n figsize (2-tuple, optional): Tuple denoting figure size of the plot\n e.g. (6, 6). Defaults to ``None``.\n\n title_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"large\".\n\n text_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"medium\".\n\n Returns:\n ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was\n drawn.\n\n Example:\n >>> import scikitplot as skplt\n >>> lr = LogisticRegression()\n >>> lr = lr.fit(X_train, y_train)\n >>> y_probas = lr.predict_proba(X_test)\n >>> skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n <matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>\n >>> plt.show()\n\n .. image:: _static/examples/plot_cumulative_gain.png\n :align: center\n :alt: Cumulative Gains Plot\n \"\"\"\n y_true = np.array(y_true)\n y_probas = np.array(y_probas)\n\n classes = np.unique(y_true)\n if len(classes) != 2:\n raise ValueError('Cannot calculate Cumulative Gains for data with '\n '{} category/ies'.format(len(classes)))\n\n # Compute Cumulative Gain Curves\n percentages, gains1 = cumulative_gain_curve(y_true, y_probas[:, 0],\n classes[0])\n percentages, gains2 = cumulative_gain_curve(y_true, y_probas[:, 1],\n classes[1])\n\n if ax is None:\n fig, ax = plt.subplots(1, 1, figsize=figsize)\n\n ax.set_title(title, fontsize=title_fontsize)\n\n ax.plot(percentages, gains1, lw=3, label='Class {}'.format(classes[0]))\n ax.plot(percentages, gains2, lw=3, label='Class {}'.format(classes[1]))\n\n ax.set_xlim([0.0, 1.0])\n ax.set_ylim([0.0, 1.0])\n\n ax.plot([0, 1], [0, 1], 'k--', lw=2, label='Baseline')\n\n ax.set_xlabel('Percentage of sample', fontsize=text_fontsize)\n ax.set_ylabel('Gain', fontsize=text_fontsize)\n ax.tick_params(labelsize=text_fontsize)\n ax.grid('on')\n ax.legend(loc='lower right', fontsize=text_fontsize)\n\n return ax\n\n\ndef plot_lift_curve(y_true, y_probas, title='Lift Curve',\n ax=None, figsize=None, title_fontsize=\"large\",\n text_fontsize=\"medium\"):\n \"\"\"Generates the Lift Curve from labels and scores/probabilities\n\n The lift curve is used to determine the effectiveness of a\n binary classifier. A detailed explanation can be found at\n http://www2.cs.uregina.ca/~dbd/cs831/notes/lift_chart/lift_chart.html.\n The implementation here works only for binary classification.\n\n Args:\n y_true (array-like, shape (n_samples)):\n Ground truth (correct) target values.\n\n y_probas (array-like, shape (n_samples, n_classes)):\n Prediction probabilities for each class returned by a classifier.\n\n title (string, optional): Title of the generated plot. Defaults to\n \"Lift Curve\".\n\n ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to\n plot the learning curve. If None, the plot is drawn on a new set of\n axes.\n\n figsize (2-tuple, optional): Tuple denoting figure size of the plot\n e.g. (6, 6). Defaults to ``None``.\n\n title_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"large\".\n\n text_fontsize (string or int, optional): Matplotlib-style fontsizes.\n Use e.g. \"small\", \"medium\", \"large\" or integer-values. Defaults to\n \"medium\".\n\n Returns:\n ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was\n drawn.\n\n Example:\n >>> import scikitplot as skplt\n >>> lr = LogisticRegression()\n >>> lr = lr.fit(X_train, y_train)\n >>> y_probas = lr.predict_proba(X_test)\n >>> skplt.metrics.plot_lift_curve(y_test, y_probas)\n <matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>\n >>> plt.show()\n\n .. image:: _static/examples/plot_lift_curve.png\n :align: center\n :alt: Lift Curve\n \"\"\"\n y_true = np.array(y_true)\n y_probas = np.array(y_probas)\n\n classes = np.unique(y_true)\n if len(classes) != 2:\n raise ValueError('Cannot calculate Lift Curve for data with '\n '{} category/ies'.format(len(classes)))\n\n # Compute Cumulative Gain Curves\n percentages, gains1 = cumulative_gain_curve(y_true, y_probas[:, 0],\n classes[0])\n percentages, gains2 = cumulative_gain_curve(y_true, y_probas[:, 1],\n classes[1])\n\n percentages = percentages[1:]\n gains1 = gains1[1:]\n gains2 = gains2[1:]\n\n gains1 = gains1 / percentages\n gains2 = gains2 / percentages\n\n if ax is None:\n fig, ax = plt.subplots(1, 1, figsize=figsize)\n\n ax.set_title(title, fontsize=title_fontsize)\n\n ax.plot(percentages, gains1, lw=3, label='Class {}'.format(classes[0]))\n ax.plot(percentages, gains2, lw=3, label='Class {}'.format(classes[1]))\n\n ax.plot([0, 1], [1, 1], 'k--', lw=2, label='Baseline')\n\n ax.set_xlabel('Percentage of sample', fontsize=text_fontsize)\n ax.set_ylabel('Lift', fontsize=text_fontsize)\n ax.tick_params(labelsize=text_fontsize)\n ax.grid('on')\n ax.legend(loc='lower right', fontsize=text_fontsize)\n\n return ax\n"
] |
[
[
"numpy.random.seed",
"sklearn.datasets.load_iris",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.close",
"sklearn.decomposition.PCA"
],
[
"sklearn.metrics.silhouette_samples",
"sklearn.metrics.silhouette_score",
"numpy.asarray",
"numpy.around",
"numpy.in1d",
"sklearn.metrics.confusion_matrix",
"sklearn.utils.deprecated",
"numpy.zeros_like",
"sklearn.preprocessing.LabelEncoder",
"numpy.where",
"numpy.hstack",
"numpy.unique",
"numpy.arange",
"sklearn.metrics.precision_recall_curve",
"sklearn.calibration.calibration_curve",
"matplotlib.pyplot.cm.get_cmap",
"numpy.isnan",
"sklearn.metrics.roc_curve",
"sklearn.metrics.auc",
"sklearn.utils.multiclass.unique_labels",
"numpy.array",
"sklearn.preprocessing.label_binarize",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.colorbar",
"sklearn.metrics.average_precision_score",
"scipy.interp"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
prOttonicFusion/spectrograph
|
[
"9ebc1c4b129f9aff6b83024b3d4aa78af556c813"
] |
[
"linearSpectrum.py"
] |
[
"\"\"\"\nPlot a spectrum from a data file of color codes\n\"\"\"\n\n__author__ = \"prOttonicFusion\"\n__version__ = \"0.1.0\"\n__license__ = \"MIT\"\n\nimport numpy as np\nimport argparse\nfrom math import pi\nfrom bokeh.io import output_file, export_png, show\nfrom bokeh.plotting import figure\n\n\ndef main(color_data_file, html='', png='', title='', show_axes=False, show_grid=False):\n colors = np.loadtxt(color_data_file, comments=\"%\", dtype=str)\n data_range = len(colors)\n data = list(range(0, data_range))\n\n fig = figure(plot_height=250, title=title,\n toolbar_location=None, tools='')\n\n fig.vbar(x=data, top=1, width=0.9, color=colors)\n\n if not show_axes:\n fig.axis.visible = False\n\n if not show_grid:\n fig.xgrid.grid_line_color = None\n fig.ygrid.grid_line_color = None\n fig.outline_line_color = None\n\n if html != '':\n output_file(html, mode=None, root_dir=None)\n\n if png != '':\n export_png(fig, filename=png)\n\n show(fig)\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n 'color_data_file', help='path to the data file containing a list of colors')\n parser.add_argument('--html',\n help='set the output file name and save as HTML, default: none', default='')\n parser.add_argument('--png',\n help='set the output file name and save as png, default: none', default='')\n parser.add_argument('--title',\n help='set plot title, default: none', default='')\n parser.add_argument('--show_axes',\n help='show plot axes, default: False', action='store_true', default=False)\n parser.add_argument('--show_grid',\n help='show plot grid, default: False', action='store_true', default=False)\n args = parser.parse_args()\n\n return [args.color_data_file, args.html, args.png, args.title, args.show_axes, args.show_grid]\n\n\nif __name__ == \"__main__\":\n args = parse_arguments()\n main(*args)\n"
] |
[
[
"numpy.loadtxt"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
menikhilpandey/AART
|
[
"4accd3ad777933a46c57caa6e9fc7ac85cb667ee"
] |
[
"emotion_detection/realtime_demo.py"
] |
[
"import numpy as np\nimport argparse\nimport cv2\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Flatten\nfrom keras.layers.convolutional import Conv2D\nfrom keras.optimizers import Adam\nfrom keras.layers.pooling import MaxPooling2D\nfrom keras.preprocessing.image import ImageDataGenerator\n\nval_dir = 'data/test'\n\nmodel = Sequential()\n\nmodel.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(48,48,1)))\nmodel.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(1024, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(7, activation='softmax'))\n\nmodel.load_weights('model.h5')\n\ncv2.ocl.setUseOpenCL(False)\nemotion_dict = {0: \"Angry\", 1: \"Disgusted\", 2: \"Fearful\", 3: \"Happy\", 4: \"Neutral\", 5: \"Sad\", 6: \"Surprised\"}\n\ncap = cv2.VideoCapture('../video.mp4')\nwhile True:\n ret, frame = cap.read()\n if not ret:\n break\n facecasc = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = facecasc.detectMultiScale(gray,scaleFactor=1.3, minNeighbors=5)\n\n for (x, y, w, h) in faces:\n cv2.rectangle(frame, (x, y-50), (x+w, y+h+10), (255, 0, 0), 2)\n roi_gray = gray[y:y + h, x:x + w]\n cropped_img = np.expand_dims(np.expand_dims(cv2.resize(roi_gray, (48, 48)), -1), 0)\n prediction = model.predict(cropped_img)\n maxindex = int(np.argmax(prediction))\n cv2.putText(frame, emotion_dict[maxindex], (x+20, y-60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2, cv2.LINE_AA)\n\n cv2.imshow('Video', cv2.resize(frame,(1920,1080),interpolation = cv2.INTER_CUBIC))\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n"
] |
[
[
"numpy.argmax"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Chicco94/breakout-Q-learning
|
[
"dfb7c1d18c4472f21828f1163641817b6f44d726"
] |
[
"model.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport os\n\nclass Linear_QNet(nn.Module):\n\tdef __init__(self, input_size, hidden_size, hidden_size2, output_size):\n\t\t# feed forward neural network\n\t\tsuper().__init__()\n\t\tself.linear1 = nn.Linear(input_size, hidden_size)\n\t\tself.linear2 = nn.Linear(input_size, hidden_size2)\n\t\tself.linear3 = nn.Linear(hidden_size2, output_size)\n\n\tdef forward(self, x):\n\t\tx = F.relu(self.linear1(x))\n\t\tx = self.linear2(x)\n\t\tx = self.linear3(x)\n\t\treturn x\n\n\tdef save(self, state_dict, file_name=\"model.pth\"):\n\t\tmodel_folder_path = \"./models\"\n\t\tif not os.path.exists(model_folder_path):\n\t\t\tos.makedirs(model_folder_path)\n\n\t\tfile_name = os.path.join(model_folder_path,file_name)\n\t\ttorch.save(state_dict, file_name)\n\n\tdef load(self, file_name=\"model.pth\"):\n\t\tmodel_folder_path = \"./models\"\n\t\tfile_name = os.path.join(model_folder_path,file_name)\n\t\tcheckpoint = torch.load(file_name)\n\t\tself.load_state_dict(checkpoint['state_dict'])\n\nclass QTrainer():\n\n\tdef __init__(self,model, lr, gamma):\n\t\tself.lr = lr\n\t\tself.gamma = gamma\n\t\tself.model = model\n\t\tself.optimizer = optim.Adam(model.parameters(), lr=self.lr)\n\t\tself.criterion = nn.MSELoss()\n\n\tdef train_step(self, state, action, reward, next_state, done):\n\t\tstate = torch.tensor(state,dtype=torch.float)\n\t\tnext_state = torch.tensor(next_state,dtype=torch.float)\n\t\taction = torch.tensor(action,dtype=torch.long)\n\t\treward = torch.tensor(reward,dtype=torch.float)\n\n\t\tif len(state.shape) == 1:\n\t\t\tstate = torch.unsqueeze(state, 0)\n\t\t\tnext_state = torch.unsqueeze(next_state, 0)\n\t\t\taction = torch.unsqueeze(action, 0)\n\t\t\treward = torch.unsqueeze(reward, 0)\n\t\t\tdone = (done, )\n\n\t\t# 1. predicted Q values with current state\n\t\tpred = self.model(state)\n\n\t\t# 2. Q_new = r + gamma * max(next_predicted_q_value) -> only if not done\n\t\t# pred.clone()\n\t\t# preds[argmax(action)] = Q_new\n\t\ttarget = pred.clone()\n\t\tfor idx in range(len(done)):\n\t\t\tQ_new = reward[idx]\n\t\t\tif not done[idx]:\n\t\t\t\tQ_new = reward[idx] + self.gamma * torch.max(self.model(next_state[idx]))\n\t\t\ttarget[idx][torch.argmax(action[idx]).item()] = Q_new\n\t\n\t\tself.optimizer.zero_grad()\n\t\tloss = self.criterion(target,pred)\n\t\tloss.backward()\n\n\t\tself.optimizer.step()\n\n\n"
] |
[
[
"torch.load",
"torch.argmax",
"torch.unsqueeze",
"torch.tensor",
"torch.nn.Linear",
"torch.nn.MSELoss",
"torch.save"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Pangoraw/Deep-SVDD-PyTorch
|
[
"806f7099cea2013a87ebb32f30a6f4c9595ebbeb"
] |
[
"src/datasets/mnist.py"
] |
[
"from torch.utils.data import Subset\nfrom PIL import Image\nfrom torchvision.datasets import MNIST\nfrom base.torchvision_dataset import TorchvisionDataset\nfrom .preprocessing import get_target_label_idx, global_contrast_normalization\n\nimport torchvision.transforms as transforms\n\nMNIST.resources = [\n ('https://ossci-datasets.s3.amazonaws.com/mnist/train-images-idx3-ubyte.gz', 'f68b3c2dcbeaaa9fbdd348bbdeb94873'),\n ('https://ossci-datasets.s3.amazonaws.com/mnist/train-labels-idx1-ubyte.gz', 'd53e105ee54ea40749a09fcbcd1e9432'),\n ('https://ossci-datasets.s3.amazonaws.com/mnist/t10k-images-idx3-ubyte.gz', '9fb629c4189551a2d022fa330f9573f3'),\n ('https://ossci-datasets.s3.amazonaws.com/mnist/t10k-labels-idx1-ubyte.gz', 'ec29112dd5afa0611ce80d1b7f02629c')\n ]\n\nclass MNIST_Dataset(TorchvisionDataset):\n\n def __init__(self, root: str, normal_class=0):\n super().__init__(root)\n\n self.n_classes = 2 # 0: normal, 1: outlier\n self.normal_classes = tuple([normal_class])\n self.outlier_classes = list(range(0, 10))\n self.outlier_classes.remove(normal_class)\n\n # Pre-computed min and max values (after applying GCN) from train data per class\n min_max = [(-0.8826567065619495, 9.001545489292527),\n (-0.6661464580883915, 20.108062262467364),\n (-0.7820454743183202, 11.665100841080346),\n (-0.7645772083211267, 12.895051191467457),\n (-0.7253923114302238, 12.683235701611533),\n (-0.7698501867861425, 13.103278415430502),\n (-0.778418217980696, 10.457837397569108),\n (-0.7129780970522351, 12.057777597673047),\n (-0.8280402650205075, 10.581538445782988),\n (-0.7369959242164307, 10.697039838804978)]\n\n # MNIST preprocessing: GCN (with L1 norm) and min-max feature scaling to [0,1]\n transform = transforms.Compose([transforms.ToTensor(),\n transforms.Lambda(lambda x: global_contrast_normalization(x, scale='l1')),\n transforms.Normalize([min_max[normal_class][0]],\n [min_max[normal_class][1] - min_max[normal_class][0]])])\n\n target_transform = transforms.Lambda(lambda x: int(x in self.outlier_classes))\n\n train_set = MyMNIST(root=self.root, train=True, download=True,\n transform=transform, target_transform=target_transform)\n # Subset train_set to normal class\n train_idx_normal = get_target_label_idx(train_set.train_labels.clone().data.cpu().numpy(), self.normal_classes)\n self.train_set = Subset(train_set, train_idx_normal)\n\n self.test_set = MyMNIST(root=self.root, train=False, download=True,\n transform=transform, target_transform=target_transform)\n\n\nclass MyMNIST(MNIST):\n \"\"\"Torchvision MNIST class with patch of __getitem__ method to also return the index of a data sample.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(MyMNIST, self).__init__(*args, **kwargs)\n\n def __getitem__(self, index):\n \"\"\"Override the original method of the MNIST class.\n Args:\n index (int): Index\n Returns:\n triple: (image, target, index) where target is index of the target class.\n \"\"\"\n if self.train:\n img, target = self.train_data[index], self.train_labels[index]\n else:\n img, target = self.test_data[index], self.test_labels[index]\n\n # doing this so that it is consistent with all other datasets\n # to return a PIL Image\n img = Image.fromarray(img.numpy(), mode='L')\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target, index # only line changed\n"
] |
[
[
"torch.utils.data.Subset"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
liseda-lab/Supervised-SS
|
[
"62cbea0475fb93693c1edf4f6d1ff1bdaab17265"
] |
[
"Regression/gplearn/_program.py"
] |
[
"\"\"\"The underlying data structure used in gplearn.\r\n\r\nThe :mod:`gplearn._program` module contains the underlying representation of a\r\ncomputer program. It is used for creating and evolving programs used in the\r\n:mod:`gplearn.genetic` module.\r\n\"\"\"\r\n\r\n# Author: Trevor Stephens <trevorstephens.com>\r\n#\r\n# License: BSD 3 clause\r\n\r\nfrom copy import deepcopy\r\n\r\nimport numpy as np\r\nfrom sklearn.utils.random import sample_without_replacement\r\n\r\nfrom gplearn.functions import _Function\r\nfrom gplearn.utils import check_random_state\r\n\r\n\r\nclass _Program(object):\r\n\r\n \"\"\"A program-like representation of the evolved program.\r\n\r\n This is the underlying data-structure used by the public classes in this\r\n module. It should not be used directly by the user.\r\n\r\n Parameters\r\n ----------\r\n function_set : list\r\n A list of valid functions to use in the program.\r\n\r\n arities : dict\r\n A dictionary of the form `{arity: [functions]}`. The arity is the\r\n number of arguments that the function takes, the functions must match\r\n those in the `function_set` parameter.\r\n\r\n init_depth : tuple of two ints\r\n The range of tree depths for the initial population of naive formulas.\r\n Individual trees will randomly choose a maximum depth from this range.\r\n When combined with `init_method='half and half'` this yields the well-\r\n known 'ramped half and half' initialization method.\r\n\r\n init_method : str\r\n - 'grow' : Nodes are chosen at random from both functions and\r\n terminals, allowing for smaller trees than `init_depth` allows. Tends\r\n to grow asymmetrical trees.\r\n - 'full' : Functions are chosen until the `init_depth` is reached, and\r\n then terminals are selected. Tends to grow 'bushy' trees.\r\n - 'half and half' : Trees are grown through a 50/50 mix of 'full' and\r\n 'grow', making for a mix of tree shapes in the initial population.\r\n\r\n n_features : int\r\n The number of features in `X`.\r\n\r\n const_range : tuple of two floats\r\n The range of constants to include in the formulas.\r\n\r\n metric : _Fitness object\r\n The raw fitness metric.\r\n\r\n p_point_replace : float\r\n The probability that any given node will be mutated during point\r\n mutation.\r\n\r\n parsimony_coefficient : float\r\n This constant penalizes large programs by adjusting their fitness to\r\n be less favorable for selection. Larger values penalize the program\r\n more which can control the phenomenon known as 'bloat'. Bloat is when\r\n evolution is increasing the size of programs without a significant\r\n increase in fitness, which is costly for computation time and makes for\r\n a less understandable final result. This parameter may need to be tuned\r\n over successive runs.\r\n\r\n random_state : RandomState instance\r\n The random number generator. Note that ints, or None are not allowed.\r\n The reason for this being passed is that during parallel evolution the\r\n same program object may be accessed by multiple parallel processes.\r\n\r\n program : list, optional (default=None)\r\n The flattened tree representation of the program. If None, a new naive\r\n random tree will be grown. If provided, it will be validated.\r\n\r\n Attributes\r\n ----------\r\n program : list\r\n The flattened tree representation of the program.\r\n\r\n raw_fitness_ : float\r\n The raw fitness of the individual program.\r\n\r\n fitness_ : float\r\n The penalized fitness of the individual program.\r\n\r\n oob_fitness_ : float\r\n The out-of-bag raw fitness of the individual program for the held-out\r\n samples. Only present when sub-sampling was used in the estimator by\r\n specifying `max_samples` < 1.0.\r\n\r\n parents : dict, or None\r\n If None, this is a naive random program from the initial population.\r\n Otherwise it includes meta-data about the program's parent(s) as well\r\n as the genetic operations performed to yield the current program. This\r\n is set outside this class by the controlling evolution loops.\r\n\r\n depth_ : int\r\n The maximum depth of the program tree.\r\n\r\n length_ : int\r\n The number of functions and terminals in the program.\r\n\r\n \"\"\"\r\n\r\n def __init__(self,\r\n function_set,\r\n arities,\r\n init_depth,\r\n init_method,\r\n n_features,\r\n const_range,\r\n metric,\r\n p_point_replace,\r\n parsimony_coefficient,\r\n random_state,\r\n program=None):\r\n\r\n self.function_set = function_set\r\n self.arities = arities\r\n self.init_depth = (init_depth[0], init_depth[1] + 1)\r\n self.init_method = init_method\r\n self.n_features = n_features\r\n self.const_range = const_range\r\n self.metric = metric\r\n self.p_point_replace = p_point_replace\r\n self.parsimony_coefficient = parsimony_coefficient\r\n self.program = program\r\n\r\n if self.program is not None:\r\n if not self.validate_program():\r\n raise ValueError('The supplied program is incomplete')\r\n else:\r\n # Create a naive random program\r\n self.program = self.build_program(random_state)\r\n\r\n self.raw_fitness_ = None\r\n self.fitness_ = None\r\n self.parents = None\r\n self._n_samples = None\r\n self._max_samples = None\r\n self._indices_state = None\r\n\r\n def build_program(self, random_state):\r\n \"\"\"Build a naive random program.\r\n\r\n Parameters\r\n ----------\r\n random_state : RandomState instance\r\n The random number generator.\r\n\r\n Returns\r\n -------\r\n program : list\r\n The flattened tree representation of the program.\r\n\r\n \"\"\"\r\n if self.init_method == 'half and half':\r\n method = ('full' if random_state.randint(2) else 'grow')\r\n else:\r\n method = self.init_method\r\n max_depth = random_state.randint(*self.init_depth)\r\n\r\n # Start a program with a function to avoid degenerative programs\r\n function = random_state.randint(len(self.function_set))\r\n function = self.function_set[function]\r\n program = [function]\r\n terminal_stack = [function.arity]\r\n\r\n while terminal_stack:\r\n depth = len(terminal_stack)\r\n choice = self.n_features + len(self.function_set)\r\n choice = random_state.randint(choice)\r\n # Determine if we are adding a function or terminal\r\n if (depth < max_depth) and (method == 'full' or\r\n choice <= len(self.function_set)):\r\n function = random_state.randint(len(self.function_set))\r\n function = self.function_set[function]\r\n program.append(function)\r\n terminal_stack.append(function.arity)\r\n else:\r\n # We need a terminal, add a variable or constant\r\n if self.const_range is not None:\r\n terminal = random_state.randint(self.n_features + 1)\r\n else:\r\n terminal = random_state.randint(self.n_features)\r\n if terminal == self.n_features:\r\n terminal = random_state.uniform(*self.const_range)\r\n if self.const_range is None:\r\n # We should never get here\r\n raise ValueError('A constant was produced with '\r\n 'const_range=None.')\r\n program.append(terminal)\r\n terminal_stack[-1] -= 1\r\n while terminal_stack[-1] == 0:\r\n terminal_stack.pop()\r\n if not terminal_stack:\r\n return program\r\n terminal_stack[-1] -= 1\r\n\r\n # We should never get here\r\n return None\r\n\r\n def validate_program(self):\r\n \"\"\"Rough check that the embedded program in the object is valid.\"\"\"\r\n terminals = [0]\r\n for node in self.program:\r\n if isinstance(node, _Function):\r\n terminals.append(node.arity)\r\n else:\r\n terminals[-1] -= 1\r\n while terminals[-1] == 0:\r\n terminals.pop()\r\n terminals[-1] -= 1\r\n return terminals == [-1]\r\n\r\n def __str__(self):\r\n \"\"\"Overloads `print` output of the object to resemble a LISP tree.\"\"\"\r\n terminals = [0]\r\n output = ''\r\n for i, node in enumerate(self.program):\r\n if isinstance(node, _Function):\r\n terminals.append(node.arity)\r\n output += node.name + '('\r\n else:\r\n if isinstance(node, int):\r\n output += 'X%s' % node\r\n else:\r\n output += '%.3f' % node\r\n terminals[-1] -= 1\r\n while terminals[-1] == 0:\r\n terminals.pop()\r\n terminals[-1] -= 1\r\n output += ')'\r\n if i != len(self.program) - 1:\r\n output += ', '\r\n return output\r\n\r\n def export_graphviz(self, fade_nodes=None):\r\n \"\"\"Returns a string, Graphviz script for visualizing the program.\r\n\r\n Parameters\r\n ----------\r\n fade_nodes : list, optional\r\n A list of node indices to fade out for showing which were removed\r\n during evolution.\r\n\r\n Returns\r\n -------\r\n output : string\r\n The Graphviz script to plot the tree representation of the program.\r\n\r\n \"\"\"\r\n terminals = []\r\n if fade_nodes is None:\r\n fade_nodes = []\r\n output = 'digraph program {\\nnode [style=filled]'\r\n for i, node in enumerate(self.program):\r\n fill = '#cecece'\r\n if isinstance(node, _Function):\r\n if i not in fade_nodes:\r\n fill = '#136ed4'\r\n terminals.append([node.arity, i])\r\n output += ('%d [label=\"%s\", fillcolor=\"%s\"] ;\\n'\r\n % (i, node.name, fill))\r\n else:\r\n if i not in fade_nodes:\r\n fill = '#60a6f6'\r\n if isinstance(node, int):\r\n output += ('%d [label=\"%s%s\", fillcolor=\"%s\"] ;\\n'\r\n % (i, 'X', node, fill))\r\n else:\r\n output += ('%d [label=\"%.3f\", fillcolor=\"%s\"] ;\\n'\r\n % (i, node, fill))\r\n if i == 0:\r\n # A degenerative program of only one node\r\n return output + '}'\r\n terminals[-1][0] -= 1\r\n terminals[-1].append(i)\r\n while terminals[-1][0] == 0:\r\n output += '%d -> %d ;\\n' % (terminals[-1][1],\r\n terminals[-1][-1])\r\n terminals[-1].pop()\r\n if len(terminals[-1]) == 2:\r\n parent = terminals[-1][-1]\r\n terminals.pop()\r\n if not terminals:\r\n return output + '}'\r\n terminals[-1].append(parent)\r\n terminals[-1][0] -= 1\r\n\r\n # We should never get here\r\n return None\r\n\r\n def _depth(self):\r\n \"\"\"Calculates the maximum depth of the program tree.\"\"\"\r\n terminals = [0]\r\n depth = 1\r\n for node in self.program:\r\n if isinstance(node, _Function):\r\n terminals.append(node.arity)\r\n depth = max(len(terminals), depth)\r\n else:\r\n terminals[-1] -= 1\r\n while terminals[-1] == 0:\r\n terminals.pop()\r\n terminals[-1] -= 1\r\n return depth - 1\r\n\r\n def _length(self):\r\n \"\"\"Calculates the number of functions and terminals in the program.\"\"\"\r\n return len(self.program)\r\n\r\n def execute(self, X):\r\n \"\"\"Execute the program according to X.\r\n\r\n Parameters\r\n ----------\r\n X : {array-like}, shape = [n_samples, n_features]\r\n Training vectors, where n_samples is the number of samples and\r\n n_features is the number of features.\r\n\r\n Returns\r\n -------\r\n y_hats : array-like, shape = [n_samples]\r\n The result of executing the program on X.\r\n\r\n \"\"\"\r\n # Check for single-node programs\r\n node = self.program[0]\r\n if isinstance(node, float):\r\n return np.repeat(node, X.shape[0])\r\n if isinstance(node, int):\r\n return X[:, node]\r\n\r\n apply_stack = []\r\n\r\n for node in self.program:\r\n\r\n if isinstance(node, _Function):\r\n apply_stack.append([node])\r\n else:\r\n # Lazily evaluate later\r\n apply_stack[-1].append(node)\r\n\r\n while len(apply_stack[-1]) == apply_stack[-1][0].arity + 1:\r\n # Apply functions that have sufficient arguments\r\n function = apply_stack[-1][0]\r\n terminals = [np.repeat(t, X.shape[0]) if isinstance(t, float)\r\n else X[:, t] if isinstance(t, int)\r\n else t for t in apply_stack[-1][1:]]\r\n intermediate_result = function(*terminals)\r\n if len(apply_stack) != 1:\r\n apply_stack.pop()\r\n apply_stack[-1].append(intermediate_result)\r\n else:\r\n return intermediate_result\r\n\r\n # We should never get here\r\n return None\r\n\r\n def get_all_indices(self, n_samples=None, max_samples=None,\r\n random_state=None):\r\n \"\"\"Get the indices on which to evaluate the fitness of a program.\r\n\r\n Parameters\r\n ----------\r\n n_samples : int\r\n The number of samples.\r\n\r\n max_samples : int\r\n The maximum number of samples to use.\r\n\r\n random_state : RandomState instance\r\n The random number generator.\r\n\r\n Returns\r\n -------\r\n indices : array-like, shape = [n_samples]\r\n The in-sample indices.\r\n\r\n not_indices : array-like, shape = [n_samples]\r\n The out-of-sample indices.\r\n\r\n \"\"\"\r\n if self._indices_state is None and random_state is None:\r\n raise ValueError('The program has not been evaluated for fitness '\r\n 'yet, indices not available.')\r\n\r\n if n_samples is not None and self._n_samples is None:\r\n self._n_samples = n_samples\r\n if max_samples is not None and self._max_samples is None:\r\n self._max_samples = max_samples\r\n if random_state is not None and self._indices_state is None:\r\n self._indices_state = random_state.get_state()\r\n\r\n indices_state = check_random_state(None)\r\n indices_state.set_state(self._indices_state)\r\n\r\n not_indices = sample_without_replacement(\r\n self._n_samples,\r\n self._n_samples - self._max_samples,\r\n random_state=indices_state)\r\n sample_counts = np.bincount(not_indices, minlength=self._n_samples)\r\n indices = np.where(sample_counts == 0)[0]\r\n\r\n return indices, not_indices\r\n\r\n def _indices(self):\r\n \"\"\"Get the indices used to measure the program's fitness.\"\"\"\r\n return self.get_all_indices()[0]\r\n\r\n def raw_fitness(self, X, y, sample_weight):\r\n \"\"\"Evaluate the raw fitness of the program according to X, y.\r\n\r\n Parameters\r\n ----------\r\n X : {array-like}, shape = [n_samples, n_features]\r\n Training vectors, where n_samples is the number of samples and\r\n n_features is the number of features.\r\n\r\n y : array-like, shape = [n_samples]\r\n Target values.\r\n\r\n sample_weight : array-like, shape = [n_samples]\r\n Weights applied to individual samples.\r\n\r\n Returns\r\n -------\r\n raw_fitness : float\r\n The raw fitness of the program.\r\n\r\n \"\"\"\r\n y_pred = self.execute(X)\r\n raw_fitness = self.metric(y, y_pred, sample_weight)\r\n\r\n return raw_fitness\r\n\r\n def fitness(self, parsimony_coefficient=None):\r\n \"\"\"Evaluate the penalized fitness of the program according to X, y.\r\n\r\n Parameters\r\n ----------\r\n parsimony_coefficient : float, optional\r\n If automatic parsimony is being used, the computed value according\r\n to the population. Otherwise the initialized value is used.\r\n\r\n Returns\r\n -------\r\n fitness : float\r\n The penalized fitness of the program.\r\n\r\n \"\"\"\r\n if parsimony_coefficient is None:\r\n parsimony_coefficient = self.parsimony_coefficient\r\n penalty = parsimony_coefficient * len(self.program) * self.metric.sign\r\n return self.raw_fitness_ - penalty\r\n\r\n def get_subtree(self, random_state, program=None):\r\n \"\"\"Get a random subtree from the program.\r\n\r\n Parameters\r\n ----------\r\n random_state : RandomState instance\r\n The random number generator.\r\n\r\n program : list, optional (default=None)\r\n The flattened tree representation of the program. If None, the\r\n embedded tree in the object will be used.\r\n\r\n Returns\r\n -------\r\n start, end : tuple of two ints\r\n The indices of the start and end of the random subtree.\r\n\r\n \"\"\"\r\n if program is None:\r\n program = self.program\r\n probs = np.array([0.9 if isinstance(node, _Function) else 0.1\r\n for node in program])\r\n probs = np.cumsum(probs / probs.sum())\r\n start = np.searchsorted(probs, random_state.uniform())\r\n\r\n stack = 1\r\n end = start\r\n while stack > end - start:\r\n node = program[end]\r\n if isinstance(node, _Function):\r\n stack += node.arity\r\n end += 1\r\n\r\n return start, end\r\n\r\n def reproduce(self):\r\n \"\"\"Return a copy of the embedded program.\"\"\"\r\n return deepcopy(self.program)\r\n\r\n def crossover(self, donor, random_state):\r\n \"\"\"Perform the crossover genetic operation on the program.\r\n\r\n Crossover selects a random subtree from the embedded program to be\r\n replaced. A donor also has a subtree selected at random and this is\r\n inserted into the original parent to form an offspring.\r\n\r\n Parameters\r\n ----------\r\n donor : list\r\n The flattened tree representation of the donor program.\r\n\r\n random_state : RandomState instance\r\n The random number generator.\r\n\r\n Returns\r\n -------\r\n program : list\r\n The flattened tree representation of the program.\r\n\r\n \"\"\"\r\n # Get a subtree to replace\r\n start, end = self.get_subtree(random_state)\r\n removed = range(start, end)\r\n # Get a subtree to donate\r\n donor_start, donor_end = self.get_subtree(random_state, donor)\r\n donor_removed = list(set(range(len(donor))) -\r\n set(range(donor_start, donor_end)))\r\n # Insert genetic material from donor\r\n return (self.program[:start] +\r\n donor[donor_start:donor_end] +\r\n self.program[end:]), removed, donor_removed\r\n\r\n def subtree_mutation(self, random_state):\r\n \"\"\"Perform the subtree mutation operation on the program.\r\n\r\n Subtree mutation selects a random subtree from the embedded program to\r\n be replaced. A donor subtree is generated at random and this is\r\n inserted into the original parent to form an offspring. This\r\n implementation uses the \"headless chicken\" method where the donor\r\n subtree is grown using the initialization methods and a subtree of it\r\n is selected to be donated to the parent.\r\n\r\n Parameters\r\n ----------\r\n random_state : RandomState instance\r\n The random number generator.\r\n\r\n Returns\r\n -------\r\n program : list\r\n The flattened tree representation of the program.\r\n\r\n \"\"\"\r\n # Build a new naive program\r\n chicken = self.build_program(random_state)\r\n # Do subtree mutation via the headless chicken method!\r\n return self.crossover(chicken, random_state)\r\n\r\n def hoist_mutation(self, random_state):\r\n \"\"\"Perform the hoist mutation operation on the program.\r\n\r\n Hoist mutation selects a random subtree from the embedded program to\r\n be replaced. A random subtree of that subtree is then selected and this\r\n is 'hoisted' into the original subtrees location to form an offspring.\r\n This method helps to control bloat.\r\n\r\n Parameters\r\n ----------\r\n random_state : RandomState instance\r\n The random number generator.\r\n\r\n Returns\r\n -------\r\n program : list\r\n The flattened tree representation of the program.\r\n\r\n \"\"\"\r\n # Get a subtree to replace\r\n start, end = self.get_subtree(random_state)\r\n subtree = self.program[start:end]\r\n # Get a subtree of the subtree to hoist\r\n sub_start, sub_end = self.get_subtree(random_state, subtree)\r\n hoist = subtree[sub_start:sub_end]\r\n # Determine which nodes were removed for plotting\r\n removed = list(set(range(start, end)) -\r\n set(range(start + sub_start, start + sub_end)))\r\n return self.program[:start] + hoist + self.program[end:], removed\r\n\r\n def point_mutation(self, random_state):\r\n \"\"\"Perform the point mutation operation on the program.\r\n\r\n Point mutation selects random nodes from the embedded program to be\r\n replaced. Terminals are replaced by other terminals and functions are\r\n replaced by other functions that require the same number of arguments\r\n as the original node. The resulting tree forms an offspring.\r\n\r\n Parameters\r\n ----------\r\n random_state : RandomState instance\r\n The random number generator.\r\n\r\n Returns\r\n -------\r\n program : list\r\n The flattened tree representation of the program.\r\n\r\n \"\"\"\r\n program = deepcopy(self.program)\r\n\r\n # Get the nodes to modify\r\n mutate = np.where([True if (random_state.uniform() <\r\n self.p_point_replace)\r\n else False\r\n for _ in range(len(program))])[0]\r\n\r\n for node in mutate:\r\n if isinstance(program[node], _Function):\r\n arity = program[node].arity\r\n # Find a valid replacement with same arity\r\n replacement = len(self.arities[arity])\r\n replacement = random_state.randint(replacement)\r\n replacement = self.arities[arity][replacement]\r\n program[node] = replacement\r\n else:\r\n # We've got a terminal, add a const or variable\r\n if self.const_range is not None:\r\n terminal = random_state.randint(self.n_features + 1)\r\n else:\r\n terminal = random_state.randint(self.n_features)\r\n if terminal == self.n_features:\r\n terminal = random_state.uniform(*self.const_range)\r\n if self.const_range is None:\r\n # We should never get here\r\n raise ValueError('A constant was produced with '\r\n 'const_range=None.')\r\n program[node] = terminal\r\n\r\n return program, list(mutate)\r\n\r\n depth_ = property(_depth)\r\n length_ = property(_length)\r\n indices_ = property(_indices)\r\n"
] |
[
[
"numpy.repeat",
"numpy.where",
"sklearn.utils.random.sample_without_replacement",
"numpy.bincount"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Shivvrat/Machine-Learning-Algorithms
|
[
"f20503ee513dbd7e51470c464e47358dd6c1e133"
] |
[
"Learning-Algorithms-for-Bayesian-Networks/Learning-Algorithms-for-Bayesian-Networks-master/pod_em_learn.py"
] |
[
"\"\"\"\r\n\r\n__author__ = \"Shivvrat Arya\"\r\n__version__ = \"Python3.7\"\r\n\"\"\"\r\n\r\nfrom numpy import array, zeros, nan_to_num, divide, product\r\n\r\nimport helper\r\nfrom helper import generate_random_parameters, complete_data\r\n\r\n\r\ndef train(pod_examples, var_in_clique, markov, cardinalities_of_var, iterations):\r\n\t\"\"\"\r\n\r\n\t:param weighted_examples:\r\n\t:param var_in_clique:\r\n\t:param markov:\r\n\t:param cardinalities_of_var:\r\n\t:return: parameters in double form\r\n\t\"\"\"\r\n\tif not markov:\r\n\t\tparameters = generate_random_parameters(var_in_clique, cardinalities_of_var)\r\n\t\tfor each in range(iterations):\r\n\t\t\tweighted_examples, weights = e_step(parameters, pod_examples, var_in_clique, cardinalities_of_var)\r\n\t\t\tparameters = m_step(weighted_examples, weights, var_in_clique, cardinalities_of_var)\r\n\t\treturn parameters\r\n\telse:\r\n\t\tprint(\"Please provide a Bayesian Network\")\r\n\t\tprint(\"We are doing Bayesian Learning\")\r\n\t\texit()\r\n\r\n\r\ndef e_step(parameters, examples, var_in_clique, cardinalities_of_var):\r\n\tweighted_examples, weights = complete_data(examples, cardinalities_of_var, parameters, var_in_clique)\r\n\treturn weighted_examples, weights\r\n\r\n\r\ndef m_step(examples, weights, var_in_clique, cardinalities_of_var):\r\n\tparameters = get_parameters_given_weighted_example(examples, weights, var_in_clique, cardinalities_of_var)\r\n\treturn parameters\r\n\r\n\r\ndef get_parameters_given_weighted_example(examples, weights, var_in_clique, cardinalities_of_var):\r\n\tparameters = []\r\n\tcardinalities_of_var = array(cardinalities_of_var)\r\n\texamples = array(examples)\r\n\tvar_in_clique_np = array(var_in_clique)\r\n\tfor each_clique in range(len(var_in_clique)):\r\n\t\tvar_in_this_clique = var_in_clique_np[each_clique]\r\n\t\tvals_for_this_clique = examples[:, var_in_this_clique]\r\n\t\tcardinalities_of_var_in_this_clique = cardinalities_of_var[var_in_this_clique]\r\n\t\ttotal_tuples = product(cardinalities_of_var_in_this_clique)\r\n\t\tif len(var_in_this_clique) > 1:\r\n\t\t\tnumber_of_parameters = int(total_tuples / cardinalities_of_var_in_this_clique[-1])\r\n\t\t\tnums = zeros([number_of_parameters, ])\r\n\t\t\tdenom = zeros([number_of_parameters, ])\r\n\t\t\tfor each_vals_for_this_clique, weights_for_this_example in zip(vals_for_this_clique, weights):\r\n\t\t\t\t# indexing of parameters is done on the basis of parent variables only\r\n\t\t\t\tindex_val_without_child = helper.get_index_given_truth_values(var_in_this_clique[:-1],\r\n\t\t\t\t each_vals_for_this_clique[:-1],\r\n\t\t\t\t cardinalities_of_var_in_this_clique[\r\n\t\t\t\t :-1])\r\n\t\t\t\tdenom[index_val_without_child] += weights_for_this_example\r\n\t\t\t\tif each_vals_for_this_clique[-1] == 0:\r\n\t\t\t\t\tnums[index_val_without_child] += weights_for_this_example\r\n\t\t\tparameter_val = divide(nums, denom)\r\n\t\t\tparameter_val = nan_to_num(parameter_val)\r\n\t\t\tparameter_val[parameter_val == 0] = pow(10, -5)\r\n\t\t\tparameters.append(parameter_val)\r\n\t\telse:\r\n\t\t\tcount_of_zero = 0\r\n\t\t\ttotal_count = 0\r\n\t\t\tfor each_vals_for_this_clique, weights_for_this_example in zip(vals_for_this_clique, weights):\r\n\t\t\t\ttotal_count += weights_for_this_example\r\n\t\t\t\tif each_vals_for_this_clique[0] == 0:\r\n\t\t\t\t\tcount_of_zero += weights_for_this_example\r\n\t\t\tparameter = nan_to_num(divide(count_of_zero, total_count))\r\n\t\t\tif parameter == 0:\r\n\t\t\t\tparameter += pow(10, -5)\r\n\t\t\tparameters.append(parameter)\r\n\treturn parameters\r\n"
] |
[
[
"numpy.product",
"numpy.nan_to_num",
"numpy.array",
"numpy.zeros",
"numpy.divide"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
achang67/pyGSM-1
|
[
"ba7a1a1563a0d7765999e6683a93236571e6a470"
] |
[
"pygsm/coordinate_systems/internal_coordinates.py"
] |
[
"#!/usr/bin/env python\n\n# standard library imports\nimport time\n\n# third party\nfrom collections import OrderedDict\nimport numpy as np\nfrom numpy.linalg import multi_dot\n\nfrom utilities import elements, options, nifty, block_matrix\n\nELEMENT_TABLE = elements.ElementData()\n\nCacheWarning = False\n\n\nclass InternalCoordinates(object):\n\n @staticmethod\n def default_options():\n ''' InternalCoordinates default options.'''\n\n if hasattr(InternalCoordinates, '_default_options'):\n return InternalCoordinates._default_options.copy()\n opt = options.Options()\n\n opt.add_option(\n key=\"xyz\",\n required=True,\n doc='cartesian coordinates in angstrom'\n )\n\n opt.add_option(\n key='atoms',\n required=True,\n #allowed_types=[],\n doc='atom element named tuples/dictionary must be of type list[elements].'\n )\n\n opt.add_option(\n key='connect',\n value=False,\n allowed_types=[bool],\n doc=\"Connect the fragments/residues together with a minimum spanning bond,\\\n use for DLC, Don't use for TRIC, or HDLC.\",\n )\n\n opt.add_option(\n key='addcart',\n value=False,\n allowed_types=[bool],\n doc=\"Add cartesian coordinates\\\n use to form HDLC ,Don't use for TRIC, DLC.\",\n )\n\n opt.add_option(\n key='addtr',\n value=False,\n allowed_types=[bool],\n doc=\"Add translation and rotation coordinates\\\n use for TRIC.\",\n )\n\n opt.add_option(\n key='constraints',\n value=None,\n allowed_types=[list],\n doc='A list of Distance,Angle,Torsion constraints (see slots.py),\\\n This is only useful if doing a constrained geometry optimization\\\n since GSM will handle the constraint automatically.'\n )\n opt.add_option(\n key='cVals',\n value=None,\n allowed_types=[list],\n doc='List of Distance,Angle,Torsion constraints values'\n )\n\n opt.add_option(\n key='form_topology',\n value=True,\n doc='A lazy argument for forming the topology on the fly, dont use this',\n )\n\n opt.add_option(\n key='primitives',\n value=None,\n doc='This is a Primitive internal coordinates object -- can be used instead \\\n of creating new primitive object'\n )\n\n opt.add_option(\n key='topology',\n value=None,\n doc='This is the molecule topology, used for building primitives'\n )\n\n opt.add_option(\n key='print_level',\n value=1,\n required=False,\n allowed_types=[int],\n doc='0-- no printing, 1-- printing')\n\n InternalCoordinates._default_options = opt\n return InternalCoordinates._default_options.copy()\n\n @classmethod\n def from_options(cls, **kwargs):\n \"\"\" Returns an instance of this class with default options updated from values in kwargs\"\"\"\n return cls(cls.default_options().set_values(kwargs))\n\n def __init__(self,\n options\n ):\n\n self.options = options\n self.stored_wilsonB = OrderedDict()\n\n def addConstraint(self, cPrim, cVal):\n raise NotImplementedError(\"Constraints not supported with Cartesian coordinates\")\n\n def haveConstraints(self):\n raise NotImplementedError(\"Constraints not supported with Cartesian coordinates\")\n\n def augmentGH(self, xyz, G, H):\n raise NotImplementedError(\"Constraints not supported with Cartesian coordinates\")\n\n def calcGradProj(self, xyz, gradx):\n raise NotImplementedError(\"Constraints not supported with Cartesian coordinates\")\n\n def clearCache(self):\n self.stored_wilsonB = OrderedDict()\n\n def wilsonB(self, xyz):\n \"\"\"\n Given Cartesian coordinates xyz, return the Wilson B-matrix\n given by dq_i/dx_j where x is flattened (i.e. x1, y1, z1, x2, y2, z2)\n \"\"\"\n global CacheWarning\n t0 = time.time()\n xhash = hash(xyz.tostring())\n ht = time.time() - t0\n if xhash in self.stored_wilsonB:\n ans = self.stored_wilsonB[xhash]\n return ans\n WilsonB = []\n Der = self.derivatives(xyz)\n for i in range(Der.shape[0]):\n WilsonB.append(Der[i].flatten())\n self.stored_wilsonB[xhash] = np.array(WilsonB)\n if len(self.stored_wilsonB) > 1000 and not CacheWarning:\n nifty.logger.warning(\"\\x1b[91mWarning: more than 100 B-matrices stored, memory leaks likely\\x1b[0m\")\n CacheWarning = True\n ans = np.array(WilsonB)\n return ans\n\n def GMatrix(self, xyz, u=None):\n \"\"\"\n Given Cartesian coordinates xyz, return the G-matrix\n given by G = BuBt where u is an arbitrary matrix (default to identity)\n \"\"\"\n # t0 = time.time()\n Bmat = self.wilsonB(xyz)\n # t1 = time.time()\n\n if u is None:\n BuBt = np.dot(Bmat, Bmat.T)\n else:\n BuBt = np.dot(Bmat, np.dot(u, Bmat.T))\n # t2 = time.time()\n # t10 = t1-t0\n # t21 = t2-t1\n # print(\"time to form B-matrix %.3f\" % t10)\n # print(\"time to mat-mult B %.3f\" % t21)\n return BuBt\n\n def GInverse_SVD(self, xyz):\n xyz = xyz.reshape(-1, 3)\n # Perform singular value decomposition\n # nifty.click()\n loops = 0\n while True:\n try:\n G = self.GMatrix(xyz)\n # time_G = nifty.click()\n U, S, VT = np.linalg.svd(G)\n # time_svd = nifty.click()\n except np.linalg.LinAlgError:\n nifty.logger.warning(\"\\x1b[1;91m SVD fails, perturbing coordinates and trying again\\x1b[0m\")\n xyz = xyz + 1e-2*np.random.random(xyz.shape)\n loops += 1\n if loops == 10:\n raise RuntimeError('SVD failed too many times')\n continue\n break\n # print \"Build G: %.3f SVD: %.3f\" % (time_G, time_svd),\n V = VT.T\n UT = U.T\n Sinv = np.zeros_like(S)\n LargeVals = 0\n for ival, value in enumerate(S):\n # print \"%.5e % .5e\" % (ival,value)\n if np.abs(value) > 1e-6:\n LargeVals += 1\n Sinv[ival] = 1/value\n # print \"%i atoms; %i/%i singular values are > 1e-6\" % (xyz.shape[0], LargeVals, len(S))\n Sinv = np.diag(Sinv)\n Inv = multi_dot([V, Sinv, UT])\n return Inv\n\n def GInverse_EIG(self, xyz):\n xyz = xyz.reshape(-1, 3)\n # nifty.click()\n G = self.GMatrix(xyz)\n # time_G = nifty.click()\n Gi = np.linalg.inv(G)\n # time_inv = nifty.click()\n # print \"G-time: %.3f Inv-time: %.3f\" % (time_G, time_inv)\n return Gi\n\n def checkFiniteDifference(self, xyz):\n xyz = xyz.reshape(-1, 3)\n Analytical = self.derivatives(xyz)\n FiniteDifference = np.zeros_like(Analytical)\n h = 1e-5\n for i in range(xyz.shape[0]):\n for j in range(3):\n x1 = xyz.copy()\n x2 = xyz.copy()\n x1[i, j] += h\n x2[i, j] -= h\n PMDiff = self.calcDiff(x1, x2)\n FiniteDifference[:, i, j] = PMDiff/(2*h)\n for i in range(Analytical.shape[0]):\n nifty.logger.info(\"IC %i/%i : %s\" % (i, Analytical.shape[0], self.Internals[i]))\n lines = [\"\"]\n maxerr = 0.0\n for j in range(Analytical.shape[1]):\n lines.append(\"Atom %i\" % (j+1))\n for k in range(Analytical.shape[2]):\n error = Analytical[i, j, k] - FiniteDifference[i, j, k]\n if np.abs(error) > 1e-5:\n color = \"\\x1b[91m\"\n else:\n color = \"\\x1b[92m\"\n lines.append(\"%s % .5e % .5e %s% .5e\\x1b[0m\" % (\"xyz\"[k], Analytical[i, j, k], FiniteDifference[i, j, k], color, Analytical[i, j, k] - FiniteDifference[i, j, k]))\n if maxerr < np.abs(error):\n maxerr = np.abs(error)\n if maxerr > 1e-5:\n nifty.logger.info('\\n'.join(lines))\n else:\n nifty.logger.info(\"Max Error = %.5e\" % maxerr)\n nifty.logger.info(\"Finite-difference Finished\")\n\n def checkFiniteDifferenceHess(self, xyz):\n xyz = xyz.reshape(-1, 3)\n Analytical = self.second_derivatives(xyz)\n FiniteDifference = np.zeros_like(Analytical)\n h = 1e-4\n verbose = False\n nifty.logger.info(\"-=# Now checking second derivatives of internal coordinates w/r.t. Cartesians #=-\\n\")\n for j in range(xyz.shape[0]):\n for m in range(3):\n for k in range(xyz.shape[0]):\n for n in range(3):\n x1 = xyz.copy()\n x2 = xyz.copy()\n x3 = xyz.copy()\n x4 = xyz.copy()\n x1[j, m] += h\n x1[k, n] += h # (+, +)\n x2[j, m] += h\n x2[k, n] -= h # (+, -)\n x3[j, m] -= h\n x3[k, n] += h # (-, +)\n x4[j, m] -= h\n x4[k, n] -= h # (-, -)\n PMDiff1 = self.calcDiff(x1, x2)\n PMDiff2 = self.calcDiff(x4, x3)\n FiniteDifference[:, j, m, k, n] += (PMDiff1+PMDiff2)/(4*h**2)\n # print('\\r%i %i' % (j, k), end='')\n # print()\n for i in range(Analytical.shape[0]):\n title = \"%20s : %20s\" % (\"IC %i/%i\" % (i+1, Analytical.shape[0]), self.Internals[i])\n lines = [title]\n if verbose:\n logger.info(title+'\\n')\n maxerr = 0.0\n numerr = 0\n for j in range(Analytical.shape[1]):\n for m in range(Analytical.shape[2]):\n for k in range(Analytical.shape[3]):\n for n in range(Analytical.shape[4]):\n ana = Analytical[i, j, m, k, n]\n fin = FiniteDifference[i, j, m, k, n]\n error = ana - fin\n message = \"Atom %i %s %i %s a: % 12.5e n: % 12.5e e: % 12.5e %s\" % (j+1, 'xyz'[m], k+1, 'xyz'[n], ana, fin,\n error, 'X' if np.abs(error) > 1e-5 else '')\n if np.abs(error) > 1e-5:\n numerr += 1\n if (ana != 0.0 or fin != 0.0) and verbose:\n logger.info(message+'\\n')\n lines.append(message)\n if maxerr < np.abs(error):\n maxerr = np.abs(error)\n if maxerr > 1e-5 and not verbose:\n logger.info('\\n'.join(lines)+'\\n')\n logger.info(\"%s : Max Error = % 12.5e (%i above threshold)\\n\" % (title, maxerr, numerr))\n logger.info(\"Finite-difference Finished\\n\")\n return FiniteDifference\n\n def calcGrad(self, xyz, gradx, frozen_atoms=None):\n Ginv = self.GInverse(xyz)\n Bmat = self.wilsonB(xyz)\n\n # Internal coordinate gradient\n return block_matrix.dot(Ginv, block_matrix.dot(Bmat, gradx))\n\n def calcHess(self, xyz, gradx, hessx):\n \"\"\"\n Compute the internal coordinate Hessian. \n Expects Cartesian coordinates to be provided in a.u.\n \"\"\"\n # xyz = xyz.flatten()\n # self.calculate(xyz)\n # Ginv = self.GInverse(xyz)\n # Bmat = self.wilsonB(xyz)\n # Gq = self.calcGrad(xyz, gradx)\n # deriv2 = self.second_derivatives(xyz)\n # Bmatp = deriv2.reshape(deriv2.shape[0], xyz.shape[0], xyz.shape[0])\n # Hx_BptGq = hessx - np.einsum('pmn,p->mn', Bmatp, Gq)\n # Hq = np.einsum('ps,sm,mn,nr,rq', Ginv, Bmat, Hx_BptGq, Bmat.T, Ginv, optimize=True)\n # return Hq\n\n q0 = self.calculate(xyz)\n Ginv = self.GInverse(xyz)\n Ginv = block_matrix.full_matrix(Ginv)\n Bmat = self.wilsonB(xyz)\n Bmat = block_matrix.full_matrix(Bmat)\n\n # np.einsum('pmn,p->mn',Bmatp,Gq)\n BptGq = self.calcCg(xyz,gradx)\n Hx_BptGq = hessx - BptGq \n\n Hq = np.einsum('ps,sm,mn,nr,rq', Ginv, Bmat, Hx_BptGq, Bmat.T, Ginv, optimize=True)\n return Hq\n\n def readCache(self, xyz, dQ):\n if not hasattr(self, 'stored_xyz'):\n return None\n if np.linalg.norm(self.stored_xyz - xyz) < 1e-10:\n if np.linalg.norm(self.stored_dQ - dQ) < 1e-10:\n return self.stored_newxyz\n return None\n\n def writeCache(self, xyz, dQ, newxyz):\n # xyz = xyz.flatten()\n # dQ = dQ.flatten()\n # newxyz = newxyz.flatten()\n self.stored_xyz = xyz.copy()\n self.stored_dQ = dQ.copy()\n self.stored_newxyz = newxyz.copy()\n \n def newCartesian(self, xyz, dQ, frozen_atoms=None, verbose=True):\n cached = self.readCache(xyz, dQ)\n if cached is not None:\n # print \"Returning cached result\"\n return cached\n xyz1 = xyz.copy()\n dQ1 = dQ.flatten()\n # Iterate until convergence:\n microiter = 0\n ndqs = []\n ndqt = 100.\n rmsds = []\n self.bork = False\n # Damping factor\n damp = 1.0\n \n # Function to exit from loop\n def finish(microiter, rmsdt, ndqt, xyzsave, xyz_iter1):\n if ndqt > 1e-1:\n if verbose:\n nifty.logger.info(\" Failed to obtain coordinates after %i microiterations (rmsd = %.3e |dQ| = %.3e)\\n\" % (microiter, rmsdt, ndqt))\n self.bork = True\n self.writeCache(xyz, dQ, xyz_iter1)\n return xyzsave.reshape((-1, 3))\n elif ndqt > 1e-3:\n if verbose:\n nifty.logger.info(\" Approximate coordinates obtained after %i microiterations (rmsd = %.3e |dQ| = %.3e)\\n\" % (microiter, rmsdt, ndqt))\n else:\n if verbose:\n nifty.logger.info(\" Cartesian coordinates obtained after %i microiterations (rmsd = %.3e |dQ| = %.3e)\\n\" % (microiter, rmsdt, ndqt))\n self.writeCache(xyz, dQ, xyzsave)\n return xyzsave.reshape((-1, 3))\n\n fail_counter = 0\n while True:\n microiter += 1\n Bmat = self.wilsonB(xyz1)\n Ginv = self.GInverse(xyz1)\n\n # Get new Cartesian coordinates\n dxyz = damp*block_matrix.dot(block_matrix.transpose(Bmat), block_matrix.dot(Ginv, dQ1))\n\n if frozen_atoms is not None:\n for a in [3*i for i in frozen_atoms]:\n dxyz[a:a+3] = 0.\n\n xyz2 = xyz1 + dxyz.reshape((-1, 3))\n if microiter == 1:\n xyzsave = xyz2.copy()\n xyz_iter1 = xyz2.copy()\n # Calculate the actual change in internal coordinates\n dQ_actual = self.calcDiff(xyz2, xyz1)\n rmsd = np.sqrt(np.mean((np.array(xyz2-xyz1).flatten())**2))\n ndq = np.linalg.norm(dQ1-dQ_actual)\n if len(ndqs) > 0:\n if ndq > ndqt:\n if verbose:\n nifty.logger.info(\" Iter: %i Err-dQ (Best) = %.5e (%.5e) RMSD: %.5e Damp: %.5e (Bad)\\n\" % (microiter, ndq, ndqt, rmsd, damp))\n damp /= 2\n fail_counter += 1\n # xyz2 = xyz1.copy()\n else:\n if verbose:\n nifty.logger.info(\" Iter: %i Err-dQ (Best) = %.5e (%.5e) RMSD: %.5e Damp: %.5e (Good)\\n\" % (microiter, ndq, ndqt, rmsd, damp))\n fail_counter = 0\n damp = min(damp*1.2, 1.0)\n rmsdt = rmsd\n ndqt = ndq\n xyzsave = xyz2.copy()\n else:\n if verbose:\n nifty.logger.info(\" Iter: %i Err-dQ = %.5e RMSD: %.5e Damp: %.5e\\n\" % (microiter, ndq, rmsd, damp))\n rmsdt = rmsd\n ndqt = ndq\n ndqs.append(ndq)\n rmsds.append(rmsd)\n # Check convergence / fail criteria\n if rmsd < 1e-6 or ndq < 1e-6:\n return finish(microiter, rmsdt, ndqt, xyzsave, xyz_iter1)\n if fail_counter >= 5:\n return finish(microiter, rmsdt, ndqt, xyzsave, xyz_iter1)\n if microiter == 50:\n return finish(microiter, rmsdt, ndqt, xyzsave, xyz_iter1)\n # Figure out the further change needed\n dQ1 = dQ1 - dQ_actual\n xyz1 = xyz2.copy()\n"
] |
[
[
"numpy.diag",
"numpy.dot",
"numpy.linalg.svd",
"numpy.random.random",
"numpy.abs",
"numpy.einsum",
"numpy.linalg.inv",
"numpy.linalg.multi_dot",
"numpy.linalg.norm",
"numpy.zeros_like",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
chriscab83/CarND-Semantic-Segmentation
|
[
"8fcfa05dfe22ac9fcbabe2ee4a7889b61c9d58b4"
] |
[
"main.py"
] |
[
"import os.path\nimport tensorflow as tf\nimport helper\nimport warnings\nfrom distutils.version import LooseVersion\nimport project_tests as tests\n\n\n# Check TensorFlow Version\nassert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__)\nprint('TensorFlow Version: {}'.format(tf.__version__))\n\n# Check for a GPU\nif not tf.test.gpu_device_name():\n warnings.warn('No GPU found. Please use a GPU to train your neural network.')\nelse:\n print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))\n\n\ndef load_vgg(sess, vgg_path):\n \"\"\"\n Load Pretrained VGG Model into TensorFlow.\n :param sess: TensorFlow Session\n :param vgg_path: Path to vgg folder, containing \"variables/\" and \"saved_model.pb\"\n :return: Tuple of Tensors from VGG model (image_input, keep_prob, layer3_out, layer4_out, layer7_out)\n \"\"\"\n # TODO: Implement function\n # Use tf.saved_model.loader.load to load the model and weights\n vgg_tag = 'vgg16'\n vgg_input_tensor_name = 'image_input:0'\n vgg_keep_prob_tensor_name = 'keep_prob:0'\n vgg_layer3_out_tensor_name = 'layer3_out:0'\n vgg_layer4_out_tensor_name = 'layer4_out:0'\n vgg_layer7_out_tensor_name = 'layer7_out:0'\n\n tf.saved_model.loader.load(sess, [vgg_tag], vgg_path)\n\n graph = tf.get_default_graph()\n input_layer = graph.get_tensor_by_name(vgg_input_tensor_name)\n keep_prob = graph.get_tensor_by_name(vgg_keep_prob_tensor_name)\n layer3_out = graph.get_tensor_by_name(vgg_layer3_out_tensor_name)\n layer4_out = graph.get_tensor_by_name(vgg_layer4_out_tensor_name)\n layer7_out = graph.get_tensor_by_name(vgg_layer7_out_tensor_name)\n\n return input_layer, keep_prob, layer3_out, layer4_out, layer7_out\ntests.test_load_vgg(load_vgg, tf)\n\n\ndef layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes):\n \"\"\"\n Create the layers for a fully convolutional network. Build skip-layers using the vgg layers.\n :param vgg_layer3_out: TF Tensor for VGG Layer 3 output\n :param vgg_layer4_out: TF Tensor for VGG Layer 4 output\n :param vgg_layer7_out: TF Tensor for VGG Layer 7 output\n :param num_classes: Number of classes to classify\n :return: The Tensor for the last layer of output\n \"\"\"\n # TODO: Implement function\n conv_1x1_7 = tf.layers.conv2d(\n vgg_layer7_out, \n num_classes, \n 1, \n padding='same',\n kernel_initializer=tf.random_normal_initializer(stddev=0.01),\n kernel_regularizer=tf.contrib.layers.l2_regularizer(1e-3))\n\n upsample_1 = tf.layers.conv2d_transpose(\n conv_1x1_7, \n num_classes, \n 4, \n strides=(2,2), \n padding='same',\n kernel_initializer=tf.random_normal_initializer(stddev=0.01),\n kernel_regularizer=tf.contrib.layers.l2_regularizer(1e-3))\n \n conv_1x1_4 = tf.layers.conv2d(\n vgg_layer4_out, \n num_classes, \n 1, \n padding='same',\n kernel_initializer=tf.random_normal_initializer(stddev=0.01),\n kernel_regularizer=tf.contrib.layers.l2_regularizer(1e-3))\n\n skip_1 = tf.add(upsample_1, conv_1x1_4)\n\n upsample_2 = tf.layers.conv2d_transpose(\n skip_1,\n num_classes,\n 4, \n strides=(2,2), \n padding='same',\n kernel_initializer=tf.random_normal_initializer(stddev=0.01),\n kernel_regularizer=tf.contrib.layers.l2_regularizer(1e-3))\n\n conv_1x1_3 = tf.layers.conv2d(\n vgg_layer3_out,\n num_classes,\n 1,\n padding='same',\n kernel_initializer=tf.random_normal_initializer(stddev=0.01),\n kernel_regularizer=tf.contrib.layers.l2_regularizer(1e-3))\n\n skip_2 = tf.add(upsample_2, conv_1x1_3)\n\n upsample_3 = tf.layers.conv2d_transpose(\n skip_2,\n num_classes,\n 16,\n strides=(8,8),\n padding='same',\n kernel_initializer=tf.random_normal_initializer(stddev=0.01),\n kernel_regularizer=tf.contrib.layers.l2_regularizer(1e-3))\n\n return upsample_3\ntests.test_layers(layers)\n\n\ndef optimize(nn_last_layer, correct_label, learning_rate, num_classes):\n \"\"\"\n Build the TensorFLow loss and optimizer operations.\n :param nn_last_layer: TF Tensor of the last layer in the neural network\n :param correct_label: TF Placeholder for the correct label image\n :param learning_rate: TF Placeholder for the learning rate\n :param num_classes: Number of classes to classify\n :return: Tuple of (logits, train_op, cross_entropy_loss)\n \"\"\"\n # TODO: Implement function\n\n logits = tf.reshape(nn_last_layer, (-1, num_classes))\n correct_label = tf.reshape(correct_label, (-1, num_classes))\n\n cross_entropy_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=correct_label))\n\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n\n train_op = optimizer.minimize(cross_entropy_loss)\n\n return logits, train_op, cross_entropy_loss\ntests.test_optimize(optimize)\n\n\ndef train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image,\n correct_label, keep_prob, learning_rate):\n \"\"\"\n Train neural network and print out the loss during training.\n :param sess: TF Session\n :param epochs: Number of epochs\n :param batch_size: Batch size\n :param get_batches_fn: Function to get batches of training data. Call using get_batches_fn(batch_size)\n :param train_op: TF Operation to train the neural network\n :param cross_entropy_loss: TF Tensor for the amount of loss\n :param input_image: TF Placeholder for input images\n :param correct_label: TF Placeholder for label images\n :param keep_prob: TF Placeholder for dropout keep probability\n :param learning_rate: TF Placeholder for learning rate\n \"\"\"\n # TODO: Implement function\n print(\"Training.\\n\")\n\n sess.run(tf.global_variables_initializer())\n\n for epoch in range(epochs):\n print(\"Epoch: {}/{}......\".format(epoch, epochs))\n for image, label in get_batches_fn(batch_size):\n _, loss = sess.run([train_op, cross_entropy_loss],\n feed_dict= {\n input_image: image,\n correct_label: label,\n keep_prob: 0.5,\n learning_rate: 0.00001\n }\n )\n print(\"Loss: {}\".format(loss))\n pass\ntests.test_train_nn(train_nn)\n\n\ndef run():\n num_classes = 2\n image_shape = (160, 576)\n data_dir = './data'\n runs_dir = './runs'\n tests.test_for_kitti_dataset(data_dir)\n\n # Download pretrained vgg model\n helper.maybe_download_pretrained_vgg(data_dir)\n\n # OPTIONAL: Train and Inference on the cityscapes dataset instead of the Kitti dataset.\n # You'll need a GPU with at least 10 teraFLOPS to train on.\n # https://www.cityscapes-dataset.com/\n\n with tf.Session() as sess:\n # Path to vgg model\n vgg_path = os.path.join(data_dir, 'vgg')\n # Create function to get batches\n get_batches_fn = helper.gen_batch_function(os.path.join(data_dir, 'data_road/training'), image_shape)\n\n # OPTIONAL: Augment Images for better results\n # https://datascience.stackexchange.com/questions/5224/how-to-prepare-augment-images-for-neural-network\n\n # TODO: Build NN using load_vgg, layers, and optimize function\n\n epochs = 30\n batch_size = 10\n\n correct_label = tf.placeholder(tf.int32, [None, None, None, num_classes], name='correct_label')\n learning_rate = tf.placeholder(tf.float32, name='learning_rate')\n\n input_image, keep_prob, layer3_out, layer4_out, layer7_out = load_vgg(sess, vgg_path)\n layer_output = layers(layer3_out, layer4_out, layer7_out, num_classes)\n\n logits, train_op, cross_entropy_loss = optimize(layer_output, correct_label, learning_rate, num_classes)\n\n # TODO: Train NN using the train_nn function\n\n train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, \n input_image, correct_label, keep_prob, learning_rate)\n\n # TODO: Save inference data using helper.save_inference_samples\n helper.save_inference_samples(runs_dir, data_dir, sess, image_shape, logits, keep_prob, input_image)\n\n # OPTIONAL: Apply the trained model to a video\n\nif __name__ == '__main__':\n run()\n"
] |
[
[
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.test.gpu_device_name",
"tensorflow.reshape",
"tensorflow.placeholder",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.global_variables_initializer",
"tensorflow.add",
"tensorflow.train.AdamOptimizer",
"tensorflow.Session",
"tensorflow.get_default_graph",
"tensorflow.random_normal_initializer",
"tensorflow.saved_model.loader.load"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
math2peters/CastleSerialLink
|
[
"70d4792b9555df52f5d1237b7a0c9f2f0bed7a53"
] |
[
"CastleSerialLinkControl.py"
] |
[
"import numpy as np\n\nclass SerialLink():\n \"\"\"\n Class to communicate with castle serial link, takes Pyserial Serial class in constructor\n \"\"\"\n\n\n def __init__(self, serial, device_id=0):\n \"\"\"\n :param serial: Pyserial Serial class\n :param device_id: number between 0-63 associate with serial link address\n\n \"\"\"\n\n assert isinstance(device_id, int)\n assert 0 <= device_id < 64\n\n # assign class, default baudrate is 9600 and device id is 0 on the serial link\n self.serial_link = serial\n\n self.device_id = device_id\n\n # Addresses for registers, taken from serial link manual\n self.register_dictionary = {\"voltage\": 0, \"ripple\": 1, \"current\": 2, \"throttle\": 3, \"power\": 4, \"speed\": 5,\n \"temp\": 6, \"BEC voltage\": 7, \"BEC current\": 8, \"Raw NTC\": 9, \"RAW linear\": 10,\n \"link live\": 25, \"fail safe\": 26, \"e stop\": 27, \"packet in\": 28, \"packet out\": 29,\n \"check bad\": 30, \"packet bad\": 31, \"write throttle\": 128, \"write fail safe\": 129,\n \"write e stop\": 130, \"write packet in\": 131, \"write packet out\": 132,\n \"write check bad\": 133, \"write packet bad\": 134\n }\n\n # Scales for converting from bytes to integers, taken from serial link manual. -1 means do not scale\n self.scale_dictionary = {\"voltage\": 20.0, \"ripple\": 4.0, \"current\": 50.0, \"throttle\": 1.0, \"power\": 0.2502,\n \"speed\": 20416.66, \"temp\": 30.0, \"BEC voltage\": 4.0, \"BEC current\": 4.0 ,\n \"Raw NTC\": 63.8125, \"RAW linear\": 30.0, \"link live\": -1, \"fail safe\": -1,\n \"e stop\": -1, \"packet in\": -1, \"packet out\": -1, \"check bad\": -1, \"packet bad\": -1,\n }\n\n\n def calc_checksum(self, rsp):\n \"\"\"\n Verify the incoming checksum from the serial link\n :param rsp: a byte array, has shape (3,). The first two values are read, and the -1 value is the checksum\n :return: True if checksum is valid, false if not\n \"\"\"\n\n intlist = [int(a) for a in rsp]\n\n # Calculate the checksum\n if np.sum(intlist) % 256 == 0:\n return True\n else:\n return False\n\n def append_checksum(self, array):\n \"\"\"\n array is list of size 4. Appends the checksum of the first 4 bytes to the end of the list\n :param array: a list of size 4, contains the command we are writing the the serial link\n :return: array with the checksum\n \"\"\"\n\n array.append((0 - np.sum(array)) % 256)\n return array\n\n def convert_response(self, var, rsp):\n \"\"\"\n :param var: The variable we requested, e.g. \"voltage\"\n :param rsp: the 3-byte response of the serial link. The last byte is a checksum\n :return: The converted response\n \"\"\"\n\n # extract the values from the byte array\n values = rsp[:2]\n\n # get the the scale to multiply the values by\n scale = self.scale_dictionary[var]\n\n # if scale = -1, there is no scale associated with it in the manual\n if scale == -1:\n return values[0] * 256 + values[1]\n else:\n return (values[0] * 256 + values[1]) * scale / 2042.0\n\n\n def write_var(self, var, s):\n \"\"\"\n Sends a command to the serial link\n :param var: the register to write to, e.g. \"speed\"\n :param s: integer between 0 and 65535 to write to the register\n :return: the response of the serial link, which is just confirmation of the command we sent\n with a checksum appended. This does not contain new information\n \"\"\"\n assert 0 <= s < 256**2\n assert isinstance(s, int)\n\n # the list of bytes (as integers) to write to the serial link\n # byte 1 is the device address, always starts with 1xxxxxxx hence the 128\n # byte 2 is the register address\n # bytes 3-4 are the values to be written to the register\n # byte 5 is a checksum\n write_array = [128 + self.device_id,\n self.register_dictionary[var],\n int(s // 256), s % 256]\n\n write_array = self.append_checksum(write_array)\n\n self.serial_link.write(write_array)\n\n # 3 byte response from serial link confirming command was sent\n rsp = self.serial_link.read(3)\n return rsp\n\n def read_var(self, var):\n \"\"\"\n Reads a value from the serial link register\n :param var: the register to read from, e.g. \"speed\"\n :return: the 3-byte response of the serial link\n \"\"\"\n\n # byte 1 is the device address, always starts with 1xxxxxxx hence the 128\n # byte 2 is the register address\n # bytes 3-4 are ignored by the serial link since we are reading\n # byte 5 is a checksum\n read_array = [128 + self.device_id,\n self.register_dictionary[var],\n 0, 0]\n read_array = self.append_checksum(read_array)\n\n\n self.serial_link.write(read_array)\n rsp = self.serial_link.read(3)\n\n # check that the response is indeed 3 bytes and that the checksum is correct\n if len(rsp) == 3 and self.calc_checksum(rsp):\n return self.convert_response(var, rsp)\n\n else:\n raise Exception(\"Invalid response from serial link. The response was: {}\".format(rsp))\n"
] |
[
[
"numpy.sum"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Binjie-Qin/SVS-net
|
[
"00ae880143f2c84e600ce1638d2c2fa5e892e24d"
] |
[
"src/data_feed.py"
] |
[
"\r\nimport time\r\nimport numpy as np\r\nimport random\r\nimport scipy as sp\r\nimport scipy.interpolate\r\nimport scipy.ndimage\r\nimport scipy.ndimage.interpolation\r\nimport random\r\nimport h5py\r\nimport pylab as py\r\nimport matplotlib.pyplot as plt\r\nfrom skimage import transform\r\nimport random\r\nimport cv2\r\nplt.switch_backend('agg')\r\nINTENSITY_FACTOR = 0.2\r\nVECTOR_FIELD_SIGMA = 5. # in pixel\r\nROTATION_FACTOR = 10 # degree\r\nTRANSLATION_FACTOR = 0.2 # proportion of the image size\r\nSHEAR_FACTOR = 2 * np.pi / 180 # in radian\r\nZOOM_FACTOR = 0.1\r\n\r\n\r\ndef flip_axis(x, axis):\r\n x = np.asarray(x).swapaxes(axis, 0)\r\n x = x[::-1, ...]\r\n x = x.swapaxes(0, axis)\r\n return x\r\n\r\n\r\ndef random_channel_shift(x1,x2,x3,x4, intensity, channel_index=0):\r\n x1 = np.rollaxis(x1, channel_index, 0)\r\n x2 = np.rollaxis(x2, channel_index, 0)\r\n x3 = np.rollaxis(x3, channel_index, 0)\r\n x4 = np.rollaxis(x4, channel_index, 0)\r\n min_x1, max_x1 = np.min(x1), np.max(x1)\r\n min_x2, max_x2 = np.min(x2), np.max(x2)\r\n min_x3, max_x3 = np.min(x3), np.max(x3)\r\n min_x4, max_x4 = np.min(x4), np.max(x4)\r\n shift = np.random.uniform(-intensity, intensity) # TODO add a choice if we want the same shift for all channels\r\n channel_images1 = [np.clip(x_channel + shift, min_x1, max_x1)\r\n for x_channel in x1]\r\n channel_images2 = [np.clip(x_channel + shift, min_x2, max_x2)\r\n for x_channel in x2]\r\n channel_images3 = [np.clip(x_channel + shift, min_x3, max_x3)\r\n for x_channel in x3]\r\n channel_images4 = [np.clip(x_channel + shift, min_x4, max_x4)\r\n for x_channel in x4]\r\n\r\n x1 = np.stack(channel_images1, axis=0)\r\n x1 = np.rollaxis(x1, 0, channel_index + 1)\r\n x2 = np.stack(channel_images2, axis=0)\r\n x2 = np.rollaxis(x2, 0, channel_index + 1)\r\n x3 = np.stack(channel_images3, axis=0)\r\n x3 = np.rollaxis(x3, 0, channel_index + 1)\r\n x4 = np.stack(channel_images4, axis=0)\r\n x4 = np.rollaxis(x4, 0, channel_index + 1)\r\n\r\n return x1,x2,x3,x4\r\n\r\ndef apply_transform(x, transform_matrix, channel_index=0, fill_mode='nearest', cval=0.):\r\n x = np.rollaxis(x, channel_index, 0)\r\n final_affine_matrix = transform_matrix[:2, :2]\r\n final_offset = transform_matrix[:2, 2]\r\n channel_images = [sp.ndimage.interpolation.affine_transform(x_channel, final_affine_matrix,\r\n final_offset, order=0, mode=fill_mode, cval=cval) for\r\n x_channel in x]\r\n x = np.stack(channel_images, axis=0)\r\n x = np.rollaxis(x, 0, channel_index + 1)\r\n return x\r\n\r\n\r\ndef transform_matrix_offset_center(matrix, x, y):\r\n o_x = float(x) / 2 + 0.5\r\n o_y = float(y) / 2 + 0.5\r\n offset_matrix = np.array([[1, 0, o_x], [0, 1, o_y], [0, 0, 1]])\r\n reset_matrix = np.array([[1, 0, -o_x], [0, 1, -o_y], [0, 0, 1]])\r\n transform_matrix = np.dot(np.dot(offset_matrix, matrix), reset_matrix)\r\n return transform_matrix\r\n\r\n\r\n\r\ndef train_generator(_X, _Y,_batchSize, iter_times, _keepPctOriginal=0.5, _intensity=INTENSITY_FACTOR, _hflip=True, _vflip=True):\r\n n_data=_X.shape[0]\r\n shapeX = _X.shape\r\n shapeY = _Y.shape\r\n currentBatch=0\r\n while 1:\r\n index=np.random.permutation(n_data)\r\n X=_X[index,:,:,:,:]\r\n Y=_Y[index,:,:,:]\r\n X=np.transpose(X,(0,2,1,3,4))\r\n for i in range(iter_times):\r\n if currentBatch == 0:\r\n x = np.empty((_batchSize, 1, shapeX[2], shapeX[3], shapeX[4]), dtype=np.float32)\r\n y = np.empty((_batchSize, 1, shapeY[2], shapeY[3]), dtype=np.float32)\r\n index_list = random.randint(0, n_data - 1)\r\n img_x = np.empty((shapeX[2], 1, shapeX[3], shapeX[4]), dtype=np.float32)\r\n img_x1 = X[index_list][0]\r\n img_x2 = X[index_list][1]\r\n img_x3 = X[index_list][2]\r\n img_x4 = X[index_list][3]\r\n img_y = Y[index_list]\r\n if random.random() > _keepPctOriginal:\r\n if _intensity != 0:\r\n img_x1, img_x2, img_x3, img_x4 = random_channel_shift(img_x1, img_x2, img_x3, img_x4, _intensity)\r\n if _hflip == True and random.random() > 0.5:\r\n img_x1 = flip_axis(img_x1, 1)\r\n img_x2 = flip_axis(img_x2, 1)\r\n img_x3 = flip_axis(img_x3, 1)\r\n img_x4 = flip_axis(img_x4, 1)\r\n\r\n img_y = flip_axis(img_y, 1)\r\n\r\n if _vflip == True and random.random() > 0.5:\r\n img_x1 = flip_axis(img_x1, 2)\r\n img_x2 = flip_axis(img_x2, 2)\r\n img_x3 = flip_axis(img_x3, 2)\r\n img_x4 = flip_axis(img_x4, 2)\r\n img_y = flip_axis(img_y, 2)\r\n\r\n if random.random() > 0.5:\r\n angle = np.random.randint(-10, 10)\r\n img_x1 = np.reshape(transform.rotate(np.reshape(img_x1, [512, 512]), angle), [1, 512, 512])\r\n img_x2 = np.reshape(transform.rotate(np.reshape(img_x2, [512, 512]), angle), [1, 512, 512])\r\n img_x3 = np.reshape(transform.rotate(np.reshape(img_x3, [512, 512]), angle), [1, 512, 512])\r\n img_x4 = np.reshape(transform.rotate(np.reshape(img_x4, [512, 512]), angle), [1, 512, 512])\r\n img_y = np.reshape(transform.rotate(np.reshape(img_y, [512, 512]), angle), [1, 512, 512])\r\n\r\n if random.random() > 0.5:\r\n crop_size = [400, 400]\r\n w_s = random.randint(0, 512 - crop_size[1])\r\n h_s = random.randint(0, 512 - crop_size[0])\r\n img1_ = np.reshape(img_x1, [512, 512])[h_s:h_s + crop_size[0], w_s:w_s + crop_size[1]]\r\n img2_ = np.reshape(img_x2, [512, 512])[h_s:h_s + crop_size[0], w_s:w_s + crop_size[1]]\r\n img3_ = np.reshape(img_x3, [512, 512])[h_s:h_s + crop_size[0], w_s:w_s + crop_size[1]]\r\n img4_ = np.reshape(img_x4, [512, 512])[h_s:h_s + crop_size[0], w_s:w_s + crop_size[1]]\r\n imgy_ = np.reshape(img_y, [512, 512])[h_s:h_s + crop_size[0], w_s:w_s + crop_size[1]]\r\n # print(img1_.shape)\r\n\r\n img_x1 = transform.resize(img1_, (512, 512))\r\n img_x2 = transform.resize(img2_, (512, 512))\r\n img_x3 = transform.resize(img3_, (512, 512))\r\n img_x4 = transform.resize(img4_, (512, 512))\r\n img_y = transform.resize(imgy_, (512, 512))\r\n\r\n img_x1 = np.reshape(img_x1, [1, 512, 512])\r\n img_x2 = np.reshape(img_x2, [1, 512, 512])\r\n img_x3 = np.reshape(img_x3, [1, 512, 512])\r\n img_x4 = np.reshape(img_x4, [1, 512, 512])\r\n img_y = np.reshape(img_y, [1, 512, 512])\r\n if random.random() > 0.5:\r\n zoom_factor = 0.2\r\n z_x, z_y = np.random.uniform(1 - zoom_factor, 1 + zoom_factor, 2)\r\n t_x = np.random.uniform(-0.2, 0.2) * 512\r\n t_y = np.random.uniform(-0.2, 0.2) * 512\r\n\r\n M = np.float32([[z_x, 0, t_x], [0, z_y, t_y]])\r\n\r\n img1_ = np.reshape(img_x1, [512, 512])\r\n img2_ = np.reshape(img_x2, [512, 512])\r\n img3_ = np.reshape(img_x3, [512, 512])\r\n img4_ = np.reshape(img_x4, [512, 512])\r\n imgy_ = np.reshape(img_y, [512, 512])\r\n dst1 = cv2.warpAffine(img1_, M, (512, 512))\r\n dst2 = cv2.warpAffine(img2_, M, (512, 512))\r\n dst3 = cv2.warpAffine(img3_, M, (512, 512))\r\n dst4 = cv2.warpAffine(img4_, M, (512, 512))\r\n dsty = cv2.warpAffine(imgy_, M, (512, 512))\r\n\r\n img_x1 = np.reshape(dst1, [1, 512, 512])\r\n img_x2 = np.reshape(dst2, [1, 512, 512])\r\n img_x3 = np.reshape(dst3, [1, 512, 512])\r\n img_x4 = np.reshape(dst4, [1, 512, 512])\r\n img_y = np.reshape(dsty, [1, 512, 512])\r\n if random.random() > 0.5:\r\n _shear = 2 * np.pi / 180\r\n shear = np.random.uniform(-_shear, _shear)\r\n shear_matrix = np.array([[np.cos(shear), 0, 0],\r\n [-np.sin(shear), 1, 0]])\r\n\r\n img1_ = np.reshape(img_x1, [512, 512])\r\n img2_ = np.reshape(img_x2, [512, 512])\r\n img3_ = np.reshape(img_x3, [512, 512])\r\n img4_ = np.reshape(img_x4, [512, 512])\r\n imgy_ = np.reshape(img_y, [512, 512])\r\n dst1 = cv2.warpAffine(img1_, shear_matrix, (512, 512))\r\n dst2 = cv2.warpAffine(img2_, shear_matrix, (512, 512))\r\n dst3 = cv2.warpAffine(img3_, shear_matrix, (512, 512))\r\n dst4 = cv2.warpAffine(img4_, shear_matrix, (512, 512))\r\n dsty = cv2.warpAffine(imgy_, shear_matrix, (512, 512))\r\n\r\n img_x1 = np.reshape(dst1, [1, 512, 512])\r\n img_x2 = np.reshape(dst2, [1, 512, 512])\r\n img_x3 = np.reshape(dst3, [1, 512, 512])\r\n img_x4 = np.reshape(dst4, [1, 512, 512])\r\n img_y = np.reshape(dsty, [1, 512, 512])\r\n img_x[0] = img_x1[...]\r\n img_x[1] = img_x2[...]\r\n img_x[2] = img_x3[...]\r\n img_x[3] = img_x4[...]\r\n img_x = np.transpose(img_x, (1, 0, 2, 3))\r\n x[currentBatch][...] = img_x[...]\r\n y[currentBatch][...] = img_y[...]\r\n currentBatch += 1\r\n\r\n if currentBatch==_batchSize:\r\n currentBatch=0\r\n yield (x,y)\r\n elif i ==iter_times-1:\r\n yield (x[:currentBatch], y[:currentBatch])\r\n currentBatch = 0\r\n\r\ndef validation_generator(_X, _Y,_batchSize):\r\n n_data = _X.shape[0]\r\n shapeX = _X.shape\r\n shapeY = _Y.shape\r\n currentBatch = 0\r\n index = np.random.permutation(n_data)\r\n X = _X[index, :, :, :,:]\r\n Y = _Y[index, :, :, :]\r\n while 1:\r\n for i in range(n_data):\r\n if currentBatch == 0:\r\n x = np.empty((_batchSize, 1, shapeX[2], shapeX[3],shapeX[4]), dtype=np.float32)\r\n y = np.empty((_batchSize, 1, shapeY[2], shapeY[3]), dtype=np.float32)\r\n index_list = random.randint(0, n_data-1)\r\n img_x = X[index_list]\r\n img_y = Y[index_list]\r\n\r\n x[currentBatch][...] = img_x[...]\r\n y[currentBatch][...] = img_y[...]\r\n currentBatch += 1\r\n if currentBatch == _batchSize:\r\n currentBatch = 0\r\n yield (x, y)\r\n elif i==n_data-1:\r\n yield (x[:currentBatch], y[:currentBatch])\r\n currentBatch = 0\r\n\r\n"
] |
[
[
"numpy.rollaxis",
"numpy.dot",
"numpy.asarray",
"numpy.max",
"numpy.random.randint",
"numpy.clip",
"numpy.reshape",
"numpy.stack",
"numpy.sin",
"numpy.float32",
"scipy.ndimage.interpolation.affine_transform",
"numpy.min",
"matplotlib.pyplot.switch_backend",
"numpy.transpose",
"numpy.array",
"numpy.cos",
"numpy.random.permutation",
"numpy.random.uniform",
"numpy.empty"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"0.15",
"1.4",
"0.16",
"1.0",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"0.10",
"0.17",
"1.3"
],
"tensorflow": []
}
] |
nadegeguiglielmoni/HapPy
|
[
"fec797800157acda4d501dc60d890b5b0bbb6bee"
] |
[
"happy/estimate.py"
] |
[
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# General\nimport os, sys, math\n\n# Happy\nfrom happy.utils import *\nfrom happy.plot import *\n\n# Stats\nfrom scipy.signal import savgol_filter # SmoothingAUC\nfrom scipy.signal import find_peaks # Finding peaks\nfrom scipy.signal import peak_widths\n\ndef estimate_haploidy(\n infile, max_cont: int, max_dip: int, size: int, outfile, plot=False, debug=False\n):\n \"\"\"Finds peaks and modality, then computes scores of haploidy\"\"\"\n\n # Get histogram file and size estimation\n HIST = check_files(infile)\n SIZE = size_from_string(size)\n\n print(\"# Hap.py estimate\")\n print(\"Coverage histogram:\\t{0}\\nOutput file:\\t{1}\\n\".format(HIST, outfile))\n print(\n \"===============================================================================\\n\"\n )\n\n # Read coverage histogram\n log(\"Reading histogram!\")\n freqs = [int(line.split()[1]) for line in open(HIST, \"r\")][1:-1]\n\n # Apply Savitzky-Golay filter to smooth coverage histogram\n log(\"Analysing curve!\")\n smoothed = [s for s in savgol_filter(freqs, 41, 3) if s >= 0]\n peaks, props = find_peaks(smoothed, height=15000, prominence=10000)\n heights = [smoothed[i] for i in peaks]\n widths = peak_widths(smoothed, peaks)[0] # Get peak widths\n\n if max_cont is None:\n max_cont = peaks[len(peaks) - 1] * 0.30\n else :\n try :\n max_cont = int(max_cont)\n except :\n raise Exception(\"ERROR: Invalid value of --max-cont!\")\n\n if max_dip is None:\n max_dip = peaks[len(peaks) - 1] * 0.55\n else :\n try :\n max_dip = int(max_dip)\n except :\n raise Exception(\"ERROR: Invalid value of --max-dip!\")\n\n if debug:\n debug_smooth_histogram(freqs, smoothed, peaks, heights, widths, os.getcwd())\n\n params, cov = None, None\n peak_ratios = None\n limits = {}\n\n if len(peaks) > 3: # In case 3+ peaks:\n peaks, heights, widths = check_peaks(\n peaks, heights, widths, len(smoothed), max_cont, max_dip\n )\n\n if len(peaks) == 0:\n log(\"No peak found.\")\n sys.exit(1)\n\n elif len(peaks) == 3: # In case 3 peaks : 1 in each category\n log(\n \"Found 3 peaks at: {0}x, {1}x and {2}x\".format(peaks[0], peaks[1], peaks[2])\n )\n haplotigs_peak_ratio = round(heights[-2] / heights[-1], 3)\n\n # For each peak pos and width\n for n, pos, width in zip(range(3), peaks, widths):\n if n == 0:\n categ = \"Contaminants\"\n elif n == 1:\n categ = \"Diploid\"\n elif n == 2:\n break\n # Store limit under the key category of the peak\n limits[categ] = math.ceil(pos + width)\n\n elif len(peaks) == 2: # If only 2 peaks\n log(\"Found 2 peaks at: {0}x and {1}x\".format(peaks[0], peaks[1]))\n # Peaks could be :\n # CONTA + HAPLO\n # CONTA + DIPLO\n # HAPLO + DIPLO\n haplotigs_peak_ratio = round(heights[-2] / heights[-1], 3)\n\n if (\n peaks[0] < max_cont\n ): # In case found contaminant <-- 2 peaks == contams and higher or lower\n limits[\"Contaminants\"] = math.ceil(peaks[0] + widths[0])\n\n if peaks[1] < max_dip: # CONTA + DIPLO\n limits[\"Diploid\"] = math.ceil(\n peaks[1] - widths[1]\n ) # diploid region is between contams and lower border of haploid peak\n else: # CONTA + HAPLO\n limits[\"Diploid\"] = math.ceil(\n peaks[1] + widths[1]\n ) # diploid region is between contams and upper border of diploid peak\n\n else: # DIPLO + HAPLO\n limits[\"Contaminants\"] = 0\n limits[\"Diploid\"] = math.ceil(peaks[0] + widths[0])\n\n elif len(peaks) == 1:\n log(\"Found 1 peak at: {}x\".format(peaks[0]))\n haplotigs_peak_ratio = 0.0\n\n if peaks[0] < max_cont: # CONTAMINANT ASM\n limits[\"Contaminants\"] = math.ceil(peaks[0] + widths[0])\n limits[\"Diploid\"] = math.ceil(peaks[0] + widths[0])\n elif peaks[0] < max_dip: # DIPLOID ASM\n limits[\"Contaminants\"] = math.ceil(peaks[0] - widths[0])\n limits[\"Diploid\"] = math.ceil(peaks[0] + widths[0])\n else: # HAPLOID ASM\n limits[\"Contaminants\"] = 0\n limits[\"Diploid\"] = math.ceil(peaks[0] - widths[0])\n\n AUC_conta = sum(smoothed[: limits[\"Contaminants\"]])\n AUC_diplo = sum(smoothed[limits[\"Contaminants\"] : limits[\"Diploid\"]])\n AUC_haplo = sum(smoothed[limits[\"Diploid\"] :])\n\n log(\"Scoring assembly...\")\n AUC_ratio = 1 - (AUC_diplo / AUC_haplo)\n Haploidy = AUC_haplo / ( (AUC_diplo)/2 + AUC_haplo )\n print(\"AUC(Haploid): H = {}\".format(AUC_haplo))\n print(\"AUC(Diploid): D = {}\".format(AUC_diplo))\n print(\"Ratio: 1-(D/H) = {}\".format(round(AUC_ratio, 3)))\n print(\"Haploidy: H/(H + (D/2)) = {}\".format(round(Haploidy, 3)))\n\n TSS = 1 - abs(SIZE - (AUC_haplo + AUC_diplo / 2)) / SIZE\n\n write_stats(outfile, AUC_haplo, AUC_diplo, AUC_ratio, Haploidy)\n\n if plot:\n log(\"Outputting plots...\")\n plot_metrics(\n outfile,\n smoothed,\n peaks,\n heights,\n limits,\n haplotigs_peak_ratio,\n AUC_ratio,\n TSS,\n AUC_conta,\n AUC_diplo,\n AUC_haplo,\n )\n\n log(\"Finished!\")\n sys.exit(0)\n\n\ndef check_peaks(peaks, heights, widths, maximum_cov: int, max_cont: int, max_dip: int):\n \"\"\"In case there are more than 3 peaks, find only the 3 highest interest peaks\"\"\"\n log(\n \"Warning: detected more than 3 peaks at: {}x and {}x\".format(\n \"x, \".join(str(peak) for peak in peaks[:-1]), peaks[-1]\n )\n )\n\n contaminant_peak, diploid_peak, haploid_peak = None, None, None\n contaminant_height, diploid_height, haploid_height = None, None, None\n contaminant_width, diploid_width, haploid_width = None, None, None\n\n # Find highest peaks\n for pos, height in zip(peaks, heights):\n if pos < max_cont :\n if contaminant_peak == None:\n contaminant_peak = pos\n contaminant_height = height\n elif height > contaminant_height:\n contaminant_peak = pos\n contaminant_height = height\n else:\n continue\n elif pos >= max_cont and pos < max_dip:\n if diploid_peak == None:\n diploid_peak = pos\n diploid_height = height\n elif height > diploid_height:\n diploid_peak = pos\n diploid_height = height\n else:\n continue\n else:\n if haploid_peak == None:\n haploid_peak = pos\n haploid_height = height\n elif height > haploid_height:\n haploid_peak = pos\n haploid_height = height\n else:\n continue\n\n # widths = general boundaries <-- may be a problem sometimes\n contaminant_width = math.floor(\n abs(max_cont - contaminant_peak)\n ) # floor of absolute distance between contaminant boundary and highest contaminant peak\n diploid_width = math.floor(\n abs(max_dip - diploid_peak)\n ) # floor of absolute distance between diploid boundary and highest diploid peak\n haploid_width = math.floor(\n abs(maximum_cov - diploid_peak)\n ) # floor of absolute distance between haploid peak and max coverage ( == len(x) == number of bins ) from the histogram\n\n newpeaks = [contaminant_peak, diploid_peak, haploid_peak]\n newheights = [contaminant_height, diploid_height, haploid_height]\n newwidths = [contaminant_width, diploid_width, haploid_width]\n return newpeaks, newheights, newwidths\n\ndef write_stats(outname: str, AUC_haplo: float, AUC_diplo: float, AUC_ratio: float,\n haploidy: float\n ):\n log(\"Outputting stats...\")\n\n f = open(outname, \"w\")\n f.write(\"AUC(Haploid) = {}\\n\".format(AUC_haplo))\n f.write(\"AUC(Diploid) = {}\\n\".format(AUC_diplo))\n f.write(\"Ratio = {}\\n\".format(AUC_ratio))\n f.write(\"Haploidy = {}\".format(haploidy))\n f.close()\n"
] |
[
[
"scipy.signal.find_peaks",
"scipy.signal.savgol_filter",
"scipy.signal.peak_widths"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.6",
"1.10",
"1.4",
"1.3",
"1.9",
"1.5",
"1.7",
"1.2",
"1.8"
],
"tensorflow": []
}
] |
Flobian/DSAMaterialNetworks
|
[
"e9628e9e72ec63ca0d228af552c6a679faf72543"
] |
[
"worksheets_English/sheet1/code/pathgraph.py"
] |
[
"# -*- coding: utf-8 -*-\r\n\r\n# import necessary library\r\nimport numpy as np\r\n\r\n# define a function \r\ndef path_graph( n ):\r\n \"\"\"\r\n Returns the (n x n) adjacency matrix \r\n of a path graph with n nodes.\r\n \"\"\"\r\n\r\n # empty adjacency matrix of shape (n x n)\r\n A = np.zeros((n,n))\r\n\r\n # loop over every node besides the last one\r\n for u in range(0, n-1):\r\n\r\n # connect this node to the subsequent one\r\n A[u,u+1] = 1\r\n\r\n A = A + np.transpose(A)\r\n\r\n # the matrix will now be returned\r\n return A\r\n\r\n# call the function to obtain an adjancency matrix\r\n# for a path graph of 10 nodes\r\npath_10 = path_graph(10)\r\n\r\n# put the matrix on screen in text\r\nprint(path_10)\r\n"
] |
[
[
"numpy.zeros",
"numpy.transpose"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ppruthi/SynapseML
|
[
"d38c82455b28585cb35f6f4386a508ff4026f1d3"
] |
[
"core/src/main/python/synapse/ml/cyber/anomaly/collaborative_filtering.py"
] |
[
"__author__ = \"rolevin\"\n\nimport os\nfrom typing import List, Optional, Tuple\n\nfrom synapse.ml.cyber.anomaly.complement_access import ComplementAccessTransformer\nfrom synapse.ml.cyber.feature import indexers, scalers\nfrom synapse.ml.cyber.utils import spark_utils\n\nimport numpy as np\n\nfrom pyspark import SQLContext # noqa\nfrom pyspark.ml import Estimator, Transformer\nfrom pyspark.ml.param.shared import Param, Params\nfrom pyspark.ml.recommendation import ALS\nfrom pyspark.sql import DataFrame, functions as f, types as t\n\n\"\"\"\nGlossary:\nthe term 'res' in this package is a shorthand for resource\n\"\"\"\n\n\ndef _make_dot():\n \"\"\"\n create a method that performs a dot product between two vectors (list of doubles)\n :return: the method\n \"\"\"\n\n @f.udf(t.DoubleType())\n def dot(v, u):\n if (v is not None) and (u is not None):\n vv = (\n np.pad(\n np.array(v), (0, len(u) - len(v)), \"constant\", constant_values=1.0\n )\n if len(v) < len(u)\n else np.array(v)\n )\n uu = (\n np.pad(\n np.array(u), (0, len(v) - len(u)), \"constant\", constant_values=1.0\n )\n if len(u) < len(v)\n else np.array(u)\n )\n\n return float(vv.dot(uu))\n else:\n return None\n\n return dot\n\n\nclass AccessAnomalyConfig:\n \"\"\"\n Define default values for AccessAnomaly Params\n \"\"\"\n\n default_tenant_col = \"tenant\"\n default_user_col = \"user\"\n default_res_col = \"res\"\n default_likelihood_col = \"likelihood\"\n default_output_col = \"anomaly_score\"\n\n default_rank = 10\n default_max_iter = 25\n default_reg_param = 1.0\n default_num_blocks = None # |tenants| if separate_tenants is False else 10\n default_separate_tenants = False\n\n default_low_value = 5.0\n default_high_value = 10.0\n\n default_apply_implicit_cf = True\n default_alpha = 1.0\n\n default_complementset_factor = 2\n default_neg_score = 1.0\n\n\nclass _UserResourceFeatureVectorMapping:\n \"\"\"\n Private class used to pass the mappings as calculated by the AccessAnomaliesEstimator.\n An object representing the user and resource models\n (mapping from name to latent vector)\n and the relevant column names\n \"\"\"\n\n def __init__(\n self,\n tenant_col: str,\n user_col: str,\n user_vec_col: str,\n res_col: str,\n res_vec_col: str,\n history_access_df: Optional[DataFrame],\n user2component_mappings_df: Optional[DataFrame],\n res2component_mappings_df: Optional[DataFrame],\n user_feature_vector_mapping_df: DataFrame,\n res_feature_vector_mapping_df: DataFrame,\n ):\n\n self.tenant_col = tenant_col\n self.user_col = user_col\n self.user_vec_col = user_vec_col\n self.res_col = res_col\n self.res_vec_col = res_vec_col\n self.history_access_df = history_access_df\n self.user2component_mappings_df = user2component_mappings_df\n self.res2component_mappings_df = res2component_mappings_df\n self.user_feature_vector_mapping_df = user_feature_vector_mapping_df\n self.res_feature_vector_mapping_df = res_feature_vector_mapping_df\n\n assert self.history_access_df is None or set(\n self.history_access_df.schema.fieldNames()\n ) == {tenant_col, user_col, res_col}, self.history_access_df.schema.fieldNames()\n\n def replace_mappings(\n self,\n user_feature_vector_mapping_df: Optional[DataFrame] = None,\n res_feature_vector_mapping_df: Optional[DataFrame] = None,\n ):\n\n \"\"\"\n create a new model replacing the user and resource models with new ones (optional)\n\n :param user_feature_vector_mapping_df: optional new user model mapping names to latent vectors\n :param res_feature_vector_mapping_df: optional new resource model mapping names to latent vectors\n :return:\n \"\"\"\n return _UserResourceFeatureVectorMapping(\n self.tenant_col,\n self.user_col,\n self.user_vec_col,\n self.res_col,\n self.res_vec_col,\n self.history_access_df,\n self.user2component_mappings_df,\n self.res2component_mappings_df,\n user_feature_vector_mapping_df\n if user_feature_vector_mapping_df is not None\n else self.user_feature_vector_mapping_df,\n res_feature_vector_mapping_df\n if res_feature_vector_mapping_df is not None\n else self.res_feature_vector_mapping_df,\n )\n\n def check(self):\n \"\"\"\n check the validity of the model\n :return: boolean value where True indicating the verification succeeded\n \"\"\"\n return self._check_user_mapping() and self._check_res_mapping()\n\n def _check_user_mapping(self):\n field_map = {\n ff.name: ff for ff in self.user_feature_vector_mapping_df.schema.fields\n }\n\n assert field_map.get(self.tenant_col) is not None, field_map\n assert field_map.get(self.user_col) is not None\n\n return (\n self.user_feature_vector_mapping_df.select(self.tenant_col, self.user_col)\n .distinct()\n .count()\n == self.user_feature_vector_mapping_df.count()\n )\n\n def _check_res_mapping(self):\n field_map = {\n ff.name: ff for ff in self.res_feature_vector_mapping_df.schema.fields\n }\n\n assert field_map.get(self.tenant_col) is not None, field_map\n assert field_map.get(self.res_col) is not None\n\n return (\n self.res_feature_vector_mapping_df.select(self.tenant_col, self.res_col)\n .distinct()\n .count()\n == self.res_feature_vector_mapping_df.count()\n )\n\n\n# noinspection PyPep8Naming\nclass AccessAnomalyModel(Transformer):\n outputCol = Param(\n Params._dummy(),\n \"outputCol\",\n \"The name of the output column representing the calculated anomaly score. \"\n \"Values will be between (-inf, +inf) with an estimated mean of 0.0 and standard deviation of 1.0. \",\n )\n\n \"\"\"\n A pyspark.ml.Transformer model that can predict anomaly scores for user, resource access pairs\n \"\"\"\n\n def __init__(\n self,\n userResourceFeatureVectorMapping: _UserResourceFeatureVectorMapping,\n outputCol: str,\n ):\n super().__init__()\n self.user_res_feature_vector_mapping = userResourceFeatureVectorMapping\n\n has_user2component_mappings = (\n self.user_res_feature_vector_mapping.user2component_mappings_df is not None\n )\n has_res2component_mappings = (\n self.user_res_feature_vector_mapping.res2component_mappings_df is not None\n )\n\n assert has_user2component_mappings == has_res2component_mappings\n\n self.has_components = has_user2component_mappings and has_res2component_mappings\n self.preserve_history = True\n\n if self.has_components:\n self._user_mapping_df = (\n self.user_res_feature_vector_mapping.user_feature_vector_mapping_df.join(\n self.user_res_feature_vector_mapping.user2component_mappings_df,\n [self.tenant_col, self.user_col],\n )\n .select(\n self.tenant_col,\n self.user_col,\n self.user_vec_col,\n f.col(\"component\").alias(\"user_component\"),\n )\n .cache()\n )\n\n self._res_mapping_df = (\n self.user_res_feature_vector_mapping.res_feature_vector_mapping_df.join(\n self.user_res_feature_vector_mapping.res2component_mappings_df,\n [self.tenant_col, self.res_col],\n )\n .select(\n self.tenant_col,\n self.res_col,\n self.res_vec_col,\n f.col(\"component\").alias(\"res_component\"),\n )\n .cache()\n )\n else:\n self._user_mapping_df = (\n self.user_res_feature_vector_mapping.user_feature_vector_mapping_df\n )\n self._res_mapping_df = (\n self.user_res_feature_vector_mapping.res_feature_vector_mapping_df\n )\n\n spark_utils.ExplainBuilder.build(self, outputCol=outputCol)\n\n @staticmethod\n def _metadata_schema() -> t.StructType:\n return t.StructType(\n [\n t.StructField(\"tenant_col\", t.StringType(), False),\n t.StructField(\"user_col\", t.StringType(), False),\n t.StructField(\"user_vec_col\", t.StringType(), False),\n t.StructField(\"res_col\", t.StringType(), False),\n t.StructField(\"res_vec_col\", t.StringType(), False),\n t.StructField(\"output_col\", t.StringType(), False),\n t.StructField(\"has_history_access_df\", t.BooleanType(), False),\n t.StructField(\"has_user2component_mappings_df\", t.BooleanType(), False),\n t.StructField(\"has_res2component_mappings_df\", t.BooleanType(), False),\n t.StructField(\n \"has_user_feature_vector_mapping_df\", t.BooleanType(), False\n ),\n t.StructField(\n \"has_res_feature_vector_mapping_df\", t.BooleanType(), False\n ),\n ]\n )\n\n def save(self, path: str, path_suffix: str = \"\", output_format: str = \"parquet\"):\n dfs = [\n self.user_res_feature_vector_mapping.history_access_df,\n self.user_res_feature_vector_mapping.user2component_mappings_df,\n self.user_res_feature_vector_mapping.res2component_mappings_df,\n self.user_res_feature_vector_mapping.user_feature_vector_mapping_df,\n self.user_res_feature_vector_mapping.res_feature_vector_mapping_df,\n ]\n\n adf = next(iter([df for df in dfs if df is not None]))\n assert adf is not None\n\n spark = spark_utils.DataFrameUtils.get_spark_session(adf)\n\n metadata_df = spark.createDataFrame(\n [\n (\n self.tenant_col,\n self.user_col,\n self.user_vec_col,\n self.res_col,\n self.res_vec_col,\n self.output_col,\n self.user_res_feature_vector_mapping.history_access_df is not None,\n self.user_res_feature_vector_mapping.user2component_mappings_df\n is not None,\n self.user_res_feature_vector_mapping.res2component_mappings_df\n is not None,\n self.user_res_feature_vector_mapping.user_feature_vector_mapping_df\n is not None,\n self.user_res_feature_vector_mapping.res_feature_vector_mapping_df\n is not None,\n )\n ],\n AccessAnomalyModel._metadata_schema(),\n )\n\n metadata_df.write.format(output_format).save(\n os.path.join(path, \"metadata_df\", path_suffix)\n )\n\n if self.user_res_feature_vector_mapping.history_access_df is not None:\n self.user_res_feature_vector_mapping.history_access_df.write.format(\n output_format\n ).save(os.path.join(path, \"history_access_df\", path_suffix))\n\n if self.user_res_feature_vector_mapping.user2component_mappings_df is not None:\n self.user_res_feature_vector_mapping.user2component_mappings_df.write.format(\n output_format\n ).save(\n os.path.join(path, \"user2component_mappings_df\", path_suffix)\n )\n\n if self.user_res_feature_vector_mapping.res2component_mappings_df is not None:\n self.user_res_feature_vector_mapping.res2component_mappings_df.write.format(\n output_format\n ).save(os.path.join(path, \"res2component_mappings_df\", path_suffix))\n\n if (\n self.user_res_feature_vector_mapping.user_feature_vector_mapping_df\n is not None\n ):\n self.user_res_feature_vector_mapping.user_feature_vector_mapping_df.write.format(\n output_format\n ).save(\n os.path.join(path, \"user_feature_vector_mapping_df\", path_suffix)\n )\n\n if (\n self.user_res_feature_vector_mapping.res_feature_vector_mapping_df\n is not None\n ):\n self.user_res_feature_vector_mapping.res_feature_vector_mapping_df.write.format(\n output_format\n ).save(\n os.path.join(path, \"res_feature_vector_mapping_df\", path_suffix)\n )\n\n @staticmethod\n def load(\n spark: SQLContext, path: str, output_format: str = \"parquet\"\n ) -> \"AccessAnomalyModel\":\n metadata_df = spark.read.format(output_format).load(\n os.path.join(path, \"metadata_df\")\n )\n assert metadata_df.count() == 1\n\n metadata_row = metadata_df.collect()[0]\n\n tenant_col = metadata_row[\"tenant_col\"]\n user_col = metadata_row[\"user_col\"]\n user_vec_col = metadata_row[\"user_vec_col\"]\n res_col = metadata_row[\"res_col\"]\n res_vec_col = metadata_row[\"res_vec_col\"]\n output_col = metadata_row[\"output_col\"]\n\n has_history_access_df = metadata_row[\"has_history_access_df\"]\n has_user2component_mappings_df = metadata_row[\"has_user2component_mappings_df\"]\n has_res2component_mappings_df = metadata_row[\"has_res2component_mappings_df\"]\n has_user_feature_vector_mapping_df = metadata_row[\n \"has_user_feature_vector_mapping_df\"\n ]\n has_res_feature_vector_mapping_df = metadata_row[\n \"has_res_feature_vector_mapping_df\"\n ]\n\n history_access_df = (\n spark.read.format(output_format).load(\n os.path.join(path, \"history_access_df\")\n )\n if has_history_access_df\n else None\n )\n\n user2component_mappings_df = (\n spark.read.format(output_format).load(\n os.path.join(path, \"user2component_mappings_df\")\n )\n if has_user2component_mappings_df\n else None\n )\n\n res2component_mappings_df = (\n spark.read.format(output_format).load(\n os.path.join(path, \"res2component_mappings_df\")\n )\n if has_res2component_mappings_df\n else None\n )\n\n user_feature_vector_mapping_df = (\n spark.read.format(output_format).load(\n os.path.join(path, \"user_feature_vector_mapping_df\")\n )\n if has_user_feature_vector_mapping_df\n else None\n )\n\n res_feature_vector_mapping_df = (\n spark.read.format(output_format).load(\n os.path.join(path, \"res_feature_vector_mapping_df\")\n )\n if has_res_feature_vector_mapping_df\n else None\n )\n\n return AccessAnomalyModel(\n _UserResourceFeatureVectorMapping(\n tenant_col,\n user_col,\n user_vec_col,\n res_col,\n res_vec_col,\n history_access_df,\n user2component_mappings_df,\n res2component_mappings_df,\n user_feature_vector_mapping_df,\n res_feature_vector_mapping_df,\n ),\n output_col,\n )\n\n @property\n def tenant_col(self):\n return self.user_res_feature_vector_mapping.tenant_col\n\n @property\n def user_col(self):\n return self.user_res_feature_vector_mapping.user_col\n\n @property\n def user_vec_col(self):\n return self.user_res_feature_vector_mapping.user_vec_col\n\n @property\n def res_col(self):\n return self.user_res_feature_vector_mapping.res_col\n\n @property\n def res_vec_col(self):\n return self.user_res_feature_vector_mapping.res_vec_col\n\n @property\n def user_mapping_df(self):\n return self._user_mapping_df\n\n @property\n def res_mapping_df(self):\n return self._res_mapping_df\n\n def _transform(self, df: DataFrame) -> DataFrame:\n dot = _make_dot()\n\n tenant_col = self.tenant_col\n user_col = self.user_col\n user_vec_col = self.user_vec_col\n res_col = self.res_col\n res_vec_col = self.res_vec_col\n output_col = self.output_col\n\n seen_token = \"__seen__\"\n\n def value_calc():\n return f.when(\n f.col(seen_token).isNull() | ~f.col(seen_token),\n f.when(\n f.col(user_vec_col).isNotNull() & f.col(res_vec_col).isNotNull(),\n f.when(\n f.col(\"user_component\") == f.col(\"res_component\"),\n dot(f.col(user_vec_col), f.col(res_vec_col)),\n ).otherwise(f.lit(float(\"inf\"))),\n ).otherwise(f.lit(None))\n if self.has_components\n else f.when(\n f.col(user_vec_col).isNotNull() & f.col(res_vec_col).isNotNull(),\n dot(f.col(user_vec_col), f.col(res_vec_col)),\n ).otherwise(f.lit(None)),\n ).otherwise(f.lit(0.0))\n\n history_access_df = self.user_res_feature_vector_mapping.history_access_df\n\n the_df = (\n df.join(\n history_access_df.withColumn(seen_token, f.lit(True)),\n [tenant_col, user_col, res_col],\n how=\"left\",\n )\n if self.preserve_history and history_access_df is not None\n else df.withColumn(seen_token, f.lit(False))\n )\n\n user_mapping_df = self.user_mapping_df\n res_mapping_df = self.res_mapping_df\n\n return (\n the_df.join(user_mapping_df, [tenant_col, user_col], how=\"left\")\n .join(res_mapping_df, [tenant_col, res_col], how=\"left\")\n .withColumn(output_col, value_calc())\n .drop(\n user_vec_col, res_vec_col, \"user_component\", \"res_component\", seen_token\n )\n )\n\n\n# noinspection PyPep8Naming\nclass ConnectedComponents:\n def __init__(\n self,\n tenantCol: str,\n userCol: str,\n res_col: str,\n componentColName: str = \"component\",\n ):\n self.tenant_col = tenantCol\n self.user_col = userCol\n self.res_col = res_col\n self.component_col_name = componentColName\n\n def transform(self, df: DataFrame) -> Tuple[DataFrame, DataFrame]:\n edges = (\n df.select(self.tenant_col, self.user_col, self.res_col)\n .distinct()\n .orderBy(self.tenant_col, self.user_col, self.res_col)\n .cache()\n )\n\n users = (\n df.select(self.tenant_col, self.user_col)\n .distinct()\n .orderBy(self.tenant_col, self.user_col)\n .cache()\n )\n user2index = spark_utils.DataFrameUtils.zip_with_index(\n users, col_name=\"user_component\"\n )\n user2components = user2index\n res2components = None\n\n chg = True\n\n while chg:\n res2components = (\n edges.join(user2components, [self.tenant_col, self.user_col])\n .groupBy(self.tenant_col, self.res_col)\n .agg(f.min(\"user_component\").alias(\"res_component\"))\n )\n\n next_user2components = (\n edges.join(res2components, [self.tenant_col, self.res_col])\n .groupBy(self.tenant_col, self.user_col)\n .agg(f.min(\"res_component\").alias(\"user_component\"))\n .cache()\n )\n\n chg = (\n user2components.join(\n next_user2components,\n on=[self.tenant_col, self.user_col, \"user_component\"],\n ).count()\n != user2components.count()\n )\n\n user2components = next_user2components\n\n assert res2components is not None\n\n return (\n user2components.select(\n self.tenant_col,\n self.user_col,\n f.col(\"user_component\").alias(self.component_col_name),\n ).orderBy(self.tenant_col, self.user_col),\n res2components.select(\n self.tenant_col,\n self.res_col,\n f.col(\"res_component\").alias(self.component_col_name),\n ).orderBy(self.tenant_col, self.res_col),\n )\n\n\n# noinspection PyPep8Naming\nclass AccessAnomaly(Estimator):\n \"\"\"\n This is the AccessAnomaly, a pyspark.ml.Estimator which\n creates the AccessAnomalyModel which is a pyspark.ml.Transformer\n \"\"\"\n\n tenantCol = Param(\n Params._dummy(),\n \"tenantCol\",\n \"The name of the tenant column. \"\n \"This is a unique identifier used to partition the dataframe into independent \"\n \"groups where the values in each such group are completely isolated from one another. \"\n \"Note: if this column is irrelevant for your data, \"\n \"then just create a tenant column and give it a single value for all rows.\",\n )\n\n userCol = Param(\n Params._dummy(),\n \"userCol\",\n \"The name of the user column. \"\n \"This is a the name of the user column in the dataframe.\",\n )\n\n resCol = Param(\n Params._dummy(),\n \"resCol\",\n \"The name of the resource column. \"\n \"This is a the name of the resource column in the dataframe.\",\n )\n\n likelihoodCol = Param(\n Params._dummy(),\n \"likelihoodCol\",\n \"The name of the column with the likelihood estimate for user, res access \"\n \"(usually based on access counts per time unit). \",\n )\n\n outputCol = Param(\n Params._dummy(),\n \"outputCol\",\n \"The name of the output column representing the calculated anomaly score. \"\n \"Values will be between (-inf, +inf) with an estimated mean of 0.0 and standard deviation of 1.0. \",\n )\n\n rankParam = Param(\n Params._dummy(),\n \"rankParam\",\n \"rankParam is the number of latent factors in the model (defaults to 10).\",\n )\n\n maxIter = Param(\n Params._dummy(),\n \"maxIter\",\n \"maxIter is the maximum number of iterations to run (defaults to 25).\",\n )\n\n regParam = Param(\n Params._dummy(),\n \"regParam\",\n \"regParam specifies the regularization parameter in ALS (defaults to 0.1).\",\n )\n\n numBlocks = Param(\n Params._dummy(),\n \"numBlocks\",\n \"numBlocks is the number of blocks the users and items will be partitioned into \"\n \"in order to parallelize computation \"\n \"(defaults to |tenants| if separate_tenants is False else 10).\",\n )\n\n separateTenants = Param(\n Params._dummy(),\n \"separateTenants\",\n \"separateTenants applies the algorithm per tenant in isolation. \"\n \"Setting to True may reduce runtime significantly, if number of tenant is large, \"\n \"but will increase accuracy. (defaults to False).\",\n )\n\n lowValue = Param(\n Params._dummy(),\n \"lowValue\",\n \"lowValue is used to scale the values of likelihood_col to be in the range [lowValue, highValue] \"\n \"(defaults to 5.0).\",\n )\n\n highValue = Param(\n Params._dummy(),\n \"highValue\",\n \"highValue is used to scale the values of likelihood_col to be in the range [lowValue, highValue] \"\n \"(defaults to 10.0).\",\n )\n\n applyImplicitCf = Param(\n Params._dummy(),\n \"applyImplicitCf\",\n \"specifies whether to use the implicit/explicit feedback ALS for the data \"\n \"(defaults to True which means using implicit feedback).\",\n )\n\n alphaParam = Param(\n Params._dummy(),\n \"alphaParam\",\n \"alphaParam is a parameter applicable to the implicit feedback variant \"\n \"of ALS that governs the baseline confidence in preference observations.\"\n \"(defaults to 1.0).\",\n )\n\n complementsetFactor = Param(\n Params._dummy(),\n \"complementsetFactor\",\n \"complementsetFactor is a parameter applicable to the implicit feedback variant \"\n \"of ALS that governs the baseline confidence in preference observations.\"\n \"(defaults to 2).\",\n )\n\n negScore = Param(\n Params._dummy(),\n \"negScore\",\n \"negScore is a parameter applicable to the explicit feedback variant of ALS that governs \"\n \"the value to assign to the values of the complement set.\"\n \"(defaults to 1.0).\",\n )\n\n historyAccessDf = Param(\n Params._dummy(),\n \"historyAccessDf\",\n \"historyAccessDf is an optional spark dataframe which includes the \"\n \"list of seen user resource pairs for which the anomaly score should be zero.\",\n )\n\n def __init__(\n self,\n tenantCol: str = AccessAnomalyConfig.default_tenant_col,\n userCol: str = AccessAnomalyConfig.default_user_col,\n resCol: str = AccessAnomalyConfig.default_res_col,\n likelihoodCol: str = AccessAnomalyConfig.default_likelihood_col,\n outputCol: str = AccessAnomalyConfig.default_output_col,\n rankParam: int = AccessAnomalyConfig.default_rank,\n maxIter: int = AccessAnomalyConfig.default_max_iter,\n regParam: float = AccessAnomalyConfig.default_reg_param,\n numBlocks: Optional[int] = AccessAnomalyConfig.default_num_blocks,\n separateTenants: bool = AccessAnomalyConfig.default_separate_tenants,\n lowValue: Optional[float] = AccessAnomalyConfig.default_low_value,\n highValue: Optional[float] = AccessAnomalyConfig.default_high_value,\n applyImplicitCf: bool = AccessAnomalyConfig.default_apply_implicit_cf,\n alphaParam: Optional[float] = None,\n complementsetFactor: Optional[int] = None,\n negScore: Optional[float] = None,\n historyAccessDf: Optional[DataFrame] = None,\n ):\n\n super().__init__()\n\n if applyImplicitCf:\n alphaParam = (\n alphaParam\n if alphaParam is not None\n else AccessAnomalyConfig.default_alpha\n )\n assert complementsetFactor is None and negScore is None\n else:\n assert alphaParam is None\n\n complementsetFactor = (\n complementsetFactor\n if complementsetFactor is not None\n else AccessAnomalyConfig.default_complementset_factor\n )\n\n negScore = (\n negScore\n if negScore is not None\n else AccessAnomalyConfig.default_neg_score\n )\n\n # must either both be None or both be not None\n assert (lowValue is None) == (highValue is None)\n assert lowValue is None or lowValue >= 1.0\n assert (lowValue is None or highValue is None) or highValue > lowValue\n assert (lowValue is None or negScore is None) or (\n lowValue is not None and negScore < lowValue\n )\n\n spark_utils.ExplainBuilder.build(\n self,\n tenantCol=tenantCol,\n userCol=userCol,\n resCol=resCol,\n likelihoodCol=likelihoodCol,\n outputCol=outputCol,\n rankParam=rankParam,\n maxIter=maxIter,\n regParam=regParam,\n numBlocks=numBlocks,\n separateTenants=separateTenants,\n lowValue=lowValue,\n highValue=highValue,\n applyImplicitCf=applyImplicitCf,\n alphaParam=alphaParam,\n complementsetFactor=complementsetFactor,\n negScore=negScore,\n historyAccessDf=historyAccessDf,\n )\n\n # --- getters and setters\n @property\n def indexed_user_col(self):\n return self.user_col + \"_index\"\n\n @property\n def user_vec_col(self):\n return self.user_col + \"_vector\"\n\n @property\n def indexed_res_col(self):\n return self.res_col + \"_index\"\n\n @property\n def res_vec_col(self):\n return self.res_col + \"_vector\"\n\n @property\n def scaled_likelihood_col(self):\n return self.likelihood_col + \"_scaled\"\n\n def _get_scaled_df(self, df: DataFrame) -> DataFrame:\n return (\n scalers.LinearScalarScaler(\n input_col=self.likelihood_col,\n partition_key=self.tenant_col,\n output_col=self.scaled_likelihood_col,\n min_required_value=self.low_value,\n max_required_value=self.high_value,\n )\n .fit(df)\n .transform(df)\n if self.low_value is not None and self.high_value is not None\n else df\n )\n\n def _enrich_and_normalize(self, indexed_df: DataFrame) -> DataFrame:\n tenant_col = self.tenant_col\n indexed_user_col = self.indexed_user_col\n indexed_res_col = self.indexed_res_col\n scaled_likelihood_col = self.scaled_likelihood_col\n\n if not self.apply_implicit_cf:\n complementset_factor = self.complementset_factor\n neg_score = self.neg_score\n assert complementset_factor is not None and neg_score is not None\n\n comp_df = (\n ComplementAccessTransformer(\n tenant_col,\n [indexed_user_col, indexed_res_col],\n complementset_factor,\n )\n .transform(indexed_df)\n .withColumn(scaled_likelihood_col, f.lit(neg_score))\n )\n else:\n comp_df = None\n\n scaled_df = self._get_scaled_df(indexed_df).select(\n tenant_col, indexed_user_col, indexed_res_col, scaled_likelihood_col\n )\n\n return scaled_df.union(comp_df) if comp_df is not None else scaled_df\n\n def _train_cf(self, als: ALS, df: DataFrame) -> Tuple[DataFrame, DataFrame]:\n tenant_col = self.tenant_col\n indexed_user_col = self.indexed_user_col\n user_vec_col = self.user_vec_col\n indexed_res_col = self.indexed_res_col\n res_vec_col = self.res_vec_col\n\n spark_model = als.fit(df)\n\n user_mapping_df = (\n spark_model.userFactors.select(\n f.col(\"id\").alias(indexed_user_col),\n f.col(\"features\").alias(user_vec_col),\n )\n .join(df.select(indexed_user_col, tenant_col).distinct(), indexed_user_col)\n .select(tenant_col, indexed_user_col, user_vec_col)\n )\n\n res_mapping_df = (\n spark_model.itemFactors.select(\n f.col(\"id\").alias(indexed_res_col), f.col(\"features\").alias(res_vec_col)\n )\n .join(df.select(indexed_res_col, tenant_col).distinct(), indexed_res_col)\n .select(tenant_col, indexed_res_col, res_vec_col)\n )\n\n return user_mapping_df, res_mapping_df\n\n def create_spark_model_vectors_df(\n self, df: DataFrame\n ) -> _UserResourceFeatureVectorMapping:\n tenant_col = self.tenant_col\n indexed_user_col = self.indexed_user_col\n user_vec_col = self.user_vec_col\n indexed_res_col = self.indexed_res_col\n res_vec_col = self.res_vec_col\n max_iter = self.max_iter\n distinct_tenants = df.select(tenant_col).distinct().cache()\n num_tenants = distinct_tenants.count()\n separate_tenants = self.separate_tenants\n num_blocks = (\n self.num_blocks\n if self.num_blocks is not None\n else (num_tenants if not separate_tenants else 10)\n )\n\n als = ALS(\n rank=self.rank_param,\n maxIter=max_iter,\n regParam=self.reg_param,\n numUserBlocks=num_blocks,\n numItemBlocks=num_blocks,\n implicitPrefs=self.apply_implicit_cf,\n userCol=self.indexed_user_col,\n itemCol=self.indexed_res_col,\n ratingCol=self.scaled_likelihood_col,\n nonnegative=True,\n coldStartStrategy=\"drop\",\n )\n\n alpha = self.alpha_param\n\n if alpha is not None:\n als.setAlpha(alpha)\n\n if separate_tenants:\n tenants = [\n row[tenant_col]\n for row in distinct_tenants.orderBy(tenant_col).collect()\n ]\n\n user_mapping_df: Optional[DataFrame] = None\n res_mapping_df: Optional[DataFrame] = None\n\n for curr_tenant in tenants:\n curr_df = df.filter(f.col(tenant_col) == curr_tenant).cache()\n curr_user_mapping_df, curr_res_mapping_df = self._train_cf(als, curr_df)\n\n user_mapping_df = (\n user_mapping_df.union(curr_user_mapping_df)\n if user_mapping_df is not None\n else curr_user_mapping_df\n )\n\n res_mapping_df = (\n res_mapping_df.union(curr_res_mapping_df)\n if res_mapping_df is not None\n else curr_res_mapping_df\n )\n else:\n user_mapping_df, res_mapping_df = self._train_cf(als, df)\n\n assert user_mapping_df is not None and res_mapping_df is not None\n\n return _UserResourceFeatureVectorMapping(\n tenant_col,\n indexed_user_col,\n user_vec_col,\n indexed_res_col,\n res_vec_col,\n None,\n None,\n None,\n user_mapping_df,\n res_mapping_df,\n )\n\n def _fit(self, df: DataFrame) -> AccessAnomalyModel:\n # index the user and resource columns to allow running the spark ALS algorithm\n the_indexer = indexers.MultiIndexer(\n indexers=[\n indexers.IdIndexer(\n input_col=self.user_col,\n partition_key=self.tenant_col,\n output_col=self.indexed_user_col,\n reset_per_partition=self.separate_tenants,\n ),\n indexers.IdIndexer(\n input_col=self.res_col,\n partition_key=self.tenant_col,\n output_col=self.indexed_res_col,\n reset_per_partition=self.separate_tenants,\n ),\n ]\n )\n\n the_indexer_model = the_indexer.fit(df)\n\n # indexed_df is the dataframe with the indices for user and resource\n indexed_df = the_indexer_model.transform(df)\n enriched_df = self._enrich_and_normalize(indexed_df).cache()\n\n user_res_feature_vector_mapping_df = self.create_spark_model_vectors_df(\n enriched_df\n )\n user_res_norm_cf_df_model = ModelNormalizeTransformer(\n enriched_df, self.rank_param\n ).transform(user_res_feature_vector_mapping_df)\n\n # convert user and resource indices back to names\n user_index_model = the_indexer_model.get_model_by_input_col(self.user_col)\n res_index_model = the_indexer_model.get_model_by_input_col(self.res_col)\n assert user_index_model is not None and res_index_model is not None\n\n norm_user_mapping_df = user_res_norm_cf_df_model.user_feature_vector_mapping_df\n norm_res_mapping_df = user_res_norm_cf_df_model.res_feature_vector_mapping_df\n\n indexed_user_col = self.indexed_user_col\n indexed_res_col = self.indexed_res_col\n\n # do the actual index to name mapping (using undo_transform)\n final_user_mapping_df = user_index_model.undo_transform(\n norm_user_mapping_df\n ).drop(indexed_user_col)\n final_res_mapping_df = res_index_model.undo_transform(norm_res_mapping_df).drop(\n indexed_res_col\n )\n\n tenant_col, user_col, res_col = self.tenant_col, self.user_col, self.res_col\n\n history_access_df = self.history_access_df\n access_df = (\n history_access_df\n if history_access_df is not None\n else df.select(tenant_col, user_col, res_col).cache()\n )\n\n user2component_mappings_df, res2component_mappings_df = ConnectedComponents(\n tenant_col, user_col, res_col\n ).transform(access_df)\n\n return AccessAnomalyModel(\n _UserResourceFeatureVectorMapping(\n tenant_col=self.tenant_col,\n user_col=self.user_col,\n user_vec_col=self.user_vec_col,\n res_col=self.res_col,\n res_vec_col=self.res_vec_col,\n history_access_df=history_access_df,\n user2component_mappings_df=user2component_mappings_df,\n res2component_mappings_df=res2component_mappings_df,\n user_feature_vector_mapping_df=final_user_mapping_df.cache(),\n res_feature_vector_mapping_df=final_res_mapping_df.cache(),\n ),\n self.output_col,\n )\n\n\nclass ModelNormalizeTransformer:\n \"\"\"\n Given a UserResourceCfDataframeModel this class creates and returns\n a new normalized UserResourceCfDataframeModel which has an anomaly score\n with a mean of 0.0 and standard deviation of 1.0 when applied on the given dataframe\n \"\"\"\n\n def __init__(self, access_df: DataFrame, rank: int):\n self.access_df = access_df\n self.rank = rank\n\n def _make_append_bias(\n self,\n user_col: str,\n res_col: str,\n col_name: str,\n target_col_name: str,\n rank: int,\n ) -> f.udf:\n assert col_name == user_col or col_name == res_col\n assert target_col_name == user_col or target_col_name == res_col\n\n def value_at(bias: float, value: float, i: int) -> float:\n if col_name != target_col_name or i < rank:\n res = value\n elif col_name == user_col and i == rank:\n res = bias + value\n elif col_name == res_col and i == (rank + 1):\n res = bias + value\n else:\n res = value\n\n assert res == 1.0 if i == rank and col_name == res_col else True\n assert res == 1.0 if i == (rank + 1) and col_name == user_col else True\n\n return res\n\n @f.udf(t.ArrayType(t.DoubleType()))\n def append_bias(v: List[float], bias: float, coeff: float = 1.0) -> List[float]:\n assert len(v) == rank or len(v) == rank + 2\n\n if len(v) == rank:\n # increase vector size to adjust for bias\n fix_value = bias if col_name == target_col_name else 0.0\n u = [fix_value, 1.0] if col_name == user_col else [1.0, fix_value]\n return [\n float(coeff * value)\n for value in np.append(np.array(v), np.array(u))\n ]\n else:\n # fix enhanced vector to adjust for another bias\n assert len(v) == rank + 2\n return [coeff * value_at(bias, v[i], i) for i in range(len(v))]\n\n return append_bias\n\n def transform(\n self, user_res_cf_df_model: _UserResourceFeatureVectorMapping\n ) -> _UserResourceFeatureVectorMapping:\n likelihood_col_token = \"__likelihood__\"\n\n dot = _make_dot()\n\n tenant_col = user_res_cf_df_model.tenant_col\n user_col = user_res_cf_df_model.user_col\n user_vec_col = user_res_cf_df_model.user_vec_col\n res_col = user_res_cf_df_model.res_col\n res_vec_col = user_res_cf_df_model.res_vec_col\n\n fixed_df = (\n self.access_df.join(\n user_res_cf_df_model.user_feature_vector_mapping_df,\n [tenant_col, user_col],\n )\n .join(\n user_res_cf_df_model.res_feature_vector_mapping_df,\n [tenant_col, res_col],\n )\n .select(\n tenant_col,\n user_col,\n user_vec_col,\n res_col,\n res_vec_col,\n dot(f.col(user_vec_col), f.col(res_vec_col)).alias(\n likelihood_col_token\n ),\n )\n )\n\n scaler_model = scalers.StandardScalarScaler(\n likelihood_col_token, tenant_col, user_vec_col\n ).fit(fixed_df)\n\n per_group_stats: DataFrame = scaler_model.per_group_stats\n assert isinstance(per_group_stats, DataFrame)\n\n append2user_bias = self._make_append_bias(\n user_col, res_col, user_col, user_col, self.rank\n )\n append2res_bias = self._make_append_bias(\n user_col, res_col, res_col, user_col, self.rank\n )\n\n fixed_user_mapping_df = (\n user_res_cf_df_model.user_feature_vector_mapping_df.join(\n per_group_stats, tenant_col\n ).select(\n tenant_col,\n user_col,\n append2user_bias(\n f.col(user_vec_col),\n f.lit(-1.0) * f.col(scalers.StandardScalarScalerConfig.mean_token),\n f.lit(-1.0)\n / f.when(\n f.col(scalers.StandardScalarScalerConfig.std_token) != 0.0,\n f.col(scalers.StandardScalarScalerConfig.std_token),\n ).otherwise(f.lit(1.0)),\n ).alias(user_vec_col),\n )\n )\n\n fixed_res_mapping_df = user_res_cf_df_model.res_feature_vector_mapping_df.join(\n per_group_stats, tenant_col\n ).select(\n tenant_col,\n res_col,\n append2res_bias(f.col(res_vec_col), f.lit(0)).alias(res_vec_col),\n )\n\n return user_res_cf_df_model.replace_mappings(\n fixed_user_mapping_df, fixed_res_mapping_df\n )\n"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
moondaiy/TensorFlowTutorials
|
[
"c7f0255e3704c5a40f72ac0707684fb201123c1c",
"c7f0255e3704c5a40f72ac0707684fb201123c1c",
"c7f0255e3704c5a40f72ac0707684fb201123c1c"
] |
[
"TensorFlowBasic/convNet.py",
"TensorFlowBasic/tensorBoard.py",
"TensorFlowBasic/tensor_create.py"
] |
[
"\"\"\"\n卷积神经网络\n两个卷积层,两个全连接层\n输入 [sample * 28 * 28 * 1 ] (灰度图)\n[ 28 * 28 *1 ] --> (32个卷积核,每个大小5*5*1,sample方式卷积) --> [ 28 * 28 * 32] --> (池化 2*2 ,步长2)--> [14 *14 *32]\n[ 14 * 14 *32] --> (64个卷积核,每个大小 5 * 5 * 32,sample方式卷积) --> [14 * 14 *64] --> (池化 2*2 ,步长2)--> [7 * 7 *64] \n[ 7 * 7 * 64] --> reshape 成列向量 --> (7 * 7 * 64)\n[sample * (7*7*64)] 全连接层1 weights:[7*7*64 , 1024] --> [sample * 1024]\n[sample * 1024] 全连接层2 weights:[1024,10] --> [sample *10]\n输出:10个分类\n\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n# number 1 to 10 data\nmnist = input_data.read_data_sets('MNIST_data', one_hot=True)\n\ndef compute_accuracy(v_xs, v_ys):\n global prediction\n y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})\n correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1})\n return result\n\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\ndef conv2d(x, W):\n\n # stride [1, x_movement, y_movement, 1]\n # Must have strides[0] = strides[3] = 1\n # W [filter_height, filter_width, in_channels, out_channels]\n\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\ndef max_pool_2x2(x):\n # stride [1, x_movement, y_movement, 1]\n # ksize [1, height, width, 1]\n return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')\n\n# define placeholder for inputs to network\nxs = tf.placeholder(tf.float32, [None, 784])/255. # 28x28\nys = tf.placeholder(tf.float32, [None, 10])\nkeep_prob = tf.placeholder(tf.float32)\n\n#把xs的形状变成[-1,28,28,1],-1代表先不考虑输入的图片例子多少这个维度,后面的1是channel的数量\n#因为我们输入的图片是黑白的,因此channel是1,例如如果是RGB图像,那么channel就是3。\nx_image = tf.reshape(xs, [-1, 28, 28, 1])\n# print(x_image.shape) # [n_samples, 28,28,1]\n\n#建立卷积层\n## 本层我们的卷积核patch的大小是5x5,因为黑白图片channel是1所以输入是1,输出是32个featuremap ??? 32 是什么意思?\nW_conv1 = weight_variable([5,5, 1,32]) # patch 5x5, in size 1, out size 32\nb_conv1 = bias_variable([32])\n#卷积运算\nh_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # output size 28x28x32\nh_pool1 = max_pool_2x2(h_conv1) # output size 14x14x32\n\n\nW_conv2 = weight_variable([5,5, 32, 64]) # patch 5x5, in size 32, out size 64 ??? 64 是什么意思?\nb_conv2 = bias_variable([64])\nh_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # output size 14x14x64\nh_pool2 = max_pool_2x2(h_conv2) # output size 7x7x64\n\n#全连接层\nW_fc1 = weight_variable([7*7*64, 1024])\nb_fc1 = bias_variable([1024])\n\n# [n_samples, 7, 7, 64] ->> [n_samples, 7*7*64]\n# 这个地方确实可以得到卷基层和最后的全连接层之间的关系\nh_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])\nh_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\n## fc2 layer ##\nW_fc2 = weight_variable([1024, 10])\nb_fc2 = bias_variable([10])\nprediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n\n\n# the error between prediction and real data\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),reduction_indices=[1])) # loss\ntrain_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n\nsess = tf.Session()\n\n\nif int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:\n init = tf.initialize_all_variables()\nelse:\n init = tf.global_variables_initializer()\nsess.run(init)\n\n# 原来是1000 为了快一点 改成了1000\nfor i in range(5000):\n batch_xs, batch_ys = mnist.train.next_batch(100)\n sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})\n if i % 50 == 0:\n print(compute_accuracy(mnist.test.images[:1000], mnist.test.labels[:1000]))",
"import tensorflow as tf\n\n\n#add_layer 函数里面所有的with都是为了tensorboard添加上去的\ndef add_layer(inputs, in_size, out_size, activation_function=None,nameScope=\"layer\"):\n # add one more layer and return the output of this layer\n with tf.name_scope(nameScope):\n\n with tf.name_scope('weights'):\n\n Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')\n\n with tf.name_scope('biases'):\n biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')\n\n with tf.name_scope('Wx_plus_b'):\n Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)\n\n if activation_function is None:\n outputs = Wx_plus_b\n else:\n outputs = activation_function(Wx_plus_b, )\n\n return outputs\n\n\n# 这个就是在tensorboard上可视化的时候的区别:\n# 使用with tf.name_scope('inputs')可以将xs和ys包含进来\n# 形成一个大的图层,图层的名字就是with tf.name_scope()方法里的参数。\nwith tf.name_scope('inputs'):\n\n xs = tf.placeholder(tf.float32, [None, 1], name='x_input') # 这个name的属性,也是为了使用tensorboard,添加上来的\n ys = tf.placeholder(tf.float32, [None, 1], name='y_input') # 同上\n\n# add hidden layer\nl1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu,nameScope=\"layerTest1\")\n\n# add output layer\nprediction = add_layer(l1, 10, 1, activation_function=None,nameScope=\"layerTest2\")\n\nsess = tf.Session()\n\n# 上面的wtih或者是name都是可选的,可以选择添加,也可以选择不添加,but下面的这一行是一定要写的。\n# 这个表明了 在当前的目录下面创建以恶搞logs的文件家,然后把图的信息保存进去\n# 这样运行完这段代码之后,就会有一个logs的文件夹被创建\nif int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1: # tensorflow version < 0.12\n writer = tf.train.SummaryWriter('logs/', sess.graph)\nelse: # tensorflow version >= 0.12\n writer = tf.summary.FileWriter(\"logs/\", sess.graph)\n\nif int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:\n init = tf.initialize_all_variables()\nelse:\n init = tf.global_variables_initializer()\n\nsess.run(init)",
"import tensorflow as tf\nimport numpy as np\n\n\n\n# source_tensor = np.ones((4,3),dtype=np.int64)\n\nsource_tensor = tf.placeholder(tf.float32, shape=[None,None,3])\n\n\ntarget = tf.ones(tf.shape(source_tensor),dtype=source_tensor.dtype)\n\ninit = tf.global_variables_initializer()\n\nmask = target > source_tensor\n\n# result = tf.where(mask, -1, 1)\n\n\nwith tf.Session() as sess:\n\n sess.run(init)\n\n # print(sess.run(target,feed_dict={source_tensor : np.zeros((2,3,3),dtype=np.float32)}))\n\n print(sess.run(mask,feed_dict={source_tensor:np.zeros((2,3,3),dtype=np.float32)}))\n\n # print(sess.run(result, feed_dict={source_tensor: np.zeros((2, 3, 3), dtype=np.float32)}))"
] |
[
[
"tensorflow.matmul",
"tensorflow.__version__.split",
"tensorflow.truncated_normal",
"tensorflow.constant",
"tensorflow.Variable",
"tensorflow.nn.max_pool",
"tensorflow.reshape",
"tensorflow.cast",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.initialize_all_variables",
"tensorflow.log",
"tensorflow.Session",
"tensorflow.train.AdamOptimizer",
"tensorflow.argmax",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"tensorflow.nn.conv2d",
"tensorflow.nn.dropout"
],
[
"tensorflow.matmul",
"tensorflow.__version__.split",
"tensorflow.summary.FileWriter",
"tensorflow.zeros",
"tensorflow.placeholder",
"tensorflow.train.SummaryWriter",
"tensorflow.global_variables_initializer",
"tensorflow.initialize_all_variables",
"tensorflow.name_scope",
"tensorflow.Session",
"tensorflow.random_normal"
],
[
"tensorflow.shape",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
sadicLiu/mask_rcnn_code
|
[
"a8878f81f6bbfa63b5a4b7ca2bfb80673e4febfd",
"a8878f81f6bbfa63b5a4b7ca2bfb80673e4febfd"
] |
[
"maskrcnn_benchmark/engine/trainer.py",
"maskrcnn_benchmark/layers/misc.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\nimport datetime\nimport logging\nimport time\n\nimport torch\nimport torch.distributed as dist\n\nfrom maskrcnn_benchmark.utils.comm import get_world_size\nfrom maskrcnn_benchmark.utils.metric_logger import MetricLogger\n\n\ndef reduce_loss_dict(loss_dict):\n \"\"\"\n Reduce the loss dictionary from all processes so that process with rank\n 0 has the averaged results. Returns a dict with the same fields as\n loss_dict, after reduction.\n \"\"\"\n world_size = get_world_size()\n if world_size < 2:\n return loss_dict\n with torch.no_grad():\n loss_names = []\n all_losses = []\n for k in sorted(loss_dict.keys()):\n loss_names.append(k)\n all_losses.append(loss_dict[k])\n all_losses = torch.stack(all_losses, dim=0)\n dist.reduce(all_losses, dst=0)\n if dist.get_rank() == 0:\n # only main process gets accumulated, so only divide by\n # world_size in this case\n all_losses /= world_size\n reduced_losses = {k: v for k, v in zip(loss_names, all_losses)}\n return reduced_losses\n\n\ndef do_train(\n model,\n data_loader,\n optimizer,\n scheduler,\n checkpointer,\n device,\n checkpoint_period,\n arguments,\n):\n logger = logging.getLogger(\"maskrcnn_benchmark.trainer\")\n logger.info(\"Start training\")\n meters = MetricLogger(delimiter=\" \")\n max_iter = len(data_loader)\n start_iter = arguments[\"iteration\"]\n\n # model.train()与model.eval()对应, 主要是指定模型所处的阶段, 以调整Dropout, BN等\n model.train()\n\n start_training_time = time.time()\n end = time.time()\n for iteration, (images, targets, _) in enumerate(data_loader, start_iter):\n data_time = time.time() - end\n iteration = iteration + 1\n arguments[\"iteration\"] = iteration\n\n # https://blog.csdn.net/qq_20622615/article/details/83150963\n # 这里是每个mini-batch更新一次, 用于计数以调整学习率\n scheduler.step()\n\n images = images.to(device)\n targets = [target.to(device) for target in targets]\n\n loss_dict = model(images, targets)\n\n losses = sum(loss for loss in loss_dict.values())\n\n # reduce losses over all GPUs for logging purposes\n loss_dict_reduced = reduce_loss_dict(loss_dict)\n losses_reduced = sum(loss for loss in loss_dict_reduced.values())\n meters.update(loss=losses_reduced, **loss_dict_reduced)\n\n optimizer.zero_grad()\n losses.backward()\n optimizer.step()\n\n batch_time = time.time() - end\n end = time.time()\n meters.update(time=batch_time, data=data_time)\n\n eta_seconds = meters.time.global_avg * (max_iter - iteration)\n eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))\n\n if iteration % 20 == 0 or iteration == max_iter:\n logger.info(\n meters.delimiter.join(\n [\n \"eta: {eta}\",\n \"iter: {iter}\",\n \"{meters}\",\n \"lr: {lr:.6f}\",\n \"max mem: {memory:.0f}\",\n ]\n ).format(\n eta=eta_string,\n iter=iteration,\n meters=str(meters),\n lr=optimizer.param_groups[0][\"lr\"],\n memory=torch.cuda.max_memory_allocated() / 1024.0 / 1024.0,\n )\n )\n if iteration % checkpoint_period == 0:\n checkpointer.save(\"model_{:07d}\".format(iteration), **arguments)\n if iteration == max_iter:\n checkpointer.save(\"model_final\", **arguments)\n\n total_training_time = time.time() - start_training_time\n total_time_str = str(datetime.timedelta(seconds=total_training_time))\n logger.info(\n \"Total training time: {} ({:.4f} s / it)\".format(\n total_time_str, total_training_time / (max_iter)\n )\n )\n",
"\"\"\"\nhelper class that supports empty tensors on some nn functions.\n\nIdeally, add support directly in PyTorch to empty tensors in\nthose functions.\n\nThis can be removed once https://github.com/pytorch/pytorch/issues/12013\nis implemented\n\"\"\"\n\nimport math\nimport torch\nfrom torch.nn.modules.utils import _ntuple\n\n\nclass _NewEmptyTensorOp(torch.autograd.Function):\n @staticmethod\n def forward(ctx, x, new_shape):\n ctx.shape = x.shape\n return x.new_empty(new_shape)\n\n @staticmethod\n def backward(ctx, grad):\n shape = ctx.shape\n return _NewEmptyTensorOp.apply(grad, shape), None\n\n\nclass Conv2d(torch.nn.Conv2d):\n def forward(self, x):\n # 当 x.numel()>0 时,与普通的 torch.nn.Conv2d() 函数没有区别\n if x.numel() > 0:\n return super(Conv2d, self).forward(x)\n # get output shape\n\n output_shape = [\n (i + 2 * p - (di * (k - 1) + 1)) // d + 1\n for i, p, di, k, d in zip(\n x.shape[-2:], self.padding, self.dilation, self.kernel_size, self.stride\n )\n ]\n output_shape = [x.shape[0], self.weight.shape[0]] + output_shape\n return _NewEmptyTensorOp.apply(x, output_shape)\n\n\nclass ConvTranspose2d(torch.nn.ConvTranspose2d):\n def forward(self, x):\n if x.numel() > 0:\n return super(ConvTranspose2d, self).forward(x)\n # get output shape\n\n output_shape = [\n (i - 1) * d - 2 * p + (di * (k - 1) + 1) + op\n for i, p, di, k, d, op in zip(\n x.shape[-2:],\n self.padding,\n self.dilation,\n self.kernel_size,\n self.stride,\n self.output_padding,\n )\n ]\n output_shape = [x.shape[0], self.bias.shape[0]] + output_shape\n return _NewEmptyTensorOp.apply(x, output_shape)\n\n\nclass BatchNorm2d(torch.nn.BatchNorm2d):\n def forward(self, x):\n if x.numel() > 0:\n return super(BatchNorm2d, self).forward(x)\n # get output shape\n output_shape = x.shape\n return _NewEmptyTensorOp.apply(x, output_shape)\n\n\ndef interpolate(\n input, size=None, scale_factor=None, mode=\"nearest\", align_corners=None\n):\n if input.numel() > 0:\n return torch.nn.functional.interpolate(\n input, size, scale_factor, mode, align_corners\n )\n\n def _check_size_scale_factor(dim):\n if size is None and scale_factor is None:\n raise ValueError(\"either size or scale_factor should be defined\")\n if size is not None and scale_factor is not None:\n raise ValueError(\"only one of size or scale_factor should be defined\")\n if (\n scale_factor is not None\n and isinstance(scale_factor, tuple)\n and len(scale_factor) != dim\n ):\n raise ValueError(\n \"scale_factor shape must match input shape. \"\n \"Input is {}D, scale_factor size is {}\".format(dim, len(scale_factor))\n )\n\n def _output_size(dim):\n _check_size_scale_factor(dim)\n if size is not None:\n return size\n scale_factors = _ntuple(dim)(scale_factor)\n # math.floor might return float in py2.7\n return [\n int(math.floor(input.size(i + 2) * scale_factors[i])) for i in range(dim)\n ]\n\n output_shape = tuple(_output_size(2))\n output_shape = input.shape[:-2] + output_shape\n return _NewEmptyTensorOp.apply(input, output_shape)\n"
] |
[
[
"torch.cuda.max_memory_allocated",
"torch.distributed.reduce",
"torch.no_grad",
"torch.stack",
"torch.distributed.get_rank"
],
[
"torch.nn.modules.utils._ntuple",
"torch.nn.functional.interpolate"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SaibheMcC/ARC
|
[
"52ba259c29443f1671cdf583889e31445694fe69"
] |
[
"src/solution_017c7c7b.py"
] |
[
"import json #import the json module\nimport sys #import the sys module\nimport numpy as np #import the numpy module\n\n\n#solve function\ndef solve():\n\n #set datalocation to the argument passed in from the command line\n datalocation = sys.argv[1]\n\n #open datalocation, and load it into variable data\n data = json.load(open(datalocation))\n\n # list of set values (train set or test set)\n set_values = ['train', 'test']\n\n #iterate over each value in set_values\n for value in set_values:\n\n #while the count is less than the length of the set (training set or test set)\n i = 0\n count = len(data[value])\n while i < count:\n\n #access input i of each set\n input = data[value][i]['input']\n #create a new structure, output\n output = input\n\n #iterate over input values\n #change the blue squares to red\n #by swapping any values of 1 to become 2\n for row in output:\n for column in row:\n if row[column] == 1:\n row[column] = 2\n #print (row[column])\n \n #sub_list = get first half of data and append it onto the end of the data\n sub_list = output[:int(len(output)/2)]\n\n #iterate through each item in the sub_list\n for x in sub_list:\n #append the each item to the input data\n output.append(x)\n\n #create a numpy array out of the output\n output = np.array([output])\n #print statement to print each output grid as numbers and spaces\n print(*output.flatten(), sep=' ')\n\n #add 1 to i\n #this is th counter for the while loop\n i+=1 \n \n \nsolve() #call the solve function "
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
arengela/AngelaUCSFCodeAll
|
[
"aeacf478bae7fbddfe6903c963fb9a08b0f0aecc"
] |
[
"koepsell-phase-coupling-estimation-271441c/python/phasemodel/setup.py"
] |
[
"def configuration(parent_package='',top_path=None):\n from numpy.distutils.misc_util import Configuration\n config = Configuration('phasemodel', parent_package, top_path)\n\n config.add_data_dir('tests')\n config.add_data_files('*.pyx')\n\n return config\n\nif __name__ == '__main__':\n from numpy.distutils.core import setup\n setup(**configuration(top_path='').todict())\n\n"
] |
[
[
"numpy.distutils.misc_util.Configuration"
]
] |
[
{
"matplotlib": [],
"numpy": [
"1.11",
"1.19",
"1.24",
"1.16",
"1.23",
"1.20",
"1.7",
"1.12",
"1.21",
"1.22",
"1.14",
"1.6",
"1.13",
"1.9",
"1.17",
"1.10",
"1.18",
"1.15",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
clw5180/yolact_notes
|
[
"c59fbb9cb49e1008a00a17e599014f9bd8337100"
] |
[
"eval.py"
] |
[
"from data import COCODetection, get_label_map, MEANS, COLORS\nfrom yolact import Yolact\nfrom utils.augmentations import BaseTransform, FastBaseTransform, Resize\nfrom utils.functions import MovingAverage, ProgressBar\nfrom layers.box_utils import jaccard, center_size, mask_iou\nfrom utils import timer\nfrom utils.functions import SavePath\nfrom layers.output_utils import postprocess, undo_image_transformation\nimport pycocotools\n\nfrom data import cfg, set_cfg, set_dataset\n\nimport numpy as np\nimport torch\nimport torch.backends.cudnn as cudnn\nfrom torch.autograd import Variable\nimport argparse\nimport time\nimport random\nimport cProfile\nimport pickle\nimport json\nimport os\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom collections import OrderedDict\nfrom PIL import Image\n\nimport matplotlib.pyplot as plt\nimport cv2\n\ndef str2bool(v):\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\ndef parse_args(argv=None):\n parser = argparse.ArgumentParser(\n description='YOLACT COCO Evaluation')\n parser.add_argument('--trained_model',\n default='weights/ssd300_mAP_77.43_v2.pth', type=str,\n help='Trained state_dict file path to open. If \"interrupt\", this will open the interrupt file.')\n parser.add_argument('--top_k', default=5, type=int,\n help='Further restrict the number of predictions to parse') # clw note:即输出多少个mask\n parser.add_argument('--cuda', default=True, type=str2bool,\n help='Use cuda to evaulate model')\n parser.add_argument('--fast_nms', default=True, type=str2bool,\n help='Whether to use a faster, but not entirely correct version of NMS.')\n parser.add_argument('--cross_class_nms', default=False, type=str2bool,\n help='Whether compute NMS cross-class or per-class.')\n parser.add_argument('--display_masks', default=True, type=str2bool,\n help='Whether or not to display masks over bounding boxes')\n parser.add_argument('--display_bboxes', default=True, type=str2bool,\n help='Whether or not to display bboxes around masks')\n parser.add_argument('--display_text', default=True, type=str2bool,\n help='Whether or not to display text (class [score])')\n parser.add_argument('--display_scores', default=True, type=str2bool,\n help='Whether or not to display scores in addition to classes')\n parser.add_argument('--display', dest='display', action='store_true',\n help='Display qualitative results instead of quantitative ones.') # clw note:显示定性结果,而非定量\n parser.add_argument('--shuffle', dest='shuffle', action='store_true',\n help='Shuffles the images when displaying them. Doesn\\'t have much of an effect when display is off though.')\n parser.add_argument('--ap_data_file', default='results/ap_data.pkl', type=str,\n help='In quantitative mode, the file to save detections before calculating mAP.') # 定量分析,也就是计算mAP之前保存的预测结果pkl文件\n parser.add_argument('--resume', dest='resume', action='store_true',\n help='If display not set, this resumes mAP calculations from the ap_data_file.') # 定量分析,计算mAP\n parser.add_argument('--max_images', default=-1, type=int,\n help='The maximum number of images from the dataset to consider. Use -1 for all.')\n parser.add_argument('--output_coco_json', dest='output_coco_json', action='store_true',\n help='If display is not set, instead of processing IoU values, this just dumps detections into the coco json file.')\n parser.add_argument('--bbox_det_file', default='results/bbox_detections.json', type=str,\n help='The output file for coco bbox results if --coco_results is set.')\n parser.add_argument('--mask_det_file', default='results/mask_detections.json', type=str,\n help='The output file for coco mask results if --coco_results is set.')\n parser.add_argument('--config', default=None,\n help='The config object to use.')\n parser.add_argument('--output_web_json', dest='output_web_json', action='store_true',\n help='If display is not set, instead of processing IoU values, this dumps detections for usage with the detections viewer web thingy.')\n parser.add_argument('--web_det_path', default='web/dets/', type=str,\n help='If output_web_json is set, this is the path to dump detections into.')\n parser.add_argument('--no_bar', dest='no_bar', action='store_true',\n help='Do not output the status bar. This is useful for when piping to a file.')\n parser.add_argument('--display_lincomb', default=False, type=str2bool,\n help='If the config uses lincomb masks, output a visualization of how those masks are created.')\n parser.add_argument('--benchmark', default=False, dest='benchmark', action='store_true',\n help='Equivalent to running display mode but without displaying an image.')\n parser.add_argument('--no_sort', default=False, dest='no_sort', action='store_true',\n help='Do not sort images by hashed image ID.')\n parser.add_argument('--seed', default=None, type=int,\n help='The seed to pass into random.seed. Note: this is only really for the shuffle and does not (I think) affect cuda stuff.')\n parser.add_argument('--mask_proto_debug', default=False, dest='mask_proto_debug', action='store_true',\n help='Outputs stuff for scripts/compute_mask.py.')\n parser.add_argument('--no_crop', default=False, dest='crop', action='store_false',\n help='Do not crop output masks with the predicted bounding box.')\n parser.add_argument('--image', default=None, type=str,\n help='A path to an image to use for display.')\n parser.add_argument('--images', default=None, type=str,\n help='An input folder of images and output folder to save detected images. Should be in the format input->output.')\n parser.add_argument('--video', default=None, type=str,\n help='A path to a video to evaluate on. Passing in a number will use that index webcam.')\n parser.add_argument('--video_multiframe', default=1, type=int,\n help='The number of frames to evaluate in parallel to make videos play at higher fps.')\n parser.add_argument('--score_threshold', default=0, type=float,\n help='Detections with a score under this threshold will not be considered. This currently only works in display mode.')\n parser.add_argument('--dataset', default=None, type=str,\n help='If specified, override the dataset specified in the config with this one (example: coco2017_dataset).')\n parser.add_argument('--detect', default=False, dest='detect', action='store_true',\n help='Don\\'t evauluate the mask branch at all and only do object detection. This only works for --display and --benchmark.')\n parser.add_argument('--display_fps', default=False, dest='display_fps', action='store_true',\n help='When displaying / saving video, draw the FPS on the frame')\n parser.add_argument('--emulate_playback', default=False, dest='emulate_playback', action='store_true',\n help='When saving a video, emulate the framerate that you\\'d get running in real-time mode.')\n\n parser.set_defaults(no_bar=False, display=False, resume=False, output_coco_json=False, output_web_json=False, shuffle=False,\n benchmark=False, no_sort=False, no_hash=False, mask_proto_debug=False, crop=True, detect=False, display_fps=False,\n emulate_playback=False)\n\n global args\n args = parser.parse_args(argv)\n\n if args.output_web_json:\n args.output_coco_json = True\n \n if args.seed is not None:\n random.seed(args.seed)\n\niou_thresholds = [x / 100 for x in range(50, 100, 5)]\ncoco_cats = {} # Call prep_coco_cats to fill this\ncoco_cats_inv = {}\ncolor_cache = defaultdict(lambda: {})\n\ndef prep_display(dets_out, img, h, w, undo_transform=True, class_color=False, mask_alpha=0.45, fps_str=''):\n \"\"\"\n Note: If undo_transform=False then im_h and im_w are allowed to be None.\n \"\"\"\n if undo_transform:\n img_numpy = undo_image_transformation(img, w, h)\n img_gpu = torch.Tensor(img_numpy).cuda()\n else:\n img_gpu = img / 255.0\n h, w, _ = img.shape\n \n with timer.env('Postprocess'):\n save = cfg.rescore_bbox\n cfg.rescore_bbox = True\n t = postprocess(dets_out, w, h, visualize_lincomb = args.display_lincomb,\n crop_masks = args.crop,\n score_threshold = args.score_threshold)\n cfg.rescore_bbox = save\n\n with timer.env('Copy'):\n idx = t[1].argsort(0, descending=True)[:args.top_k]\n \n if cfg.eval_mask_branch:\n # Masks are drawn on the GPU, so don't copy\n masks = t[3][idx]\n classes, scores, boxes = [x[idx].cpu().numpy() for x in t[:3]]\n\n num_dets_to_consider = min(args.top_k, classes.shape[0])\n for j in range(num_dets_to_consider):\n if scores[j] < args.score_threshold:\n num_dets_to_consider = j\n break\n\n # Quick and dirty lambda for selecting the color for a particular index\n # Also keeps track of a per-gpu color cache for maximum speed\n def get_color(j, on_gpu=None):\n global color_cache\n color_idx = (classes[j] * 5 if class_color else j * 5) % len(COLORS)\n \n if on_gpu is not None and color_idx in color_cache[on_gpu]:\n return color_cache[on_gpu][color_idx]\n else:\n color = COLORS[color_idx]\n if not undo_transform:\n # The image might come in as RGB or BRG, depending\n color = (color[2], color[1], color[0])\n if on_gpu is not None:\n color = torch.Tensor(color).to(on_gpu).float() / 255.\n color_cache[on_gpu][color_idx] = color\n return color\n\n # First, draw the masks on the GPU where we can do it really fast\n # Beware: very fast but possibly unintelligible mask-drawing code ahead\n # I wish I had access to OpenGL or Vulkan but alas, I guess Pytorch tensor operations will have to suffice\n if args.display_masks and cfg.eval_mask_branch and num_dets_to_consider > 0:\n # After this, mask is of size [num_dets, h, w, 1]\n masks = masks[:num_dets_to_consider, :, :, None]\n \n # Prepare the RGB images for each mask given their color (size [num_dets, h, w, 1])\n colors = torch.cat([get_color(j, on_gpu=img_gpu.device.index).view(1, 1, 1, 3) for j in range(num_dets_to_consider)], dim=0)\n masks_color = masks.repeat(1, 1, 1, 3) * colors * mask_alpha\n\n # This is 1 everywhere except for 1-mask_alpha where the mask is\n inv_alph_masks = masks * (-mask_alpha) + 1\n \n # I did the math for this on pen and paper. This whole block should be equivalent to:\n # for j in range(num_dets_to_consider):\n # img_gpu = img_gpu * inv_alph_masks[j] + masks_color[j]\n masks_color_summand = masks_color[0]\n if num_dets_to_consider > 1:\n inv_alph_cumul = inv_alph_masks[:(num_dets_to_consider-1)].cumprod(dim=0)\n masks_color_cumul = masks_color[1:] * inv_alph_cumul\n masks_color_summand += masks_color_cumul.sum(dim=0)\n\n img_gpu = img_gpu * inv_alph_masks.prod(dim=0) + masks_color_summand\n \n if args.display_fps:\n # Draw the box for the fps on the GPU\n font_face = cv2.FONT_HERSHEY_DUPLEX\n font_scale = 0.6\n font_thickness = 1\n\n text_w, text_h = cv2.getTextSize(fps_str, font_face, font_scale, font_thickness)[0]\n\n img_gpu[0:text_h+8, 0:text_w+8] *= 0.6 # 1 - Box alpha\n\n\n # Then draw the stuff that needs to be done on the cpu\n # Note, make sure this is a uint8 tensor or opencv will not anti alias text for whatever reason\n img_numpy = (img_gpu * 255).byte().cpu().numpy()\n\n if args.display_fps:\n # Draw the text on the CPU\n text_pt = (4, text_h + 2)\n text_color = [255, 255, 255]\n\n cv2.putText(img_numpy, fps_str, text_pt, font_face, font_scale, text_color, font_thickness, cv2.LINE_AA)\n \n if num_dets_to_consider == 0:\n return img_numpy\n\n if args.display_text or args.display_bboxes:\n for j in reversed(range(num_dets_to_consider)):\n x1, y1, x2, y2 = boxes[j, :]\n color = get_color(j)\n score = scores[j]\n\n if args.display_bboxes:\n cv2.rectangle(img_numpy, (x1, y1), (x2, y2), color, 1)\n\n if args.display_text:\n _class = cfg.dataset.class_names[classes[j]]\n text_str = '%s: %.2f' % (_class, score) if args.display_scores else _class\n\n font_face = cv2.FONT_HERSHEY_DUPLEX\n font_scale = 0.6\n font_thickness = 1\n\n text_w, text_h = cv2.getTextSize(text_str, font_face, font_scale, font_thickness)[0]\n\n text_pt = (x1, y1 - 3)\n text_color = [255, 255, 255]\n\n cv2.rectangle(img_numpy, (x1, y1), (x1 + text_w, y1 - text_h - 4), color, -1)\n cv2.putText(img_numpy, text_str, text_pt, font_face, font_scale, text_color, font_thickness, cv2.LINE_AA)\n \n \n return img_numpy\n\ndef prep_benchmark(dets_out, h, w):\n with timer.env('Postprocess'):\n t = postprocess(dets_out, w, h, crop_masks=args.crop, score_threshold=args.score_threshold)\n\n with timer.env('Copy'):\n classes, scores, boxes, masks = [x[:args.top_k] for x in t]\n # print('clw: classes.shape:', classes.shape)\n # print('clw: scores.shape:', scores.shape)\n # print('clw: boxes.shape:', boxes.shape)\n # print('clw: masks.shape:', masks.shape)\n if isinstance(scores, list):\n box_scores = scores[0].cpu().numpy()\n mask_scores = scores[1].cpu().numpy()\n else:\n scores = scores.cpu().numpy()\n classes = classes.cpu().numpy()\n boxes = boxes.cpu().numpy()\n masks = masks.cpu().numpy()\n \n with timer.env('Sync'):\n # Just in case\n torch.cuda.synchronize()\n\ndef prep_coco_cats():\n \"\"\" Prepare inverted table for category id lookup given a coco cats object. \"\"\"\n for coco_cat_id, transformed_cat_id_p1 in get_label_map().items():\n transformed_cat_id = transformed_cat_id_p1 - 1\n coco_cats[transformed_cat_id] = coco_cat_id\n coco_cats_inv[coco_cat_id] = transformed_cat_id\n\n\ndef get_coco_cat(transformed_cat_id):\n \"\"\" transformed_cat_id is [0,80) as indices in cfg.dataset.class_names \"\"\"\n return coco_cats[transformed_cat_id]\n\ndef get_transformed_cat(coco_cat_id):\n \"\"\" transformed_cat_id is [0,80) as indices in cfg.dataset.class_names \"\"\"\n return coco_cats_inv[coco_cat_id]\n\n\nclass Detections:\n\n def __init__(self):\n self.bbox_data = []\n self.mask_data = []\n\n def add_bbox(self, image_id:int, category_id:int, bbox:list, score:float):\n \"\"\" Note that bbox should be a list or tuple of (x1, y1, x2, y2) \"\"\"\n bbox = [bbox[0], bbox[1], bbox[2]-bbox[0], bbox[3]-bbox[1]]\n\n # Round to the nearest 10th to avoid huge file sizes, as COCO suggests\n bbox = [round(float(x)*10)/10 for x in bbox]\n\n self.bbox_data.append({\n 'image_id': int(image_id),\n 'category_id': get_coco_cat(int(category_id)),\n 'bbox': bbox,\n 'score': float(score)\n })\n\n def add_mask(self, image_id:int, category_id:int, segmentation:np.ndarray, score:float):\n \"\"\" The segmentation should be the full mask, the size of the image and with size [h, w]. \"\"\"\n rle = pycocotools.mask.encode(np.asfortranarray(segmentation.astype(np.uint8)))\n rle['counts'] = rle['counts'].decode('ascii') # json.dump doesn't like bytes strings\n\n # clw note: segmentation:(h, w), 如(2048, 2448),\n # np.max(self.mask_data[0]['segmentation_clw']) 结果为1\n # np.sum(self.mask_data[0]['segmentation_clw']) 结果为777857\n # 同一幅图,可能有多个dict在mask_data内,因为每个类别对应一个mask,如果检测出n个类,那就是n个dict;\n self.mask_data.append({\n 'image_id': int(image_id),\n 'category_id': get_coco_cat(int(category_id)),\n 'segmentation': rle,\n #'segmentation_clw': segmentation,\n 'score': float(score)\n })\n \n def dump(self):\n dump_arguments = [\n (self.bbox_data, args.bbox_det_file),\n (self.mask_data, args.mask_det_file)\n ]\n\n # aaa = np.max(self.mask_data[0]['segmentation_clw'])\n # bbb = np.sum(self.mask_data[0]['segmentation_clw'])\n for data, path in dump_arguments:\n with open(path, 'w') as f:\n json.dump(data, f)\n \n def dump_web(self):\n \"\"\" Dumps it in the format for my web app. Warning: bad code ahead! \"\"\"\n config_outs = ['preserve_aspect_ratio', 'use_prediction_module',\n 'use_yolo_regressors', 'use_prediction_matching',\n 'train_masks']\n\n output = {\n 'info' : {\n 'Config': {key: getattr(cfg, key) for key in config_outs},\n }\n }\n\n image_ids = list(set([x['image_id'] for x in self.bbox_data]))\n image_ids.sort()\n image_lookup = {_id: idx for idx, _id in enumerate(image_ids)}\n\n output['images'] = [{'image_id': image_id, 'dets': []} for image_id in image_ids]\n\n # These should already be sorted by score with the way prep_metrics works.\n for bbox, mask in zip(self.bbox_data, self.mask_data):\n image_obj = output['images'][image_lookup[bbox['image_id']]]\n image_obj['dets'].append({\n 'score': bbox['score'],\n 'bbox': bbox['bbox'],\n 'category': cfg.dataset.class_names[get_transformed_cat(bbox['category_id'])],\n 'mask': mask['segmentation'],\n })\n\n with open(os.path.join(args.web_det_path, '%s.json' % cfg.name), 'w') as f:\n json.dump(output, f)\n \n\n \n\ndef _mask_iou(mask1, mask2, iscrowd=False):\n with timer.env('Mask IoU'):\n ret = mask_iou(mask1, mask2, iscrowd)\n return ret.cpu()\n\ndef _bbox_iou(bbox1, bbox2, iscrowd=False):\n with timer.env('BBox IoU'):\n ret = jaccard(bbox1, bbox2, iscrowd)\n return ret.cpu()\n\ndef prep_metrics(ap_data, dets, img, gt, gt_masks, h, w, num_crowd, image_id, detections:Detections=None):\n \"\"\" Returns a list of APs for this image, with each element being for a class \"\"\"\n if not args.output_coco_json:\n with timer.env('Prepare gt'):\n gt_boxes = torch.Tensor(gt[:, :4])\n gt_boxes[:, [0, 2]] *= w\n gt_boxes[:, [1, 3]] *= h\n gt_classes = list(gt[:, 4].astype(int))\n gt_masks = torch.Tensor(gt_masks).view(-1, h*w)\n\n if num_crowd > 0:\n split = lambda x: (x[-num_crowd:], x[:-num_crowd])\n crowd_boxes , gt_boxes = split(gt_boxes)\n crowd_masks , gt_masks = split(gt_masks)\n crowd_classes, gt_classes = split(gt_classes)\n\n with timer.env('Postprocess'):\n classes, scores, boxes, masks = postprocess(dets, w, h, crop_masks=args.crop, score_threshold=args.score_threshold)\n\n if classes.size(0) == 0:\n return\n\n classes = list(classes.cpu().numpy().astype(int))\n if isinstance(scores, list):\n box_scores = list(scores[0].cpu().numpy().astype(float))\n mask_scores = list(scores[1].cpu().numpy().astype(float))\n else:\n scores = list(scores.cpu().numpy().astype(float))\n box_scores = scores\n mask_scores = scores\n masks = masks.view(-1, h*w).cuda()\n boxes = boxes.cuda()\n\n\n if args.output_coco_json:\n with timer.env('JSON Output'):\n boxes = boxes.cpu().numpy()\n masks = masks.view(-1, h, w).cpu().numpy()\n for i in range(masks.shape[0]):\n # Make sure that the bounding box actually makes sense and a mask was produced\n if (boxes[i, 3] - boxes[i, 1]) * (boxes[i, 2] - boxes[i, 0]) > 0:\n detections.add_bbox(image_id, classes[i], boxes[i,:], box_scores[i])\n detections.add_mask(image_id, classes[i], masks[i,:,:], mask_scores[i])\n return\n \n with timer.env('Eval Setup'):\n num_pred = len(classes)\n num_gt = len(gt_classes)\n\n mask_iou_cache = _mask_iou(masks, gt_masks)\n bbox_iou_cache = _bbox_iou(boxes.float(), gt_boxes.float())\n\n if num_crowd > 0:\n crowd_mask_iou_cache = _mask_iou(masks, crowd_masks, iscrowd=True)\n crowd_bbox_iou_cache = _bbox_iou(boxes.float(), crowd_boxes.float(), iscrowd=True)\n else:\n crowd_mask_iou_cache = None\n crowd_bbox_iou_cache = None\n\n box_indices = sorted(range(num_pred), key=lambda i: -box_scores[i])\n mask_indices = sorted(box_indices, key=lambda i: -mask_scores[i])\n\n iou_types = [\n ('box', lambda i,j: bbox_iou_cache[i, j].item(),\n lambda i,j: crowd_bbox_iou_cache[i,j].item(),\n lambda i: box_scores[i], box_indices),\n ('mask', lambda i,j: mask_iou_cache[i, j].item(),\n lambda i,j: crowd_mask_iou_cache[i,j].item(),\n lambda i: mask_scores[i], mask_indices)\n ]\n\n timer.start('Main loop')\n for _class in set(classes + gt_classes):\n ap_per_iou = []\n num_gt_for_class = sum([1 for x in gt_classes if x == _class])\n \n for iouIdx in range(len(iou_thresholds)):\n iou_threshold = iou_thresholds[iouIdx]\n\n for iou_type, iou_func, crowd_func, score_func, indices in iou_types:\n gt_used = [False] * len(gt_classes)\n \n ap_obj = ap_data[iou_type][iouIdx][_class]\n ap_obj.add_gt_positives(num_gt_for_class)\n\n for i in indices:\n if classes[i] != _class:\n continue\n \n max_iou_found = iou_threshold\n max_match_idx = -1\n for j in range(num_gt):\n if gt_used[j] or gt_classes[j] != _class:\n continue\n \n iou = iou_func(i, j)\n\n if iou > max_iou_found:\n max_iou_found = iou\n max_match_idx = j\n \n if max_match_idx >= 0:\n gt_used[max_match_idx] = True\n ap_obj.push(score_func(i), True)\n else:\n # If the detection matches a crowd, we can just ignore it\n matched_crowd = False\n\n if num_crowd > 0:\n for j in range(len(crowd_classes)):\n if crowd_classes[j] != _class:\n continue\n \n iou = crowd_func(i, j)\n\n if iou > iou_threshold:\n matched_crowd = True\n break\n\n # All this crowd code so that we can make sure that our eval code gives the\n # same result as COCOEval. There aren't even that many crowd annotations to\n # begin with, but accuracy is of the utmost importance.\n if not matched_crowd:\n ap_obj.push(score_func(i), False)\n timer.stop('Main loop')\n\n\nclass APDataObject:\n \"\"\"\n Stores all the information necessary to calculate the AP for one IoU and one class.\n Note: I type annotated this because why not.\n \"\"\"\n\n def __init__(self):\n self.data_points = []\n self.num_gt_positives = 0\n\n def push(self, score:float, is_true:bool):\n self.data_points.append((score, is_true))\n \n def add_gt_positives(self, num_positives:int):\n \"\"\" Call this once per image. \"\"\"\n self.num_gt_positives += num_positives\n\n def is_empty(self) -> bool:\n return len(self.data_points) == 0 and self.num_gt_positives == 0\n\n def get_ap(self) -> float:\n \"\"\" Warning: result not cached. \"\"\"\n\n if self.num_gt_positives == 0:\n return 0\n\n # Sort descending by score\n self.data_points.sort(key=lambda x: -x[0])\n\n precisions = []\n recalls = []\n num_true = 0\n num_false = 0\n\n # Compute the precision-recall curve. The x axis is recalls and the y axis precisions.\n for datum in self.data_points:\n # datum[1] is whether the detection a true or false positive\n if datum[1]: num_true += 1\n else: num_false += 1\n \n precision = num_true / (num_true + num_false)\n recall = num_true / self.num_gt_positives\n\n precisions.append(precision)\n recalls.append(recall)\n\n # Smooth the curve by computing [max(precisions[i:]) for i in range(len(precisions))]\n # Basically, remove any temporary dips from the curve.\n # At least that's what I think, idk. COCOEval did it so I do too.\n for i in range(len(precisions)-1, 0, -1):\n if precisions[i] > precisions[i-1]:\n precisions[i-1] = precisions[i]\n\n # Compute the integral of precision(recall) d_recall from recall=0->1 using fixed-length riemann summation with 101 bars.\n y_range = [0] * 101 # idx 0 is recall == 0.0 and idx 100 is recall == 1.00\n x_range = np.array([x / 100 for x in range(101)])\n recalls = np.array(recalls)\n\n # I realize this is weird, but all it does is find the nearest precision(x) for a given x in x_range.\n # Basically, if the closest recall we have to 0.01 is 0.009 this sets precision(0.01) = precision(0.009).\n # I approximate the integral this way, because that's how COCOEval does it.\n indices = np.searchsorted(recalls, x_range, side='left')\n for bar_idx, precision_idx in enumerate(indices):\n if precision_idx < len(precisions):\n y_range[bar_idx] = precisions[precision_idx]\n\n # Finally compute the riemann sum to get our integral.\n # avg([precision(x) for x in 0:0.01:1])\n return sum(y_range) / len(y_range)\n\ndef badhash(x):\n \"\"\"\n Just a quick and dirty hash function for doing a deterministic shuffle based on image_id.\n\n Source:\n https://stackoverflow.com/questions/664014/what-integer-hash-function-are-good-that-accepts-an-integer-hash-key\n \"\"\"\n x = (((x >> 16) ^ x) * 0x045d9f3b) & 0xFFFFFFFF\n x = (((x >> 16) ^ x) * 0x045d9f3b) & 0xFFFFFFFF\n x = ((x >> 16) ^ x) & 0xFFFFFFFF\n return x\n\ndef evalimage(net:Yolact, path:str, save_path:str=None):\n frame = torch.from_numpy(cv2.imread(path)).cuda().float()\n batch = FastBaseTransform()(frame.unsqueeze(0))\n preds = net(batch)\n\n img_numpy = prep_display(preds, frame, None, None, undo_transform=False)\n \n if save_path is None:\n img_numpy = img_numpy[:, :, (2, 1, 0)]\n\n if save_path is None:\n plt.imshow(img_numpy)\n plt.title(path)\n plt.show()\n else:\n cv2.imwrite(save_path, img_numpy)\n\ndef evalimages(net:Yolact, input_folder:str, output_folder:str):\n if not os.path.exists(output_folder):\n os.mkdir(output_folder)\n\n print()\n for p in Path(input_folder).glob('*'): \n path = str(p)\n name = os.path.basename(path)\n name = '.'.join(name.split('.')[:-1]) + '.png'\n out_path = os.path.join(output_folder, name)\n\n evalimage(net, path, out_path)\n print(path + ' -> ' + out_path)\n print('Done.')\n\nfrom multiprocessing.pool import ThreadPool\nfrom queue import Queue\n\nclass CustomDataParallel(torch.nn.DataParallel):\n \"\"\" A Custom Data Parallel class that properly gathers lists of dictionaries. \"\"\"\n def gather(self, outputs, output_device):\n # Note that I don't actually want to convert everything to the output_device\n return sum(outputs, [])\n\ndef evalvideo(net:Yolact, path:str, out_path:str=None):\n # If the path is a digit, parse it as a webcam index\n is_webcam = path.isdigit()\n \n # If the input image size is constant, this make things faster (hence why we can use it in a video setting).\n cudnn.benchmark = True\n \n if is_webcam:\n vid = cv2.VideoCapture(int(path))\n else:\n vid = cv2.VideoCapture(path)\n \n if not vid.isOpened():\n print('Could not open video \"%s\"' % path)\n exit(-1)\n\n target_fps = round(vid.get(cv2.CAP_PROP_FPS))\n frame_width = round(vid.get(cv2.CAP_PROP_FRAME_WIDTH))\n frame_height = round(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))\n \n if is_webcam:\n num_frames = float('inf')\n else:\n num_frames = round(vid.get(cv2.CAP_PROP_FRAME_COUNT))\n\n net = CustomDataParallel(net).cuda()\n transform = torch.nn.DataParallel(FastBaseTransform()).cuda()\n frame_times = MovingAverage(100)\n fps = 0\n frame_time_target = 1 / target_fps\n running = True\n fps_str = ''\n vid_done = False\n frames_displayed = 0\n\n if out_path is not None:\n out = cv2.VideoWriter(out_path, cv2.VideoWriter_fourcc(*\"mp4v\"), target_fps, (frame_width, frame_height))\n\n def cleanup_and_exit():\n print()\n pool.terminate()\n vid.release()\n if out_path is not None:\n out.release()\n cv2.destroyAllWindows()\n exit()\n\n def get_next_frame(vid):\n frames = []\n for idx in range(args.video_multiframe):\n frame = vid.read()[1]\n if frame is None:\n return frames\n frames.append(frame)\n return frames\n\n def transform_frame(frames):\n with torch.no_grad():\n frames = [torch.from_numpy(frame).cuda().float() for frame in frames]\n return frames, transform(torch.stack(frames, 0))\n\n def eval_network(inp):\n with torch.no_grad():\n frames, imgs = inp\n num_extra = 0\n while imgs.size(0) < args.video_multiframe:\n imgs = torch.cat([imgs, imgs[0].unsqueeze(0)], dim=0)\n num_extra += 1\n out = net(imgs)\n if num_extra > 0:\n out = out[:-num_extra]\n return frames, out\n\n def prep_frame(inp, fps_str):\n with torch.no_grad():\n frame, preds = inp\n return prep_display(preds, frame, None, None, undo_transform=False, class_color=True, fps_str=fps_str)\n\n frame_buffer = Queue()\n video_fps = 0\n\n # All this timing code to make sure that \n def play_video():\n try:\n nonlocal frame_buffer, running, video_fps, is_webcam, num_frames, frames_displayed, vid_done\n\n video_frame_times = MovingAverage(100)\n frame_time_stabilizer = frame_time_target\n last_time = None\n stabilizer_step = 0.0005\n progress_bar = ProgressBar(30, num_frames)\n\n while running:\n frame_time_start = time.time()\n\n if not frame_buffer.empty():\n next_time = time.time()\n if last_time is not None:\n video_frame_times.add(next_time - last_time)\n video_fps = 1 / video_frame_times.get_avg()\n if out_path is None:\n cv2.imshow(path, frame_buffer.get())\n else:\n out.write(frame_buffer.get())\n frames_displayed += 1\n last_time = next_time\n\n if out_path is not None:\n if video_frame_times.get_avg() == 0:\n fps = 0\n else:\n fps = 1 / video_frame_times.get_avg()\n progress = frames_displayed / num_frames * 100\n progress_bar.set_val(frames_displayed)\n\n print('\\rProcessing Frames %s %6d / %6d (%5.2f%%) %5.2f fps '\n % (repr(progress_bar), frames_displayed, num_frames, progress, fps), end='')\n\n \n # This is split because you don't want savevideo to require cv2 display functionality (see #197)\n if out_path is None and cv2.waitKey(1) == 27:\n # Press Escape to close\n running = False\n if not (frames_displayed < num_frames):\n running = False\n\n if not vid_done:\n buffer_size = frame_buffer.qsize()\n if buffer_size < args.video_multiframe:\n frame_time_stabilizer += stabilizer_step\n elif buffer_size > args.video_multiframe:\n frame_time_stabilizer -= stabilizer_step\n if frame_time_stabilizer < 0:\n frame_time_stabilizer = 0\n\n new_target = frame_time_stabilizer if is_webcam else max(frame_time_stabilizer, frame_time_target)\n else:\n new_target = frame_time_target\n\n next_frame_target = max(2 * new_target - video_frame_times.get_avg(), 0)\n target_time = frame_time_start + next_frame_target - 0.001 # Let's just subtract a millisecond to be safe\n \n if out_path is None or args.emulate_playback:\n # This gives more accurate timing than if sleeping the whole amount at once\n while time.time() < target_time:\n time.sleep(0.001)\n else:\n # Let's not starve the main thread, now\n time.sleep(0.001)\n except:\n # See issue #197 for why this is necessary\n import traceback\n traceback.print_exc()\n\n\n extract_frame = lambda x, i: (x[0][i] if x[1][i]['detection'] is None else x[0][i].to(x[1][i]['detection']['box'].device), [x[1][i]])\n\n # Prime the network on the first frame because I do some thread unsafe things otherwise\n print('Initializing model... ', end='')\n first_batch = eval_network(transform_frame(get_next_frame(vid)))\n print('Done.')\n\n # For each frame the sequence of functions it needs to go through to be processed (in reversed order)\n sequence = [prep_frame, eval_network, transform_frame]\n pool = ThreadPool(processes=len(sequence) + args.video_multiframe + 2)\n pool.apply_async(play_video)\n active_frames = [{'value': extract_frame(first_batch, i), 'idx': 0} for i in range(len(first_batch[0]))]\n\n print()\n if out_path is None: print('Press Escape to close.')\n try:\n while vid.isOpened() and running:\n # Hard limit on frames in buffer so we don't run out of memory >.>\n while frame_buffer.qsize() > 100:\n time.sleep(0.001)\n\n start_time = time.time()\n\n # Start loading the next frames from the disk\n if not vid_done:\n next_frames = pool.apply_async(get_next_frame, args=(vid,))\n else:\n next_frames = None\n \n if not (vid_done and len(active_frames) == 0):\n # For each frame in our active processing queue, dispatch a job\n # for that frame using the current function in the sequence\n for frame in active_frames:\n _args = [frame['value']]\n if frame['idx'] == 0:\n _args.append(fps_str)\n frame['value'] = pool.apply_async(sequence[frame['idx']], args=_args)\n \n # For each frame whose job was the last in the sequence (i.e. for all final outputs)\n for frame in active_frames:\n if frame['idx'] == 0:\n frame_buffer.put(frame['value'].get())\n\n # Remove the finished frames from the processing queue\n active_frames = [x for x in active_frames if x['idx'] > 0]\n\n # Finish evaluating every frame in the processing queue and advanced their position in the sequence\n for frame in list(reversed(active_frames)):\n frame['value'] = frame['value'].get()\n frame['idx'] -= 1\n\n if frame['idx'] == 0:\n # Split this up into individual threads for prep_frame since it doesn't support batch size\n active_frames += [{'value': extract_frame(frame['value'], i), 'idx': 0} for i in range(1, len(frame['value'][0]))]\n frame['value'] = extract_frame(frame['value'], 0)\n \n # Finish loading in the next frames and add them to the processing queue\n if next_frames is not None:\n frames = next_frames.get()\n if len(frames) == 0:\n vid_done = True\n else:\n active_frames.append({'value': frames, 'idx': len(sequence)-1})\n\n # Compute FPS\n frame_times.add(time.time() - start_time)\n fps = args.video_multiframe / frame_times.get_avg()\n else:\n fps = 0\n \n fps_str = 'Processing FPS: %.2f | Video Playback FPS: %.2f | Frames in Buffer: %d' % (fps, video_fps, frame_buffer.qsize())\n if not args.display_fps:\n print('\\r' + fps_str + ' ', end='')\n\n except KeyboardInterrupt:\n print('\\nStopping...')\n \n cleanup_and_exit()\n\ndef evaluate(net:Yolact, dataset, train_mode=False):\n net.detect.use_fast_nms = args.fast_nms\n net.detect.use_cross_class_nms = args.cross_class_nms\n cfg.mask_proto_debug = args.mask_proto_debug\n\n # TODO Currently we do not support Fast Mask Re-scroing in evalimage, evalimages, and evalvideo\n if args.image is not None:\n if ':' in args.image:\n inp, out = args.image.split(':')\n evalimage(net, inp, out)\n else:\n evalimage(net, args.image)\n return\n elif args.images is not None:\n inp, out = args.images.split(':')\n evalimages(net, inp, out) # clw note: 输出所有测试集图片的可视化预测结果\n return\n elif args.video is not None:\n if ':' in args.video:\n inp, out = args.video.split(':')\n evalvideo(net, inp, out)\n else:\n evalvideo(net, args.video)\n return\n\n frame_times = MovingAverage()\n dataset_size = len(dataset) if args.max_images < 0 else min(args.max_images, len(dataset))\n progress_bar = ProgressBar(30, dataset_size)\n\n print()\n\n if not args.display and not args.benchmark:\n # For each class and iou, stores tuples (score, isPositive)\n # Index ap_data[type][iouIdx][classIdx]\n ap_data = {\n 'box' : [[APDataObject() for _ in cfg.dataset.class_names] for _ in iou_thresholds],\n 'mask': [[APDataObject() for _ in cfg.dataset.class_names] for _ in iou_thresholds]\n }\n detections = Detections()\n else:\n timer.disable('Load Data')\n\n dataset_indices = list(range(len(dataset)))\n \n if args.shuffle:\n random.shuffle(dataset_indices)\n elif not args.no_sort:\n # Do a deterministic shuffle based on the image ids\n #\n # I do this because on python 3.5 dictionary key order is *random*, while in 3.6 it's\n # the order of insertion. That means on python 3.6, the images come in the order they are in\n # in the annotations file. For some reason, the first images in the annotations file are\n # the hardest. To combat this, I use a hard-coded hash function based on the image ids\n # to shuffle the indices we use. That way, no matter what python version or how pycocotools\n # handles the data, we get the same result every time.\n hashed = [badhash(x) for x in dataset.ids]\n dataset_indices.sort(key=lambda x: hashed[x])\n\n dataset_indices = dataset_indices[:dataset_size]\n\n try:\n # Main eval loop\n for it, image_idx in enumerate(dataset_indices):\n timer.reset()\n\n with timer.env('Load Data'):\n img, gt, gt_masks, h, w, num_crowd = dataset.pull_item(image_idx)\n\n # Test flag, do not upvote\n if cfg.mask_proto_debug:\n with open('scripts/info.txt', 'w') as f:\n f.write(str(dataset.ids[image_idx]))\n np.save('scripts/gt.npy', gt_masks)\n\n batch = Variable(img.unsqueeze(0))\n if args.cuda:\n batch = batch.cuda()\n\n with timer.env('Network Extra'):\n preds = net(batch)\n # Perform the meat of the operation here depending on our mode.\n if args.display:\n img_numpy = prep_display(preds, img, h, w)\n elif args.benchmark:\n prep_benchmark(preds, h, w)\n else:\n prep_metrics(ap_data, preds, img, gt, gt_masks, h, w, num_crowd, dataset.ids[image_idx], detections)\n \n # First couple of images take longer because we're constructing the graph.\n # Since that's technically initialization, don't include those in the FPS calculations.\n if it > 1:\n frame_times.add(timer.total_time())\n \n if args.display:\n if it > 1:\n print('Avg FPS: %.4f' % (1 / frame_times.get_avg()))\n plt.imshow(img_numpy)\n plt.title(str(dataset.ids[image_idx]))\n plt.show()\n elif not args.no_bar:\n if it > 1: fps = 1 / frame_times.get_avg()\n else: fps = 0\n progress = (it+1) / dataset_size * 100\n progress_bar.set_val(it+1)\n print('\\rProcessing Images %s %6d / %6d (%5.2f%%) %5.2f fps '\n % (repr(progress_bar), it+1, dataset_size, progress, fps), end='')\n\n\n\n if not args.display and not args.benchmark:\n print()\n if args.output_coco_json:\n print('Dumping detections...')\n if args.output_web_json:\n detections.dump_web()\n else:\n print('clw: dump json file !!')\n detections.dump()\n else:\n if not train_mode:\n print('Saving data...')\n with open(args.ap_data_file, 'wb') as f:\n pickle.dump(ap_data, f)\n\n return calc_map(ap_data)\n elif args.benchmark:\n print()\n print()\n print('Stats for the last frame:')\n timer.print_stats()\n avg_seconds = frame_times.get_avg()\n print('Average: %5.2f fps, %5.2f ms' % (1 / frame_times.get_avg(), 1000*avg_seconds))\n\n except KeyboardInterrupt:\n print('Stopping...')\n\n\ndef calc_map(ap_data):\n print('Calculating mAP...')\n aps = [{'box': [], 'mask': []} for _ in iou_thresholds]\n\n for _class in range(len(cfg.dataset.class_names)):\n for iou_idx in range(len(iou_thresholds)):\n for iou_type in ('box', 'mask'):\n ap_obj = ap_data[iou_type][iou_idx][_class]\n\n if not ap_obj.is_empty():\n aps[iou_idx][iou_type].append(ap_obj.get_ap())\n\n all_maps = {'box': OrderedDict(), 'mask': OrderedDict()}\n\n # Looking back at it, this code is really hard to read :/\n for iou_type in ('box', 'mask'):\n all_maps[iou_type]['all'] = 0 # Make this first in the ordereddict\n for i, threshold in enumerate(iou_thresholds):\n mAP = sum(aps[i][iou_type]) / len(aps[i][iou_type]) * 100 if len(aps[i][iou_type]) > 0 else 0\n all_maps[iou_type][int(threshold*100)] = mAP\n all_maps[iou_type]['all'] = (sum(all_maps[iou_type].values()) / (len(all_maps[iou_type].values())-1))\n \n print_maps(all_maps)\n \n # Put in a prettier format so we can serialize it to json during training\n all_maps = {k: {j: round(u, 2) for j, u in v.items()} for k, v in all_maps.items()}\n return all_maps\n\ndef print_maps(all_maps):\n # Warning: hacky \n make_row = lambda vals: (' %5s |' * len(vals)) % tuple(vals)\n make_sep = lambda n: ('-------+' * n)\n\n print()\n print(make_row([''] + [('.%d ' % x if isinstance(x, int) else x + ' ') for x in all_maps['box'].keys()]))\n print(make_sep(len(all_maps['box']) + 1))\n for iou_type in ('box', 'mask'):\n print(make_row([iou_type] + ['%.2f' % x if x < 100 else '%.1f' % x for x in all_maps[iou_type].values()]))\n print(make_sep(len(all_maps['box']) + 1))\n print()\n\n\n\nif __name__ == '__main__':\n parse_args()\n\n if args.config is not None:\n set_cfg(args.config) # clw note:用我自己在config.py里面自定义的pear_config 替换 cfg变量(默认是yolact_base_config)的配置\n # pear_config就是一个Config类的对象,这个类包括一个dict成员,存放配置项,也包括copy、replace方法;\n # 作者搞这个类的初衷就是希望在读/写配置项的时候可以写成 cfg.x 而不是写成 cfg['x'],作者认为那样写很蠢\n if args.trained_model == 'interrupt':\n args.trained_model = SavePath.get_interrupt('weights/')\n elif args.trained_model == 'latest':\n args.trained_model = SavePath.get_latest('weights/', cfg.name)\n\n if args.config is None:\n model_path = SavePath.from_str(args.trained_model)\n # TODO: Bad practice? Probably want to do a name lookup instead.\n args.config = model_path.model_name + '_config'\n print('Config not specified. Parsed %s from the file name.\\n' % args.config)\n set_cfg(args.config)\n\n if args.detect:\n cfg.eval_mask_branch = False\n\n if args.dataset is not None:\n set_dataset(args.dataset)\n\n with torch.no_grad():\n if not os.path.exists('results'):\n os.makedirs('results')\n\n if args.cuda:\n cudnn.fastest = True\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n else:\n torch.set_default_tensor_type('torch.FloatTensor')\n\n if args.resume and not args.display:\n with open(args.ap_data_file, 'rb') as f:\n ap_data = pickle.load(f)\n calc_map(ap_data)\n exit()\n\n if args.image is None and args.video is None and args.images is None:\n dataset = COCODetection(cfg.dataset.valid_images, cfg.dataset.valid_info,\n transform=BaseTransform(), has_gt=cfg.dataset.has_gt)\n prep_coco_cats()\n else:\n dataset = None \n\n print('Loading model...', end='')\n net = Yolact()\n net.load_weights(args.trained_model)\n net.eval()\n print(' Done.')\n\n if args.cuda:\n net = net.cuda()\n\n evaluate(net, dataset)\n\n\n"
] |
[
[
"torch.set_default_tensor_type",
"torch.cuda.synchronize",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.title",
"torch.Tensor",
"torch.from_numpy",
"numpy.save",
"torch.no_grad",
"numpy.searchsorted",
"torch.stack",
"numpy.array",
"matplotlib.pyplot.show"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
RiceAstroparticleLab/strax
|
[
"38a7fcb58e92e20a3441ba008b7598de65068ed0"
] |
[
"strax/dtypes.py"
] |
[
"\"\"\"Fundamental dtypes for use in strax.\n\nNote that if you change the dtype titles (comments), numba will crash if\nthere is an existing numba cache. Clear __pycache__ and restart.\nTODO: file numba issue.\n\"\"\"\nimport numpy as np\nimport typing as ty\nimport numba\n\n\n__all__ = ('interval_dtype raw_record_dtype record_dtype hit_dtype peak_dtype '\n 'DIGITAL_SUM_WAVEFORM_CHANNEL DEFAULT_RECORD_LENGTH '\n 'time_fields time_dt_fields hitlet_dtype hitlet_with_data_dtype '\n 'copy_to_buffer peak_interval_dtype').split()\n\nDIGITAL_SUM_WAVEFORM_CHANNEL = -1\nDEFAULT_RECORD_LENGTH = 110\n\n\ntime_fields = [\n (('Start time since unix epoch [ns]',\n 'time'), np.int64),\n (('Exclusive end time since unix epoch [ns]',\n 'endtime'), np.int64)]\n\ntime_dt_fields = [\n (('Start time since unix epoch [ns]',\n 'time'), np.int64),\n # Don't try to make O(second) long intervals!\n (('Length of the interval in samples',\n 'length'), np.int32),\n (('Width of one sample [ns]',\n 'dt'), np.int16)]\n\n# Base dtype for interval-like objects (pulse, hit)\ninterval_dtype = time_dt_fields + [\n (('Channel/PMT number',\n 'channel'), np.int16)]\n\n# Base dtype with interval like objects for long objects (peaks)\npeak_interval_dtype = interval_dtype.copy()\n# Allow peaks to have very long dts\npeak_interval_dtype[2] = (('Width of one sample [ns]', 'dt'), np.int32)\n\ndef raw_record_dtype(samples_per_record=DEFAULT_RECORD_LENGTH):\n \"\"\"Data type for a waveform raw_record.\n\n Length can be shorter than the number of samples in data,\n this indicates a record with zero-padding at the end.\n \"\"\"\n return interval_dtype + [\n # np.int16 is not enough for some PMT flashes...\n (('Length of pulse to which the record belongs (without zero-padding)',\n 'pulse_length'), np.int32),\n (('Fragment number in the pulse',\n 'record_i'), np.int16),\n (('Baseline determined by the digitizer (if this is supported)',\n 'baseline'), np.int16),\n # Note this is defined as a SIGNED integer, so we can\n # still represent negative values after subtracting baselines\n (('Waveform data in raw ADC counts',\n 'data'), np.int16, samples_per_record)]\n\n\ndef record_dtype(samples_per_record=DEFAULT_RECORD_LENGTH):\n \"\"\"Data type for a waveform record.\n\n Length can be shorter than the number of samples in data,\n this indicates a record with zero-padding at the end.\n \"\"\"\n return interval_dtype + [\n # np.int16 is not enough for some PMT flashes...\n (('Length of pulse to which the record belongs (without zero-padding)',\n 'pulse_length'), np.int32),\n (('Fragment number in the pulse',\n 'record_i'), np.int16),\n ((\"Integral in ADC counts x samples\",\n 'area'), np.int32),\n (('Level of data reduction applied (strax.ReductionLevel enum)',\n 'reduction_level'), np.uint8),\n (('Baseline in ADC counts. data = int(baseline) - data_orig',\n 'baseline'), np.float32),\n (('Baseline RMS in ADC counts. data = baseline - data_orig',\n 'baseline_rms'), np.float32),\n (('Multiply data by 2**(this number). Baseline is unaffected.',\n 'amplitude_bit_shift'), np.int16),\n (('Waveform data in raw counts above integer part of baseline',\n 'data'), np.int16, samples_per_record),\n ]\n\n\n# Data type for a 'hit': a sub-range of a record\nhit_dtype = interval_dtype + [\n ((\"Integral [ADC x samples]\",\n 'area'), np.float32),\n (('Index of sample in record in which hit starts',\n 'left'), np.int16),\n (('Index of first sample in record just beyond hit (exclusive bound)',\n 'right'), np.int16),\n (('For lone hits, index of sample in record where integration starts',\n 'left_integration'), np.int16),\n (('For lone hits, index of first sample beyond integration region',\n 'right_integration'), np.int16),\n (('Internal (temporary) index of fragment in which hit was found',\n 'record_i'), np.int32),\n (('ADC threshold applied in order to find hits',\n 'threshold'), np.float32),\n (('Maximum amplitude above baseline [ADC counts]',\n 'height'), np.float32),\n]\n\n\ndef hitlet_dtype():\n \"\"\"\n Hitlet dtype same as peaklet or peak dtype but for hit-kind of\n objects.\n \"\"\"\n dtype = interval_dtype + [\n (('Total hit area in pe',\n 'area'), np.float32),\n (('Maximum of the PMT pulse in pe/sample',\n 'amplitude'), np.float32),\n (('Position of the Amplitude in ns (minus \"time\")',\n 'time_amplitude'), np.int16),\n (('Hit entropy',\n 'entropy'), np.float32),\n (('Width (in ns) of the central 50% area of the hitlet',\n 'range_50p_area'), np.float32),\n (('Width (in ns) of the central 80% area of the hitlet',\n 'range_80p_area'), np.float32),\n (('Position of the 25% area decile [ns]',\n 'left_area'), np.float32),\n (('Position of the 10% area decile [ns]',\n 'low_left_area'), np.float32),\n (('Width (in ns) of the highest density region covering a 50% area of the hitlet',\n 'range_hdr_50p_area'), np.float32),\n (('Width (in ns) of the highest density region covering a 80% area of the hitlet',\n 'range_hdr_80p_area'), np.float32),\n (('Left edge of the 50% highest density region [ns]',\n 'left_hdr'), np.float32),\n (('Left edge of the 80% highest density region [ns]',\n 'low_left_hdr'), np.float32),\n (('FWHM of the PMT pulse [ns]',\n 'fwhm'), np.float32),\n (('Left edge of the FWHM [ns] (minus \"time\")',\n 'left'), np.float32),\n (('FWTM of the PMT pulse [ns]', 'fwtm'),\n np.float32),\n (('Left edge of the FWTM [ns] (minus \"time\")',\n 'low_left'), np.float32),]\n return dtype\n\n\ndef hitlet_with_data_dtype(n_samples=2):\n \"\"\"\n Hitlet dtype with data field. Required within the plugins to compute\n hitlet properties. \n \n :param n_samples: Buffer length of the data field. Make sure it can\n hold the longest hitlet.\n \"\"\"\n if n_samples < 2:\n raise ValueError('n_samples must be at least 2!')\n\n dtype = hitlet_dtype()\n additional_fields = [(('Hitlet data in PE/sample with ZLE (only the first length samples are filled)', 'data'),\n np.float32, n_samples),\n (('Dummy field required for splitting',\n 'max_gap'), np.int32),\n (('Maximum interior goodness of split',\n 'max_goodness_of_split'), np.float32),\n ]\n\n return dtype + additional_fields\n\n\ndef peak_dtype(n_channels=100, n_sum_wv_samples=200, n_widths=11):\n \"\"\"Data type for peaks - ranges across all channels in a detector\n Remember to set channel to -1 (todo: make enum)\n \"\"\"\n if n_channels == 1:\n raise ValueError(\"Must have more than one channel\")\n # Otherwise array changes shape?? badness ensues\n return peak_interval_dtype + [\n # For peaklets this is likely to be overwritten:\n (('Classification of the peak(let)',\n 'type'), np.int8),\n (('S1 ln probability',\n 's1_prob'), np.float32),\n (('S2 ln probability',\n 's2_prob'), np.float32),\n (('Integral across channels [PE]',\n 'area'), np.float32),\n (('Integral per channel [PE]',\n 'area_per_channel'), np.float32, n_channels),\n ((\"Number of hits contributing at least one sample to the peak \",\n 'n_hits'), np.int32),\n (('Waveform data in PE/sample (not PE/ns!)',\n 'data'), np.float32, n_sum_wv_samples),\n (('Peak widths in range of central area fraction [ns]',\n 'width'), np.float32, n_widths),\n (('Peak widths: time between nth and 5th area decile [ns]',\n 'area_decile_from_midpoint'), np.float32, n_widths),\n (('Does the channel reach ADC saturation?',\n 'saturated_channel'), np.int8, n_channels),\n (('Total number of saturated channels',\n 'n_saturated_channels'), np.int16),\n (('Channel within tight range of mean',\n 'tight_coincidence'), np.int16),\n (('Largest gap between hits inside peak [ns]',\n 'max_gap'), np.int32),\n (('Maximum interior goodness of split',\n 'max_goodness_of_split'), np.float32),\n ]\n\n\ndef copy_to_buffer(source: np.ndarray,\n buffer: np.ndarray,\n func_name: str,\n field_names: ty.Tuple[str] = None):\n \"\"\"\n Copy the data from the source to the destination e.g. raw_records to\n records. To this end, we dynamically create the njitted function\n with the name 'func_name' (should start with \"_\").\n\n :param source: array of input\n :param buffer: array of buffer to fill with values from input\n :param func_name: how to store the dynamically created function.\n Should start with an _underscore\n :param field_names: dtype names to copy (if none, use all in the\n source)\n \"\"\"\n if np.shape(source) != np.shape(buffer):\n raise ValueError('Source should be the same length as the buffer')\n\n if field_names is None:\n # To lazy to specify what to copy, just do all\n field_names = tuple(n for n in source.dtype.names\n if n in buffer.dtype.names)\n elif not any([n in buffer.dtype.names for n in field_names]):\n raise ValueError('Trying to copy dtypes that are not in the '\n 'destination')\n\n if not func_name.startswith('_'):\n raise ValueError('Start function with \"_\"')\n\n if func_name not in globals():\n # Create a numba function for us\n _create_copy_function(buffer.dtype, field_names, func_name)\n\n globals()[func_name](source, buffer)\n\n\ndef _create_copy_function(res_dtype, field_names, func_name):\n \"\"\"Write out a numba-njitted function to copy data\"\"\"\n # Cannot cache = True since we are creating the function dynamically\n code = f'''\[email protected](nogil=True)\ndef {func_name}(source, result): \n for i in range(len(source)):\n s = source[i]\n r = result[i]\n'''\n for d in field_names:\n if d not in res_dtype.names:\n raise ValueError('This cannot happen')\n if np.shape(res_dtype[d]):\n # Copy array fields as arrays\n code += f'\\n r[\"{d}\"][:] = s[\"{d}\"][:]'\n else:\n code += f'\\n r[\"{d}\"] = s[\"{d}\"]'\n # pylint: disable=exec-used\n exec(code, globals())\n"
] |
[
[
"numpy.shape"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
disc5/DyraLib
|
[
"74045c5e7cadb1b6469fb0bbccd96d8ff7b0d47b"
] |
[
"Matlab/PLNet/python_tensorflow/dypy/utils.py"
] |
[
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nUtility functions for dyad ranking / PyDR\r\n\r\n(2017/1)\r\n@author: Dirk Schaefer\r\n\"\"\"\r\n#%%\r\nfrom __future__ import division\r\nimport numpy as np\r\n#%%\r\ndef convert_orderingvec_to_rankingvec(ordering):\r\n '''\r\n Converts an ordering vector to a ranking vector (of dim M).\r\n Elements of the vectors are natural numbers 1..M.\r\n \r\n Args:\r\n ordering - numpy 1d array\r\n \r\n Returns:\r\n ranking - numpy 1d array\r\n '''\r\n M = ordering.size\r\n ranking = -1 * np.ones(M)\r\n for i1 in range(0,M):\r\n item_id = ordering[i1]\r\n if item_id > -1:\r\n ranking[item_id-1] = (i1+1)\r\n return ranking\r\n\r\n#%%\r\ndef convert_orderingmat_to_rankingmat(Orderings):\r\n '''\r\n Converts an NxM matrix of N-many ordering row vectors into a matrix of\r\n rankings.\r\n \r\n Args:\r\n Orderings - numpy ndarray of natural numbers (1..M)\r\n \r\n Returns:\r\n Rankings - numpy ndarry of natural numbers (1..M)\r\n '''\r\n (Rows,Cols) = Orderings.shape \r\n Rankings = -1 * np.ones((Rows, Cols))\r\n for i1 in range(0,Rows):\r\n Rankings[i1,:] = convert_orderingvec_to_rankingvec(Orderings[i1,:])\r\n return Rankings\r\n\r\n#%%\r\ndef convert_rankingvec_to_orderingvec(ranking):\r\n '''\r\n Converts a ranking vector to an ordering vector (of dim M).\r\n Elements of the vectors are natural numbers 1..M.\r\n \r\n Args:\r\n ranking - numpy 1d array\r\n \r\n Returns:\r\n ordering - numpy 1d array\r\n \r\n Examples:\r\n Example 1 (complete ranking of length 4)\r\n R = (3,1,4,2) corresponds to O = (2,4,1,3)\r\n\r\n Example 2 (incomplete ranking)\r\n R = (-1,1,3,2) corresponds to O = (2,4,3,-1)\r\n '''\r\n M = ranking.size\r\n ordering = -1 * np.ones(M, dtype=np.int32)\r\n for i1 in range(0,M):\r\n r_pos = ranking[i1] # rank position of i-th label\r\n if r_pos > -1:\r\n ordering[r_pos-1] = int(i1+1)\r\n return ordering\r\n\r\n#%%\r\ndef convert_rankingmat_to_orderingmat(Rankings):\r\n '''\r\n Converts an NxM matrix of N-many ranking row vectors into a matrix of\r\n orderings.\r\n \r\n Args:\r\n Rankings - numpy ndarray of natural numbers (1..M)\r\n \r\n Returns:\r\n Orderings - numpy ndarry of natural numbers (1..M)\r\n '''\r\n (Rows,Cols) = Rankings.shape \r\n Orderings = -1 * np.ones((Rows, Cols), dtype=np.int64)\r\n for i1 in range(0,Rows):\r\n Orderings[i1,:] = convert_rankingvec_to_orderingvec(Rankings[i1,:])\r\n return Orderings\r\n\r\n#%%\r\ndef invert_rankingmat(Rankings):\r\n '''\r\n Inverts an NxM (row-structured) ranking matrix.\r\n It assigns each value of a row its maximum minus that value + 1.\r\n Incomplete rankings are supported, i.e. existing -1 values are ignored.\r\n \r\n Args: \r\n Rankings - numpy ndarray \r\n \r\n Returns:\r\n InvRankings - numpy ndarray\r\n \r\n Note:\r\n This function converts rankings into relevance scores.\r\n By that it can be used for CGKronRLS:\r\n - given an ordering,\r\n - convert it to a ranking\r\n - convert it to a relevance score\r\n - rescale it btw [0,1]\r\n '''\r\n (nRows, nCols) = Rankings.shape\r\n Relevance = -1.*np.ones((nRows, nCols))\r\n for i1 in range(0, nRows):\r\n row = Rankings[i1,:]\r\n rmax = max(row)\r\n for i2 in range(0, nCols):\r\n if Rankings[i1,i2] > -1:\r\n Relevance[i1,i2] = (rmax-Rankings[i1,i2]+1) \r\n return Relevance\r\n\r\n#%%\r\ndef convert_relevancescorevec_to_rankingvec(RelevanceVec):\r\n '''\r\n Given a vector of relevance scores, expressed as natural\r\n numbers 1..M (e.g. associated to a common QID) of M query-document vectors,\r\n this function converts relevance scores (where a high score corresponds to a top rank)\r\n into a ranking vector.\r\n '''\r\n n = RelevanceVec.size\r\n temp_ordering = RelevanceVec.argsort()[::-1][:n]+1\r\n return convert_orderingvec_to_rankingvec(temp_ordering)\r\n \r\n#%%\r\ndef convert_relevancescoresmat_to_rankingmat(RelevanceMat):\r\n '''\r\n Given a matrix of relevance vectors in rows.\r\n This function converts the matrix into a matrix where the \r\n row vectors are rankings.\r\n \r\n This function can be used to convert testlabels (from L2R format)\r\n into rankings for evaluation purposes. \r\n '''\r\n (nRows, nCols) = RelevanceMat.shape\r\n RankingMat = np.zeros((nRows,nCols))\r\n for i1 in range(0, nRows):\r\n RankingMat[i1,:] = convert_relevancescorevec_to_rankingvec(RelevanceMat[i1,:])\r\n return RankingMat\r\n \r\n#%%\r\ndef kendallstau_on_rankingvec(r1, r2):\r\n '''\r\n Calculates Kendall's tau on two rankings (or likewise permutations).\r\n \r\n Args:\r\n r1, r2 - list of M integers\r\n \r\n Returns:\r\n tau - a scalar\r\n '''\r\n M = r1.size\r\n C = 0\r\n D = 0\r\n for i1 in range(0,M):\r\n for i2 in range(i1+1, M):\r\n p = (r1[i1]-r1[i2]) * (r2[i1]-r2[i2])\r\n if p>=0:\r\n C = C + 1\r\n else:\r\n D = D + 1\r\n denom = M * (M-1) / 2\r\n return (float(C)-float(D)) / float(denom)\r\n\r\n#%%\r\ndef kendallstau_on_rankingmat(R1,R2):\r\n '''\r\n Calculates the Kendall's tau Distances between row vectors of R1 and R2.\r\n \r\n Args: \r\n R1 and R2 must be matrices with the same dimensionality.\r\n \r\n Returns:\r\n mKtau - mean Ktau value\r\n Ktaus - vector of ktau value\r\n '''\r\n (nRows, nCols) = R1.shape\r\n Ktaus = np.zeros(nRows)\r\n for i1 in range(0, nRows):\r\n Ktaus[i1] = kendallstau_on_rankingvec(R1[i1,:],R2[i1,:])\r\n return (Ktaus.mean(), Ktaus)\r\n\r\n#%%\r\ndef rescale_rankingmat(Rankings):\r\n '''\r\n Rescales the values of a possibly incomplete ranking matrix to the number range [0,1].\r\n It treats each row of the Ranking matrix separatly.\r\n \r\n Args:\r\n Rankings - NxM numpy ndarray of natural numbers, where -1 denotes a missing value.\r\n \r\n Returns:\r\n Rescaled - NxM numpy ndarray matrix which contains values within [0,1] or -1 as missing value.\r\n \r\n Note:\r\n This function could be used in conjunction with CgKronRLS.\r\n '''\r\n (nRows, nCols) = Rankings.shape\r\n Rescaled = -1.*np.ones((nRows, nCols))\r\n for i1 in range(0, nRows):\r\n row = Rankings[i1,:]\r\n rmax = max(row)\r\n rmin = 1;\r\n Denom = rmax-rmin\r\n for i2 in range(0, nCols):\r\n if Rankings[i1,i2] > -1:\r\n Rescaled[i1,i2] = (Rankings[i1,i2]-rmin)/Denom \r\n return Rescaled \r\n\r\ndef create_contextualized_concat_orderings(X, Y, Y_orderings):\r\n ''' Creates a list of lists from X and Y feature vectors.\r\n \r\n This method concatenates X and Y pairs and order them\r\n according to the matrix Y_orderings.\r\n \r\n Args:\r\n X : N x p list of lists / np array - instance feature vectors in rows.\r\n Y : M x q list of list - label feature vectors in rows.\r\n Y_orderings : list of N (potentially incomplete) ordering lists\r\n \r\n Returns:\r\n list of lists : orderings of concatenated feature vectors.\r\n \r\n Examples:\r\n This function can be used for preparing PLNet inputs. E.g. \r\n for label ranking data:\r\n Z = create_contextualized_concat_orderings(X.tolist(), ...\r\n np.eye(M, dtype=np.int32).tolist() , ...\r\n dp.utils.convert_rankingmat_to_orderingmat(R))\r\n '''\r\n N = len(Y_orderings)\r\n Z = []\r\n for i1 in range(N):\r\n Z.append([X[i1] + Y[i0-1] for i0 in Y_orderings[i1]])\r\n return Z\r\n\r\n#%%\r\ndef get_kronecker_feature_map_tensor(XFeat, YFeat):\r\n \"\"\"\r\n Produces a tensor of the format rows x cols x features.\r\n This produces a contextualized dyad ranking tensor.\r\n \r\n Args:\r\n XFeat : ndarray (matrix Nxp)\r\n YFeat : ndarry (matrix Mxq)\r\n \r\n Returns:\r\n jf_tensor : ndarray (tensor N x M x (p*q))\r\n \r\n \"\"\"\r\n (N,p) = XFeat.shape\r\n (M,q) = YFeat.shape\r\n\r\n kronTensor = np.zeros([N,M, p*q], dtype=np.float64)\r\n\r\n for i1 in range(0,N):\r\n for i2 in range(0,M):\r\n kfeat = np.kron(XFeat[i1,:],YFeat[i2,:])\r\n kronTensor[i1,i2,:] = kfeat\r\n \r\n return kronTensor\r\n "
] |
[
[
"numpy.kron",
"numpy.zeros",
"numpy.ones"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
yohai/pde-superresolution
|
[
"5ed0d4c4d039c9a8ed2b197a07839c83fea89251",
"5ed0d4c4d039c9a8ed2b197a07839c83fea89251"
] |
[
"pde_superresolution/scripts/create_training_data.py",
"pde_superresolution/duckarray.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\"\"\"Run a beam pipeline to generate training data.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport json\nimport os.path\n\nfrom absl import app\nfrom absl import flags\nimport apache_beam as beam\nimport numpy as np\nfrom pde_superresolution import equations\nfrom pde_superresolution import integrate\nfrom pde_superresolution import utils\nimport tensorflow as tf\nimport xarray\n\n\n# NOTE(shoyer): allow_override=True lets us import multiple binaries for the\n# purpose of running integration tests. This is safe since we're strict about\n# only using FLAGS inside main().\n\n# files\nflags.DEFINE_string(\n 'output_path', None,\n 'Full path to which to save the resulting HDF5 file.')\n\n# equation parameters\nflags.DEFINE_enum(\n 'equation_name', 'burgers', list(equations.CONSERVATIVE_EQUATION_TYPES),\n 'Equation to integrate.', allow_override=True)\nflags.DEFINE_string(\n 'equation_kwargs', '{\"num_points\": 400}',\n 'Parameters to pass to the equation constructor.', allow_override=True)\nflags.DEFINE_integer(\n 'num_tasks', 10,\n 'Number of times to integrate each equation.')\nflags.DEFINE_integer(\n 'seed_offset', 1000000,\n 'Integer seed offset for random number generator. This should be larger '\n 'than the largest possible number of evaluation seeds, but smaller '\n 'than 2^32 (the size of NumPy\\'s random number seed).')\n\n# integrate parameters\nflags.DEFINE_float(\n 'time_max', 10,\n 'Total time for which to run each integration.',\n allow_override=True)\nflags.DEFINE_float(\n 'time_delta', 1,\n 'Difference between saved time steps in the integration.',\n allow_override=True)\nflags.DEFINE_float(\n 'warmup', 0,\n 'Amount of time to integrate before saving snapshots.',\n allow_override=True)\nflags.DEFINE_string(\n 'integrate_method', 'RK23',\n 'Method to use for integration with scipy.integrate.solve_ivp.',\n allow_override=True)\nflags.DEFINE_float(\n 'exact_filter_interval', 0,\n 'Interval between periodic filtering. Only used for spectral methods.',\n allow_override=True)\n\n\nFLAGS = flags.FLAGS\n\n\ndef main(_):\n runner = beam.runners.DirectRunner() # must create before flags are used\n\n equation_kwargs = json.loads(FLAGS.equation_kwargs)\n\n def create_equation(seed, name=FLAGS.equation_name, kwargs=equation_kwargs):\n equation_type = equations.EQUATION_TYPES[name]\n return equation_type(random_seed=seed, **kwargs)\n\n if (equations.EQUATION_TYPES[FLAGS.equation_name].BASELINE\n is equations.Baseline.SPECTRAL and FLAGS.exact_filter_interval):\n filter_interval = FLAGS.exact_filter_interval\n else:\n filter_interval = None\n\n integrate_exact = functools.partial(\n integrate.integrate_exact,\n times=np.arange(0, FLAGS.time_max, FLAGS.time_delta),\n warmup=FLAGS.warmup,\n integrate_method=FLAGS.integrate_method,\n filter_interval=filter_interval)\n\n expected_samples_per_task = int(round(FLAGS.time_max / FLAGS.time_delta))\n expected_total_samples = expected_samples_per_task * FLAGS.num_tasks\n\n def save(list_of_datasets, path=FLAGS.output_path, attrs=equation_kwargs):\n assert len(list_of_datasets) == len(seeds), len(list_of_datasets)\n combined = xarray.concat(list_of_datasets, dim='time')\n num_samples = combined.sizes['time']\n assert num_samples == expected_total_samples, num_samples\n tf.gfile.MakeDirs(os.path.dirname(path))\n with utils.write_h5py(path) as f:\n f.create_dataset('v', data=combined['y'].values)\n f.attrs.update(attrs)\n\n # introduce an offset so there's no overlap with the evaluation dataset\n seeds = [i + FLAGS.seed_offset for i in range(FLAGS.num_tasks)]\n\n pipeline = (\n beam.Create(seeds)\n | beam.Map(create_equation)\n | beam.Map(integrate_exact)\n | beam.combiners.ToList()\n | beam.Map(save)\n )\n runner.run(pipeline)\n\n\nif __name__ == '__main__':\n flags.mark_flag_as_required('output_path')\n app.run(main)\n",
"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Duck array functions that work on NumPy arrays and TensorFlow tensors.\n\nTODO(shoyer): remove this in favor of a comprehensive solution.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nfrom typing import List, Sequence, Optional, Tuple, TypeVar, Union\n\n\n# TODO(shoyer): replace with TypeVar('T', np.ndarray, tf.Tensor) when pytype\n# supports it (b/74212131)\nT = TypeVar('T')\n\n\ndef concatenate(arrays: List[T], axis: int) -> T:\n \"\"\"Concatenate arrays or tensors.\"\"\"\n if isinstance(arrays[0], tf.Tensor):\n return tf.concat(arrays, axis=axis)\n else:\n return np.concatenate(arrays, axis=axis)\n\n\ndef sin(x: T) -> T:\n if isinstance(x, tf.Tensor):\n return tf.sin(x)\n else:\n return np.sin(x)\n\n\ndef sum(x: T, axis: int = None) -> T: # pylint: disable=redefined-builtin\n if isinstance(x, tf.Tensor):\n return tf.reduce_sum(x, axis=axis)\n else:\n return np.sum(x, axis=axis)\n\n\ndef mean(x: T, axis: int = None) -> T:\n if isinstance(x, tf.Tensor):\n return tf.reduce_mean(x, axis=axis)\n else:\n return np.mean(x, axis=axis)\n\n\ndef get_shape(x: Union[tf.Tensor, np.ndarray]) -> Tuple[Optional[int]]:\n if isinstance(x, tf.Tensor):\n return tuple(x.shape.as_list()) # pytype: disable=attribute-error\n else:\n return x.shape\n\n\ndef reshape(x: T, shape: Sequence[int]) -> T:\n if isinstance(x, tf.Tensor):\n return tf.reshape(x, shape)\n else:\n return np.reshape(x, shape)\n\n\ndef maximum(x: T, y: T) -> T:\n return tf.maximum(x, y) if isinstance(x, tf.Tensor) else np.maximum(x, y)\n\n\ndef minimum(x: T, y: T) -> T:\n return tf.minimum(x, y) if isinstance(x, tf.Tensor) else np.minimum(x, y)\n\n\ndef where(cond: T, x: T, y: T) -> T:\n where_ = tf.where if isinstance(cond, tf.Tensor) else np.where\n return where_(cond, x, y)\n\n\ndef rfft(x: T) -> T:\n return tf.spectral.rfft(x) if isinstance(x, tf.Tensor) else np.fft.rfft(x)\n\n\ndef irfft(x: T) -> T:\n return tf.spectral.irfft(x) if isinstance(x, tf.Tensor) else np.fft.irfft(x)\n\n\ndef spectral_derivative(x: T, order: int = 1, period: float = 2*np.pi) -> T:\n \"\"\"Differentiate along the last axis of x using a Fourier transform.\"\"\"\n length = get_shape(x)[-1]\n if length % 2:\n raise ValueError('spectral derivative only works for even length data')\n c = 2*np.pi*1j / period\n k = np.fft.rfftfreq(length, d=1/length)\n return irfft((c * k) ** order * rfft(x))\n\n\ndef smoothing_filter(x: T,\n alpha: float = -np.log(1e-15),\n order: int = 2) -> T:\n \"\"\"Apply a low-pass smoothing filter to remove noise.\"\"\"\n # Based on:\n # Gottlieb and Hesthaven (2001), \"Spectral methods for hyperbolic problems\"\n # https://doi.org/10.1016/S0377-0427(00)00510-0\n length = get_shape(x)[-1]\n if length % 2:\n raise ValueError('smoothing filter only works for even length data')\n count = length // 2\n eta = np.arange(count+1) / count\n sigma = np.exp(-alpha * eta**(2*order))\n return irfft(sigma * rfft(x))\n\n\ndef _normalize_axis(axis: int, shape: Tuple[int]) -> int:\n ndim = len(shape)\n if not -ndim <= axis < ndim:\n raise ValueError('invalid axis {} for shape {}'.format(axis, shape))\n if axis < 0:\n axis += ndim\n return axis\n\n\ndef resample_mean(inputs: T, factor: int, axis: int = -1) -> T:\n \"\"\"Resample data to a lower-resolution with the mean.\n\n Args:\n inputs: array with dimensions [batch, x, ...].\n factor: integer factor by which to reduce the size of the x-dimension.\n axis: integer axis to resample over.\n\n Returns:\n Array with dimensions [batch, x//factor, ...].\n\n Raises:\n ValueError: if x is not evenly divided by factor.\n \"\"\"\n shape = get_shape(inputs)\n axis = _normalize_axis(axis, shape)\n if shape[axis] % factor:\n raise ValueError('resample factor {} must divide size {}'\n .format(factor, shape[axis]))\n\n new_shape = shape[:axis] + (shape[axis] // factor, factor) + shape[axis+1:]\n new_shape = [-1 if size is None else size for size in new_shape]\n\n reshaped = reshape(inputs, new_shape)\n return mean(reshaped, axis=axis+1)\n\n\ndef subsample(inputs: T, factor: int, axis: int = -1) -> T:\n \"\"\"Resample data to a lower-resolution by subsampling data-points.\n\n Args:\n inputs: array with dimensions [batch, x, ...].\n factor: integer factor by which to reduce the size of the x-dimension.\n axis: integer axis to resample over.\n\n Returns:\n Array with dimensions [batch, x//factor, ...].\n\n Raises:\n ValueError: if x is not evenly divided by factor.\n \"\"\"\n shape = get_shape(inputs)\n axis = _normalize_axis(axis, shape)\n if shape[axis] % factor:\n raise ValueError('resample factor {} must divide size {}'\n .format(factor, shape[axis]))\n\n indexer = [slice(None)] * len(shape)\n indexer[axis] = slice(None, None, factor)\n\n return inputs[tuple(indexer)]\n\n\nRESAMPLE_FUNCS = {\n 'mean': resample_mean,\n 'subsample': subsample,\n}\n"
] |
[
[
"numpy.arange"
],
[
"tensorflow.concat",
"numpy.minimum",
"tensorflow.reduce_sum",
"tensorflow.minimum",
"numpy.concatenate",
"numpy.mean",
"numpy.exp",
"tensorflow.spectral.irfft",
"numpy.fft.rfftfreq",
"numpy.reshape",
"numpy.arange",
"numpy.sin",
"numpy.log",
"numpy.fft.irfft",
"tensorflow.spectral.rfft",
"numpy.sum",
"tensorflow.sin",
"numpy.maximum",
"numpy.fft.rfft",
"tensorflow.reduce_mean",
"tensorflow.maximum",
"tensorflow.reshape"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.13",
"1.16",
"1.9",
"1.18",
"1.21",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"1.10",
"1.12",
"1.4",
"2.7",
"2.2",
"2.3",
"2.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.6",
"1.2",
"2.10"
]
}
] |
xinyufei/Quantum-Control-qutip
|
[
"bd8a119b9ff8ac0929ffb1f706328759d89fcb5e",
"bd8a119b9ff8ac0929ffb1f706328759d89fcb5e"
] |
[
"qutip/tests/test_states.py",
"qutip/floquet.py"
] |
[
"# This file is part of QuTiP: Quantum Toolbox in Python.\r\n#\r\n# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.\r\n# All rights reserved.\r\n#\r\n# Redistribution and use in source and binary forms, with or without\r\n# modification, are permitted provided that the following conditions are\r\n# met:\r\n#\r\n# 1. Redistributions of source code must retain the above copyright notice,\r\n# this list of conditions and the following disclaimer.\r\n#\r\n# 2. Redistributions in binary form must reproduce the above copyright\r\n# notice, this list of conditions and the following disclaimer in the\r\n# documentation and/or other materials provided with the distribution.\r\n#\r\n# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\r\n# of its contributors may be used to endorse or promote products derived\r\n# from this software without specific prior written permission.\r\n#\r\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\r\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n###############################################################################\r\n\r\nimport pytest\r\nimport numpy as np\r\nfrom numpy.testing import assert_, run_module_suite\r\nimport qutip\r\nfrom qutip import (expect, destroy, coherent, coherent_dm, thermal_dm,\r\n fock_dm, triplet_states)\r\n\r\n\r\[email protected](\"size, n\", [(2, 0), (2, 1), (100, 99)])\r\ndef test_basis_simple(size, n):\r\n qobj = qutip.basis(size, n)\r\n numpy = np.zeros((size, 1), dtype=complex)\r\n numpy[n, 0] = 1\r\n assert np.array_equal(qobj.full(), numpy)\r\n\r\n\r\[email protected](\"to_test\", [qutip.basis, qutip.fock, qutip.fock_dm])\r\[email protected](\"size, n\", [([2, 2], [0, 1]), ([2, 3, 4], [1, 2, 0])])\r\ndef test_implicit_tensor_basis_like(to_test, size, n):\r\n implicit = to_test(size, n)\r\n explicit = qutip.tensor(*[to_test(ss, nn) for ss, nn in zip(size, n)])\r\n assert implicit == explicit\r\n\r\n\r\[email protected](\"size, n, m\", [\r\n ([2, 2], [0, 0], [1, 1]),\r\n ([2, 3, 4], [1, 2, 0], [0, 1, 3]),\r\n ])\r\ndef test_implicit_tensor_projection(size, n, m):\r\n implicit = qutip.projection(size, n, m)\r\n explicit = qutip.tensor(*[qutip.projection(ss, nn, mm)\r\n for ss, nn, mm in zip(size, n, m)])\r\n assert implicit == explicit\r\n\r\n\r\nclass TestStates:\r\n \"\"\"\r\n A test class for the QuTiP functions for generating quantum states\r\n \"\"\"\r\n\r\n def testCoherentState(self):\r\n \"\"\"\r\n states: coherent state\r\n \"\"\"\r\n N = 10\r\n alpha = 0.5\r\n c1 = coherent(N, alpha) # displacement method\r\n c2 = coherent(7, alpha, offset=3) # analytic method\r\n assert_(abs(expect(destroy(N), c1) - alpha) < 1e-10)\r\n assert_((c1[3:]-c2).norm() < 1e-7)\r\n\r\n\r\n def testCoherentDensityMatrix(self):\r\n \"\"\"\r\n states: coherent density matrix\r\n \"\"\"\r\n N = 10\r\n\r\n rho = coherent_dm(N, 1)\r\n\r\n # make sure rho has trace close to 1.0\r\n assert_(abs(rho.tr() - 1.0) < 1e-12)\r\n\r\n def testThermalDensityMatrix(self):\r\n \"\"\"\r\n states: thermal density matrix\r\n \"\"\"\r\n N = 40\r\n\r\n rho = thermal_dm(N, 1)\r\n\r\n # make sure rho has trace close to 1.0\r\n assert_(abs(rho.tr() - 1.0) < 1e-12)\r\n\r\n def testFockDensityMatrix(self):\r\n \"\"\"\r\n states: Fock density matrix\r\n \"\"\"\r\n N = 10\r\n for i in range(N):\r\n rho = fock_dm(N, i)\r\n # make sure rho has trace close to 1.0\r\n assert_(abs(rho.tr() - 1.0) < 1e-12)\r\n assert_(rho.data[i, i] == 1.0)\r\n\r\n def testTripletStateNorm(self):\r\n \"\"\"\r\n Test the states returned by function triplet_states are normalized.\r\n \"\"\"\r\n for triplet in triplet_states():\r\n assert_(abs(triplet.norm() - 1.) < 1e-12)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n run_module_suite()\r\n",
"# This file is part of QuTiP: Quantum Toolbox in Python.\r\n#\r\n# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.\r\n# All rights reserved.\r\n#\r\n# Redistribution and use in source and binary forms, with or without\r\n# modification, are permitted provided that the following conditions are\r\n# met:\r\n#\r\n# 1. Redistributions of source code must retain the above copyright notice,\r\n# this list of conditions and the following disclaimer.\r\n#\r\n# 2. Redistributions in binary form must reproduce the above copyright\r\n# notice, this list of conditions and the following disclaimer in the\r\n# documentation and/or other materials provided with the distribution.\r\n#\r\n# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\r\n# of its contributors may be used to endorse or promote products derived\r\n# from this software without specific prior written permission.\r\n#\r\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\r\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n###############################################################################\r\n\r\n__all__ = ['floquet_modes', 'floquet_modes_t', 'floquet_modes_table',\r\n 'floquet_modes_t_lookup', 'floquet_states', 'floquet_states_t',\r\n 'floquet_wavefunction', 'floquet_wavefunction_t',\r\n 'floquet_state_decomposition', 'fsesolve',\r\n 'floquet_master_equation_rates', 'floquet_collapse_operators',\r\n 'floquet_master_equation_tensor',\r\n 'floquet_master_equation_steadystate', 'floquet_basis_transform',\r\n 'floquet_markov_mesolve', 'fmmesolve']\r\n\r\nimport numpy as np\r\nimport scipy.linalg as la\r\nimport scipy\r\nfrom numpy import angle, pi, exp, sqrt\r\nfrom types import FunctionType\r\nfrom qutip.qobj import Qobj, isket\r\nfrom qutip.superoperator import vec2mat_index, mat2vec, vec2mat\r\n#from qutip.mesolve import mesolve\r\nfrom qutip.sesolve import sesolve\r\nfrom qutip.rhs_generate import rhs_clear\r\nfrom qutip.steadystate import steadystate\r\nfrom qutip.states import ket2dm\r\nfrom qutip.states import projection\r\nfrom qutip.solver import Options\r\nfrom qutip.propagator import propagator\r\nfrom qutip.solver import Result, _solver_safety_check\r\nfrom qutip.cy.spmatfuncs import cy_ode_rhs\r\nfrom qutip.expect import expect\r\nfrom qutip.utilities import n_thermal\r\n\r\ndef floquet_modes(H, T, args=None, sort=False, U=None):\r\n \"\"\"\r\n Calculate the initial Floquet modes Phi_alpha(0) for a driven system with\r\n period T.\r\n\r\n Returns a list of :class:`qutip.qobj` instances representing the Floquet\r\n modes and a list of corresponding quasienergies, sorted by increasing\r\n quasienergy in the interval [-pi/T, pi/T]. The optional parameter `sort`\r\n decides if the output is to be sorted in increasing quasienergies or not.\r\n\r\n Parameters\r\n ----------\r\n\r\n H : :class:`qutip.qobj`\r\n system Hamiltonian, time-dependent with period `T`\r\n\r\n args : dictionary\r\n dictionary with variables required to evaluate H\r\n\r\n T : float\r\n The period of the time-dependence of the hamiltonian. The default value\r\n 'None' indicates that the 'tlist' spans a single period of the driving.\r\n\r\n U : :class:`qutip.qobj`\r\n The propagator for the time-dependent Hamiltonian with period `T`.\r\n If U is `None` (default), it will be calculated from the Hamiltonian\r\n `H` using :func:`qutip.propagator.propagator`.\r\n\r\n Returns\r\n -------\r\n\r\n output : list of kets, list of quasi energies\r\n\r\n Two lists: the Floquet modes as kets and the quasi energies.\r\n\r\n \"\"\"\r\n\r\n if U is None:\r\n # get the unitary propagator\r\n U = propagator(H, T, [], args)\r\n\r\n # find the eigenstates for the propagator\r\n evals, evecs = la.eig(U.full())\r\n\r\n eargs = angle(evals)\r\n\r\n # make sure that the phase is in the interval [-pi, pi], so that\r\n # the quasi energy is in the interval [-pi/T, pi/T] where T is the\r\n # period of the driving. eargs += (eargs <= -2*pi) * (2*pi) +\r\n # (eargs > 0) * (-2*pi)\r\n eargs += (eargs <= -pi) * (2 * pi) + (eargs > pi) * (-2 * pi)\r\n e_quasi = -eargs / T\r\n\r\n # sort by the quasi energy\r\n if sort:\r\n order = np.argsort(-e_quasi)\r\n else:\r\n order = list(range(len(evals)))\r\n\r\n # prepare a list of kets for the floquet states\r\n new_dims = [U.dims[0], [1] * len(U.dims[0])]\r\n new_shape = [U.shape[0], 1]\r\n kets_order = [Qobj(np.array(evecs[:, o]).T,\r\n dims=new_dims, shape=new_shape) for o in order]\r\n\r\n return kets_order, e_quasi[order]\r\n\r\ndef floquet_modes_t(f_modes_0, f_energies, t, H, T, args=None):\r\n \"\"\"\r\n Calculate the Floquet modes at times tlist Phi_alpha(tlist) propagting the\r\n initial Floquet modes Phi_alpha(0)\r\n\r\n Parameters\r\n ----------\r\n\r\n f_modes_0 : list of :class:`qutip.qobj` (kets)\r\n Floquet modes at :math:`t`\r\n\r\n f_energies : list\r\n Floquet energies.\r\n\r\n t : float\r\n The time at which to evaluate the floquet modes.\r\n\r\n H : :class:`qutip.qobj`\r\n system Hamiltonian, time-dependent with period `T`\r\n\r\n args : dictionary\r\n dictionary with variables required to evaluate H\r\n\r\n T : float\r\n The period of the time-dependence of the hamiltonian.\r\n\r\n Returns\r\n -------\r\n\r\n output : list of kets\r\n\r\n The Floquet modes as kets at time :math:`t`\r\n\r\n \"\"\"\r\n # find t in [0,T] such that t_orig = t + n * T for integer n\r\n t = t - int(t / T) * T\r\n f_modes_t = []\r\n\r\n # get the unitary propagator from 0 to t\r\n if t > 0.0:\r\n U = propagator(H, t, [], args)\r\n\r\n for n in np.arange(len(f_modes_0)):\r\n f_modes_t.append(U * f_modes_0[n] * exp(1j * f_energies[n] * t))\r\n else:\r\n f_modes_t = f_modes_0\r\n\r\n return f_modes_t\r\n\r\ndef floquet_modes_table(f_modes_0, f_energies, tlist, H, T, args=None):\r\n \"\"\"\r\n Pre-calculate the Floquet modes for a range of times spanning the floquet\r\n period. Can later be used as a table to look up the floquet modes for\r\n any time.\r\n\r\n Parameters\r\n ----------\r\n\r\n f_modes_0 : list of :class:`qutip.qobj` (kets)\r\n Floquet modes at :math:`t`\r\n\r\n f_energies : list\r\n Floquet energies.\r\n\r\n tlist : array\r\n The list of times at which to evaluate the floquet modes.\r\n\r\n H : :class:`qutip.qobj`\r\n system Hamiltonian, time-dependent with period `T`\r\n\r\n T : float\r\n The period of the time-dependence of the hamiltonian.\r\n\r\n args : dictionary\r\n dictionary with variables required to evaluate H\r\n\r\n Returns\r\n -------\r\n\r\n output : nested list\r\n\r\n A nested list of Floquet modes as kets for each time in `tlist`\r\n\r\n \"\"\"\r\n # truncate tlist to the driving period\r\n tlist_period = tlist[np.where(tlist <= T)]\r\n\r\n f_modes_table_t = [[] for t in tlist_period]\r\n\r\n opt = Options()\r\n opt.rhs_reuse = True\r\n rhs_clear()\r\n\r\n for n, f_mode in enumerate(f_modes_0):\r\n output = sesolve(H, f_mode, tlist_period, [], args, opt)\r\n for t_idx, f_state_t in enumerate(output.states):\r\n f_modes_table_t[t_idx].append(\r\n f_state_t * exp(1j * f_energies[n] * tlist_period[t_idx]))\r\n\r\n return f_modes_table_t\r\n\r\ndef floquet_modes_t_lookup(f_modes_table_t, t, T):\r\n \"\"\"\r\n Lookup the floquet mode at time t in the pre-calculated table of floquet\r\n modes in the first period of the time-dependence.\r\n\r\n Parameters\r\n ----------\r\n\r\n f_modes_table_t : nested list of :class:`qutip.qobj` (kets)\r\n A lookup-table of Floquet modes at times precalculated by\r\n :func:`qutip.floquet.floquet_modes_table`.\r\n\r\n t : float\r\n The time for which to evaluate the Floquet modes.\r\n\r\n T : float\r\n The period of the time-dependence of the hamiltonian.\r\n\r\n Returns\r\n -------\r\n\r\n output : nested list\r\n\r\n A list of Floquet modes as kets for the time that most closely matching\r\n the time `t` in the supplied table of Floquet modes.\r\n \"\"\"\r\n\r\n # find t_wrap in [0,T] such that t = t_wrap + n * T for integer n\r\n t_wrap = t - int(t / T) * T\r\n\r\n # find the index in the table that corresponds to t_wrap (= tlist[t_idx])\r\n t_idx = int(t_wrap / T * len(f_modes_table_t))\r\n\r\n # XXX: might want to give a warning if the cast of t_idx to int discard\r\n # a significant fraction in t_idx, which would happen if the list of time\r\n # values isn't perfect matching the driving period\r\n # if debug: print \"t = %f -> t_wrap = %f @ %d of %d\" % (t, t_wrap, t_idx,\r\n # N)\r\n\r\n return f_modes_table_t[t_idx]\r\n\r\ndef floquet_states(f_modes_t, f_energies, t):\r\n \"\"\"\r\n Evaluate the floquet states at time t given the Floquet modes at that time.\r\n\r\n Parameters\r\n ----------\r\n\r\n f_modes_t : list of :class:`qutip.qobj` (kets)\r\n A list of Floquet modes for time :math:`t`.\r\n\r\n f_energies : array\r\n The Floquet energies.\r\n\r\n t : float\r\n The time for which to evaluate the Floquet states.\r\n\r\n Returns\r\n -------\r\n\r\n output : list\r\n\r\n A list of Floquet states for the time :math:`t`.\r\n\r\n \"\"\"\r\n\r\n return [(f_modes_t[i] * exp(-1j * f_energies[i] * t))\r\n for i in np.arange(len(f_energies))]\r\n\r\ndef floquet_states_t(f_modes_0, f_energies, t, H, T, args=None):\r\n \"\"\"\r\n Evaluate the floquet states at time t given the initial Floquet modes.\r\n\r\n Parameters\r\n ----------\r\n\r\n f_modes_t : list of :class:`qutip.qobj` (kets)\r\n A list of initial Floquet modes (for time :math:`t=0`).\r\n\r\n f_energies : array\r\n The Floquet energies.\r\n\r\n t : float\r\n The time for which to evaluate the Floquet states.\r\n\r\n H : :class:`qutip.qobj`\r\n System Hamiltonian, time-dependent with period `T`.\r\n\r\n T : float\r\n The period of the time-dependence of the hamiltonian.\r\n\r\n args : dictionary\r\n Dictionary with variables required to evaluate H.\r\n\r\n Returns\r\n -------\r\n\r\n output : list\r\n\r\n A list of Floquet states for the time :math:`t`.\r\n\r\n \"\"\"\r\n\r\n f_modes_t = floquet_modes_t(f_modes_0, f_energies, t, H, T, args)\r\n return [(f_modes_t[i] * exp(-1j * f_energies[i] * t))\r\n for i in np.arange(len(f_energies))]\r\n\r\ndef floquet_wavefunction(f_modes_t, f_energies, f_coeff, t):\r\n \"\"\"\r\n Evaluate the wavefunction for a time t using the Floquet state\r\n decompositon, given the Floquet modes at time `t`.\r\n\r\n Parameters\r\n ----------\r\n\r\n f_modes_t : list of :class:`qutip.qobj` (kets)\r\n A list of initial Floquet modes (for time :math:`t=0`).\r\n\r\n f_energies : array\r\n The Floquet energies.\r\n\r\n f_coeff : array\r\n The coefficients for Floquet decomposition of the initial wavefunction.\r\n\r\n t : float\r\n The time for which to evaluate the Floquet states.\r\n\r\n Returns\r\n -------\r\n\r\n output : :class:`qutip.qobj`\r\n\r\n The wavefunction for the time :math:`t`.\r\n\r\n \"\"\"\r\n return sum([f_modes_t[i] * exp(-1j * f_energies[i] * t) * f_coeff[i]\r\n for i in np.arange(len(f_energies))])\r\n\r\ndef floquet_wavefunction_t(f_modes_0, f_energies, f_coeff, t, H, T, args=None):\r\n \"\"\"\r\n Evaluate the wavefunction for a time t using the Floquet state\r\n decompositon, given the initial Floquet modes.\r\n\r\n Parameters\r\n ----------\r\n\r\n f_modes_t : list of :class:`qutip.qobj` (kets)\r\n A list of initial Floquet modes (for time :math:`t=0`).\r\n\r\n f_energies : array\r\n The Floquet energies.\r\n\r\n f_coeff : array\r\n The coefficients for Floquet decomposition of the initial wavefunction.\r\n\r\n t : float\r\n The time for which to evaluate the Floquet states.\r\n\r\n H : :class:`qutip.qobj`\r\n System Hamiltonian, time-dependent with period `T`.\r\n\r\n T : float\r\n The period of the time-dependence of the hamiltonian.\r\n\r\n args : dictionary\r\n Dictionary with variables required to evaluate H.\r\n\r\n Returns\r\n -------\r\n\r\n output : :class:`qutip.qobj`\r\n\r\n The wavefunction for the time :math:`t`.\r\n\r\n \"\"\"\r\n\r\n f_states_t = floquet_states_t(f_modes_0, f_energies, t, H, T, args)\r\n return sum([f_states_t[i] * f_coeff[i]\r\n for i in np.arange(len(f_energies))])\r\n\r\ndef floquet_state_decomposition(f_states, f_energies, psi):\r\n r\"\"\"\r\n Decompose the wavefunction `psi` (typically an initial state) in terms of\r\n the Floquet states, :math:`\\psi = \\sum_\\alpha c_\\alpha \\psi_\\alpha(0)`.\r\n\r\n Parameters\r\n ----------\r\n\r\n f_states : list of :class:`qutip.qobj` (kets)\r\n A list of Floquet modes.\r\n\r\n f_energies : array\r\n The Floquet energies.\r\n\r\n psi : :class:`qutip.qobj`\r\n The wavefunction to decompose in the Floquet state basis.\r\n\r\n Returns\r\n -------\r\n\r\n output : array\r\n\r\n The coefficients :math:`c_\\alpha` in the Floquet state decomposition.\r\n\r\n \"\"\"\r\n # [:1,:1][0, 0] patch around scipy 1.3.0 bug\r\n return [(f_states[i].dag() * psi).data[:1, :1][0, 0]\r\n for i in np.arange(len(f_energies))]\r\n\r\ndef fsesolve(H, psi0, tlist, e_ops=[], T=None, args={}, Tsteps=100):\r\n \"\"\"\r\n Solve the Schrodinger equation using the Floquet formalism.\r\n\r\n Parameters\r\n ----------\r\n\r\n H : :class:`qutip.qobj.Qobj`\r\n System Hamiltonian, time-dependent with period `T`.\r\n\r\n psi0 : :class:`qutip.qobj`\r\n Initial state vector (ket).\r\n\r\n tlist : *list* / *array*\r\n list of times for :math:`t`.\r\n\r\n e_ops : list of :class:`qutip.qobj` / callback function\r\n list of operators for which to evaluate expectation values. If this\r\n list is empty, the state vectors for each time in `tlist` will be\r\n returned instead of expectation values.\r\n\r\n T : float\r\n The period of the time-dependence of the hamiltonian.\r\n\r\n args : dictionary\r\n Dictionary with variables required to evaluate H.\r\n\r\n Tsteps : integer\r\n The number of time steps in one driving period for which to\r\n precalculate the Floquet modes. `Tsteps` should be an even number.\r\n\r\n Returns\r\n -------\r\n\r\n output : :class:`qutip.solver.Result`\r\n\r\n An instance of the class :class:`qutip.solver.Result`, which\r\n contains either an *array* of expectation values or an array of\r\n state vectors, for the times specified by `tlist`.\r\n \"\"\"\r\n\r\n if not T:\r\n # assume that tlist span exactly one period of the driving\r\n T = tlist[-1]\r\n\r\n # find the floquet modes for the time-dependent hamiltonian\r\n f_modes_0, f_energies = floquet_modes(H, T, args)\r\n\r\n # calculate the wavefunctions using the from the floquet modes\r\n f_modes_table_t = floquet_modes_table(f_modes_0, f_energies,\r\n np.linspace(0, T, Tsteps + 1),\r\n H, T, args)\r\n\r\n # setup Result for storing the results\r\n output = Result()\r\n output.times = tlist\r\n output.solver = \"fsesolve\"\r\n\r\n if isinstance(e_ops, FunctionType):\r\n output.num_expect = 0\r\n expt_callback = True\r\n\r\n elif isinstance(e_ops, list):\r\n\r\n output.num_expect = len(e_ops)\r\n expt_callback = False\r\n\r\n if output.num_expect == 0:\r\n output.states = []\r\n else:\r\n output.expect = []\r\n for op in e_ops:\r\n if op.isherm:\r\n output.expect.append(np.zeros(len(tlist)))\r\n else:\r\n output.expect.append(np.zeros(len(tlist), dtype=complex))\r\n\r\n else:\r\n raise TypeError(\"e_ops must be a list Qobj or a callback function\")\r\n\r\n psi0_fb = psi0.transform(f_modes_0)\r\n for t_idx, t in enumerate(tlist):\r\n f_modes_t = floquet_modes_t_lookup(f_modes_table_t, t, T)\r\n f_states_t = floquet_states(f_modes_t, f_energies, t)\r\n psi_t = psi0_fb.transform(f_states_t, True)\r\n\r\n if expt_callback:\r\n # use callback method\r\n e_ops(t, psi_t)\r\n else:\r\n # calculate all the expectation values, or output psi if\r\n # no expectation value operators where defined\r\n if output.num_expect == 0:\r\n output.states.append(Qobj(psi_t))\r\n else:\r\n for e_idx, e in enumerate(e_ops):\r\n output.expect[e_idx][t_idx] = expect(e, psi_t)\r\n\r\n return output\r\n\r\ndef floquet_master_equation_rates(f_modes_0, f_energies, c_op, H, T,\r\n args, J_cb, w_th, kmax=5,\r\n f_modes_table_t=None):\r\n \"\"\"\r\n Calculate the rates and matrix elements for the Floquet-Markov master\r\n equation.\r\n\r\n Parameters\r\n ----------\r\n\r\n f_modes_0 : list of :class:`qutip.qobj` (kets)\r\n A list of initial Floquet modes.\r\n\r\n f_energies : array\r\n The Floquet energies.\r\n\r\n c_op : :class:`qutip.qobj`\r\n The collapse operators describing the dissipation.\r\n\r\n H : :class:`qutip.qobj`\r\n System Hamiltonian, time-dependent with period `T`.\r\n\r\n T : float\r\n The period of the time-dependence of the hamiltonian.\r\n\r\n args : dictionary\r\n Dictionary with variables required to evaluate H.\r\n\r\n J_cb : callback functions\r\n A callback function that computes the noise power spectrum, as\r\n a function of frequency, associated with the collapse operator `c_op`.\r\n\r\n w_th : float\r\n The temperature in units of frequency.\r\n\r\n k_max : int\r\n The truncation of the number of sidebands (default 5).\r\n\r\n f_modes_table_t : nested list of :class:`qutip.qobj` (kets)\r\n A lookup-table of Floquet modes at times precalculated by\r\n :func:`qutip.floquet.floquet_modes_table` (optional).\r\n\r\n Returns\r\n -------\r\n\r\n output : list\r\n\r\n A list (Delta, X, Gamma, A) containing the matrices Delta, X, Gamma\r\n and A used in the construction of the Floquet-Markov master equation.\r\n\r\n \"\"\"\r\n\r\n N = len(f_energies)\r\n M = 2 * kmax + 1\r\n\r\n omega = (2 * pi) / T\r\n\r\n Delta = np.zeros((N, N, M))\r\n X = np.zeros((N, N, M), dtype=complex)\r\n Gamma = np.zeros((N, N, M))\r\n A = np.zeros((N, N))\r\n\r\n nT = 100\r\n dT = T / nT\r\n tlist = np.arange(dT, T + dT / 2, dT)\r\n\r\n if f_modes_table_t is None:\r\n f_modes_table_t = floquet_modes_table(f_modes_0, f_energies,\r\n np.linspace(0, T, nT + 1), H, T,\r\n args)\r\n\r\n for t in tlist:\r\n # TODO: repeated invocations of floquet_modes_t is\r\n # inefficient... make a and b outer loops and use the mesolve\r\n # instead of the propagator.\r\n\r\n # f_modes_t = floquet_modes_t(f_modes_0, f_energies, t, H, T, args)\r\n f_modes_t = floquet_modes_t_lookup(f_modes_table_t, t, T)\r\n for a in range(N):\r\n for b in range(N):\r\n k_idx = 0\r\n for k in range(-kmax, kmax + 1, 1):\r\n # [:1,:1][0, 0] patch around scipy 1.3.0 bug\r\n X[a, b, k_idx] += (dT / T) * exp(-1j * k * omega * t) * \\\r\n (f_modes_t[a].dag() * c_op * f_modes_t[b])[:1, :1][0, 0]\r\n k_idx += 1\r\n\r\n Heaviside = lambda x: ((np.sign(x) + 1) / 2.0)\r\n for a in range(N):\r\n for b in range(N):\r\n k_idx = 0\r\n for k in range(-kmax, kmax + 1, 1):\r\n Delta[a, b, k_idx] = f_energies[a] - f_energies[b] + k * omega\r\n Gamma[a, b, k_idx] = 2 * pi * Heaviside(Delta[a, b, k_idx]) * \\\r\n J_cb(Delta[a, b, k_idx]) * abs(X[a, b, k_idx]) ** 2\r\n k_idx += 1\r\n\r\n for a in range(N):\r\n for b in range(N):\r\n for k in range(-kmax, kmax + 1, 1):\r\n k1_idx = k + kmax\r\n k2_idx = -k + kmax\r\n A[a, b] += Gamma[a, b, k1_idx] + \\\r\n n_thermal(abs(Delta[a, b, k1_idx]), w_th) * \\\r\n (Gamma[a, b, k1_idx] + Gamma[b, a, k2_idx])\r\n\r\n return Delta, X, Gamma, A\r\n\r\ndef floquet_collapse_operators(A):\r\n \"\"\"\r\n Construct collapse operators corresponding to the Floquet-Markov\r\n master-equation rate matrix `A`.\r\n\r\n .. note::\r\n\r\n Experimental.\r\n\r\n \"\"\"\r\n c_ops = []\r\n\r\n N, M = np.shape(A)\r\n\r\n #\r\n # Here we really need a master equation on Bloch-Redfield form, or perhaps\r\n # we can use the Lindblad form master equation with some rotating frame\r\n # approximations? ...\r\n #\r\n for a in range(N):\r\n for b in range(N):\r\n if a != b and abs(A[a, b]) > 0.0:\r\n # only relaxation terms included...\r\n c_ops.append(sqrt(A[a, b]) * projection(N, a, b))\r\n\r\n return c_ops\r\n\r\ndef floquet_master_equation_tensor(Alist, f_energies):\r\n \"\"\"\r\n Construct a tensor that represents the master equation in the floquet\r\n basis (with constant Hamiltonian and collapse operators).\r\n\r\n Simplest RWA approximation [Grifoni et al, Phys.Rep. 304 229 (1998)]\r\n\r\n Parameters\r\n ----------\r\n\r\n Alist : list\r\n A list of Floquet-Markov master equation rate matrices.\r\n\r\n f_energies : array\r\n The Floquet energies.\r\n\r\n Returns\r\n -------\r\n\r\n output : array\r\n\r\n The Floquet-Markov master equation tensor `R`.\r\n\r\n \"\"\"\r\n\r\n if isinstance(Alist, list):\r\n # Alist can be a list of rate matrices corresponding\r\n # to different operators that couple to the environment\r\n N, M = np.shape(Alist[0])\r\n else:\r\n # or a simple rate matrix, in which case we put it in a list\r\n Alist = [Alist]\r\n N, M = np.shape(Alist[0])\r\n\r\n Rdata_lil = scipy.sparse.lil_matrix((N * N, N * N), dtype=complex)\r\n for I in range(N * N):\r\n a, b = vec2mat_index(N, I)\r\n for J in range(N * N):\r\n c, d = vec2mat_index(N, J)\r\n\r\n R = -1.0j * (f_energies[a] - f_energies[b])*(a == c)*(b == d)\r\n Rdata_lil[I, J] = R\r\n\r\n for A in Alist:\r\n s1 = s2 = 0\r\n for n in range(N):\r\n s1 += A[a, n] * (n == c) * (n == d) - A[n, a] * \\\r\n (a == c) * (a == d)\r\n s2 += (A[n, a] + A[n, b]) * (a == c) * (b == d)\r\n\r\n dR = (a == b) * s1 - 0.5 * (1 - (a == b)) * s2\r\n\r\n if dR != 0.0:\r\n Rdata_lil[I, J] += dR\r\n\r\n return Qobj(Rdata_lil, [[N, N], [N, N]], [N*N, N*N])\r\n\r\ndef floquet_master_equation_steadystate(H, A):\r\n \"\"\"\r\n Returns the steadystate density matrix (in the floquet basis!) for the\r\n Floquet-Markov master equation.\r\n \"\"\"\r\n c_ops = floquet_collapse_operators(A)\r\n rho_ss = steadystate(H, c_ops)\r\n return rho_ss\r\n\r\ndef floquet_basis_transform(f_modes, f_energies, rho0):\r\n \"\"\"\r\n Make a basis transform that takes rho0 from the floquet basis to the\r\n computational basis.\r\n \"\"\"\r\n return rho0.transform(f_modes, True)\r\n\r\n# -----------------------------------------------------------------------------\r\n# Floquet-Markov master equation\r\n#\r\n#\r\ndef floquet_markov_mesolve(R, ekets, rho0, tlist, e_ops, f_modes_table=None,\r\n options=None, floquet_basis=True):\r\n \"\"\"\r\n Solve the dynamics for the system using the Floquet-Markov master equation.\r\n \"\"\"\r\n\r\n if options is None:\r\n opt = Options()\r\n else:\r\n opt = options\r\n\r\n if opt.tidy:\r\n R.tidyup()\r\n\r\n #\r\n # check initial state\r\n #\r\n if isket(rho0):\r\n # Got a wave function as initial state: convert to density matrix.\r\n rho0 = ket2dm(rho0)\r\n\r\n #\r\n # prepare output array\r\n #\r\n n_tsteps = len(tlist)\r\n dt = tlist[1] - tlist[0]\r\n\r\n output = Result()\r\n output.solver = \"fmmesolve\"\r\n output.times = tlist\r\n\r\n if isinstance(e_ops, FunctionType):\r\n n_expt_op = 0\r\n expt_callback = True\r\n\r\n elif isinstance(e_ops, list):\r\n\r\n n_expt_op = len(e_ops)\r\n expt_callback = False\r\n\r\n if n_expt_op == 0:\r\n output.states = []\r\n else:\r\n if not f_modes_table:\r\n raise TypeError(\"The Floquet mode table has to be provided \" +\r\n \"when requesting expectation values.\")\r\n\r\n output.expect = []\r\n output.num_expect = n_expt_op\r\n for op in e_ops:\r\n if op.isherm:\r\n output.expect.append(np.zeros(n_tsteps))\r\n else:\r\n output.expect.append(np.zeros(n_tsteps, dtype=complex))\r\n\r\n else:\r\n raise TypeError(\"Expectation parameter must be a list or a function\")\r\n\r\n #\r\n # transform the initial density matrix to the eigenbasis: from\r\n # computational basis to the floquet basis\r\n #\r\n if ekets is not None:\r\n rho0 = rho0.transform(ekets)\r\n\r\n #\r\n # setup integrator\r\n #\r\n initial_vector = mat2vec(rho0.full())\r\n r = scipy.integrate.ode(cy_ode_rhs)\r\n r.set_f_params(R.data.data, R.data.indices, R.data.indptr)\r\n r.set_integrator('zvode', method=opt.method, order=opt.order,\r\n atol=opt.atol, rtol=opt.rtol, max_step=opt.max_step)\r\n r.set_initial_value(initial_vector, tlist[0])\r\n\r\n #\r\n # start evolution\r\n #\r\n rho = Qobj(rho0)\r\n\r\n t_idx = 0\r\n for t in tlist:\r\n if not r.successful():\r\n break\r\n\r\n rho = Qobj(vec2mat(r.y), rho0.dims, rho0.shape)\r\n\r\n if expt_callback:\r\n # use callback method\r\n if floquet_basis:\r\n e_ops(t, Qobj(rho))\r\n else:\r\n f_modes_table_t, T = f_modes_table\r\n f_modes_t = floquet_modes_t_lookup(f_modes_table_t, t, T)\r\n e_ops(t, Qobj(rho).transform(f_modes_t, True))\r\n else:\r\n # calculate all the expectation values, or output rho if\r\n # no operators\r\n if n_expt_op == 0:\r\n if floquet_basis:\r\n output.states.append(Qobj(rho))\r\n else:\r\n f_modes_table_t, T = f_modes_table\r\n f_modes_t = floquet_modes_t_lookup(f_modes_table_t, t, T)\r\n output.states.append(Qobj(rho).transform(f_modes_t, True))\r\n else:\r\n f_modes_table_t, T = f_modes_table\r\n f_modes_t = floquet_modes_t_lookup(f_modes_table_t, t, T)\r\n for m in range(0, n_expt_op):\r\n output.expect[m][t_idx] = \\\r\n expect(e_ops[m], rho.transform(f_modes_t, False))\r\n\r\n r.integrate(r.t + dt)\r\n t_idx += 1\r\n\r\n return output\r\n\r\n# -----------------------------------------------------------------------------\r\n# Solve the Floquet-Markov master equation\r\n#\r\n#\r\ndef fmmesolve(H, rho0, tlist, c_ops=[], e_ops=[], spectra_cb=[], T=None,\r\n args={}, options=Options(), floquet_basis=True, kmax=5,\r\n _safe_mode=True):\r\n \"\"\"\r\n Solve the dynamics for the system using the Floquet-Markov master equation.\r\n\r\n .. note::\r\n\r\n This solver currently does not support multiple collapse operators.\r\n\r\n Parameters\r\n ----------\r\n\r\n H : :class:`qutip.qobj`\r\n system Hamiltonian.\r\n\r\n rho0 / psi0 : :class:`qutip.qobj`\r\n initial density matrix or state vector (ket).\r\n\r\n tlist : *list* / *array*\r\n list of times for :math:`t`.\r\n\r\n c_ops : list of :class:`qutip.qobj`\r\n list of collapse operators.\r\n\r\n e_ops : list of :class:`qutip.qobj` / callback function\r\n list of operators for which to evaluate expectation values.\r\n\r\n spectra_cb : list callback functions\r\n List of callback functions that compute the noise power spectrum as\r\n a function of frequency for the collapse operators in `c_ops`.\r\n\r\n T : float\r\n The period of the time-dependence of the hamiltonian. The default value\r\n 'None' indicates that the 'tlist' spans a single period of the driving.\r\n\r\n args : *dictionary*\r\n dictionary of parameters for time-dependent Hamiltonians and\r\n collapse operators.\r\n\r\n This dictionary should also contain an entry 'w_th', which is\r\n the temperature of the environment (if finite) in the\r\n energy/frequency units of the Hamiltonian. For example, if\r\n the Hamiltonian written in units of 2pi GHz, and the\r\n temperature is given in K, use the following conversion\r\n\r\n >>> temperature = 25e-3 # unit K # doctest: +SKIP\r\n >>> h = 6.626e-34 # doctest: +SKIP\r\n >>> kB = 1.38e-23 # doctest: +SKIP\r\n >>> args['w_th'] = temperature * (kB / h) * 2 * pi * 1e-9 \\\r\n #doctest: +SKIP\r\n\r\n options : :class:`qutip.solver`\r\n options for the ODE solver.\r\n\r\n k_max : int\r\n The truncation of the number of sidebands (default 5).\r\n\r\n Returns\r\n -------\r\n\r\n output : :class:`qutip.solver`\r\n\r\n An instance of the class :class:`qutip.solver`, which contains either\r\n an *array* of expectation values for the times specified by `tlist`.\r\n \"\"\"\r\n\r\n if _safe_mode:\r\n _solver_safety_check(H, rho0, c_ops, e_ops, args)\r\n\r\n if T is None:\r\n T = max(tlist)\r\n\r\n if len(spectra_cb) == 0:\r\n # add white noise callbacks if absent\r\n spectra_cb = [lambda w: 1.0] * len(c_ops)\r\n\r\n f_modes_0, f_energies = floquet_modes(H, T, args)\r\n\r\n f_modes_table_t = floquet_modes_table(f_modes_0, f_energies,\r\n np.linspace(0, T, 500 + 1),\r\n H, T, args)\r\n\r\n # get w_th from args if it exists\r\n if 'w_th' in args:\r\n w_th = args['w_th']\r\n else:\r\n w_th = 0\r\n\r\n # TODO: loop over input c_ops and spectra_cb, calculate one R for each set\r\n\r\n # calculate the rate-matrices for the floquet-markov master equation\r\n Delta, X, Gamma, Amat = floquet_master_equation_rates(\r\n f_modes_0, f_energies, c_ops[0], H, T, args, spectra_cb[0],\r\n w_th, kmax, f_modes_table_t)\r\n\r\n # the floquet-markov master equation tensor\r\n R = floquet_master_equation_tensor(Amat, f_energies)\r\n\r\n return floquet_markov_mesolve(R, f_modes_0, rho0, tlist, e_ops,\r\n f_modes_table=(f_modes_table_t, T),\r\n options=options,\r\n floquet_basis=floquet_basis)\r\n"
] |
[
[
"numpy.testing.run_module_suite",
"numpy.zeros",
"numpy.testing.assert_"
],
[
"numpy.array",
"numpy.sqrt",
"numpy.linspace",
"numpy.arange",
"numpy.sign",
"numpy.shape",
"numpy.argsort",
"numpy.angle",
"numpy.exp",
"numpy.zeros",
"numpy.where",
"scipy.integrate.ode",
"scipy.sparse.lil_matrix"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
evidation-health/bokeh
|
[
"2c580d93419033b962d36e3c46d7606cc2f24606"
] |
[
"bokeh/_legacy_charts/builder/tests/test_step_builder.py"
] |
[
"\"\"\" This is the Bokeh charts testing interface.\n\n\"\"\"\n#-----------------------------------------------------------------------------\n# Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved.\n#\n# Powered by the Bokeh Development Team.\n#\n# The full license is in the file LICENSE.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\nfrom __future__ import absolute_import\n\nfrom collections import OrderedDict\nimport unittest\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nimport pandas as pd\n\nfrom bokeh._legacy_charts import Step\n\nfrom ._utils import create_chart\n\n#-----------------------------------------------------------------------------\n# Classes and functions\n#-----------------------------------------------------------------------------\n\nclass TestStep(unittest.TestCase):\n def test_supported_input(self):\n xyvalues = OrderedDict()\n xyvalues['python'] = [2, 3, 7, 5, 26]\n xyvalues['pypy'] = [12, 33, 47, 15, 126]\n xyvalues['jython'] = [22, 43, 10, 25, 26]\n xyvaluesdf = pd.DataFrame(xyvalues)\n\n y_python = [ 2., 2., 3., 3., 7., 7., 5., 5., 26.]\n y_jython = [ 22., 22.,43., 43., 10., 10., 25., 25., 26.]\n y_pypy = [ 12., 12., 33., 33., 47., 47., 15., 15., 126.]\n x = [0, 1, 1, 2, 2, 3, 3, 4, 4]\n\n for i, _xy in enumerate([xyvalues, xyvaluesdf]):\n hm = create_chart(Step, _xy)\n builder = hm._builders[0]\n self.assertEqual(sorted(builder._groups), sorted(list(xyvalues.keys())))\n assert_array_equal(builder._data['x'], x)\n\n assert_array_equal(builder._data['y_python'], y_python)\n assert_array_equal(builder._data['y_jython'], y_jython)\n assert_array_equal(builder._data['y_pypy'], y_pypy)\n\n lvalues = [[2, 3, 7, 5, 26], [12, 33, 47, 15, 126], [22, 43, 10, 25, 26]]\n for _xy in [lvalues, np.array(lvalues)]:\n hm = create_chart(Step, _xy)\n builder = hm._builders[0]\n self.assertEqual(builder._groups, ['0', '1', '2'])\n assert_array_equal(builder._data['y_0'], y_python)\n assert_array_equal(builder._data['y_1'], y_pypy)\n assert_array_equal(builder._data['y_2'], y_jython)\n"
] |
[
[
"numpy.testing.assert_array_equal",
"numpy.array",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
hanlinxuy/HASCO
|
[
"f7c3ac51817b2550f1dcfe7c9a79f81fd15f232c"
] |
[
"src/codesign/ax_extend.py"
] |
[
"import inspect\r\nfrom typing import Any, Callable, Dict, List, Optional\r\n\r\nimport numpy as np\r\nfrom ax.core.arm import Arm\r\nfrom ax.core.base_trial import BaseTrial, TrialStatus\r\nfrom ax.core.batch_trial import BatchTrial\r\nfrom ax.core.data import Data\r\nfrom ax.core.experiment import Experiment\r\nfrom ax.core.metric import Metric\r\nfrom ax.core.objective import Objective\r\nfrom ax.core.optimization_config import OptimizationConfig\r\nfrom ax.core.outcome_constraint import OutcomeConstraint\r\nfrom ax.core.search_space import SearchSpace\r\nfrom ax.core.trial import Trial\r\nfrom ax.core.types import TEvaluationOutcome, TParameterization, TTrialEvaluation\r\nfrom ax.utils.common.docutils import copy_doc\r\nfrom ax.utils.common.typeutils import not_none, numpy_type_to_python_type, checked_cast\r\n\r\n\r\nfrom ax.utils.notebook.plotting import render\r\nfrom ax.plot.trace import optimization_trace_single_method\r\nfrom ax.plot.helper import _format_dict\r\n\r\ndef eval_trial(exp, trial, func, kwargs):\r\n \"\"\"\r\n Evaluate trial arms with the evaluation function of this\r\n experiment.\r\n\r\n kwargs:\r\n trial: trial, whose arms to evaluate.\r\n \"\"\"\r\n cached_data = exp.lookup_data_for_trial(trial.index)[0]\r\n if not cached_data.df.empty:\r\n return cached_data\r\n\r\n evaluations = {}\r\n trial.runner = exp.runner\r\n if isinstance(trial, Trial):\r\n if not trial.arm:\r\n return Data() # pragma: no cover\r\n trial.mark_running()\r\n evaluations[not_none(trial.arm).name] = evaluation_function_outer(exp, func,\r\n not_none(trial.arm).parameters, kwargs, None\r\n )\r\n elif isinstance(trial, BatchTrial):\r\n if not trial.arms:\r\n return Data() # pragma: no cover\r\n trial.mark_running()\r\n for arm, weight in trial.normalized_arm_weights().items():\r\n arm_parameters: TParameterization = arm.parameters\r\n try:\r\n evaluations[arm.name] = evaluation_function_outer(exp, func, \r\n arm_parameters, kwargs, weight)\r\n except Exception as e:\r\n print(e)\r\n continue\r\n \r\n trial.mark_completed()\r\n try:\r\n data = Data.from_evaluations(evaluations, trial.index)\r\n exp.attach_data(data)\r\n return data\r\n except ValueError as e:\r\n print(e)\r\n return Data()\r\n\r\n\r\n\r\ndef evaluation_function_outer(\r\n exp, func, parameterization: TParameterization, kwargs, weight: Optional[float] = None\r\n ) -> TTrialEvaluation:\r\n signature = inspect.signature(func)\r\n num_evaluation_function_params = len(signature.parameters.items()) - len(kwargs)\r\n if num_evaluation_function_params == 1:\r\n # pyre-fixme[20]: Anonymous call expects argument `$1`. \r\n evaluation = func(parameterization, kwargs['benchmark'], kwargs['generator'], kwargs['method']) \r\n elif num_evaluation_function_params == 2:\r\n evaluation = func(parameterization, weight, kwargs['benchmark'], kwargs['generator'], kwargs['method'])\r\n else:\r\n raise ValueError( # pragma: no cover\r\n \"Evaluation function must take either one parameter \"\r\n \"(parameterization) or two parameters (parameterization and weight).\"\r\n ) \r\n \r\n if isinstance(evaluation, dict):\r\n return evaluation\r\n elif isinstance(evaluation, tuple):\r\n return {exp.optimization_config.objective.metric.name: evaluation}\r\n elif isinstance(evaluation, (float, int)):\r\n return {exp.optimization_config.objective.metric.name: (evaluation, 0.0)}\r\n elif isinstance(evaluation, (np.float32, np.float64, np.int32, np.int64)):\r\n return {\r\n exp.optimization_config.objective.metric.name: (\r\n numpy_type_to_python_type(evaluation),\r\n 0.0,\r\n )\r\n }\r\n raise Exception( # pragma: no cover\r\n \"Evaluation function returned an invalid type. The function must \"\r\n \"either return a dictionary of metric names to mean, sem tuples \"\r\n \"or a single mean, sem tuple, or a single mean.\"\r\n )\r\n\r\n\r\n\r\ndef run_trial(exp, trial, func, **kwargs) -> Data:\r\n assert trial.status != TrialStatus.COMPLETED, \"already evaluated\"\r\n return eval_trial(exp, trial, func, kwargs)\r\n\r\n\r\n\r\ndef eval_exp(exp, func, **kwargs) -> Data:\r\n # return new data\r\n return Data.from_multiple_data(\r\n [\r\n eval_trial(exp, trial, func, kwargs)\r\n for trial in exp.trials.values()\r\n if trial.status != TrialStatus.COMPLETED \r\n ]\r\n )\r\n\r\n\r\ndef get_size(data):\r\n if data != None:\r\n return len(data._df.index) # #key * #trial\r\n else:\r\n return 0\r\n\r\n\r\n\r\n\r\ndef get_non_dominated(exp) :\r\n \r\n df = exp.fetch_data().df\r\n arms = exp.arms_by_name\r\n \r\n pareto_set = []\r\n for key in exp.metrics:\r\n tmp_df = df.loc[df['metric_name']==key].sort_values('mean')\r\n # print(tmp_df)\r\n try:\r\n arm_name = tmp_df.values[0][0]\r\n arm = arms.get(arm_name)\r\n arg_str = [str(i) for i in arm.parameters.values()] \r\n tag = '_'.join(arg_str)\r\n val = (tag, tmp_df.values[0][2])\r\n pareto_set.append({key: val})\r\n except Exception as e:\r\n print(e)\r\n break\r\n return pareto_set\r\n\r\n\r\ndef draw_optimization_trace(exp):\r\n # not tested yet\r\n \"\"\"Retrieves the plot configuration for optimization trace, which shows\r\n the evolution of the objective mean over iterations.\r\n\r\n Args:\r\n objective_optimum: Optimal objective, if known, for display in the\r\n visualization.\r\n \"\"\"\r\n if not exp.trials:\r\n raise ValueError(\"Cannot generate plot as there are no trials.\")\r\n \r\n\r\n for metric in exp.optimization_config.objective.metrics:\r\n objective_name = metric.name\r\n best_objectives = np.array(\r\n [\r\n [\r\n checked_cast(Trial, trial).get_metric_mean(objective_name)\r\n for trial in list(exp.trials.values())[1:]\r\n if trial.status.is_completed\r\n ]\r\n ]\r\n )\r\n hover_labels = [\r\n _format_dict(not_none(checked_cast(Trial, trial).arm).parameters)\r\n for trial in list(exp.trials.values())[1:]\r\n if trial.status.is_completed\r\n ]\r\n \r\n config = optimization_trace_single_method(\r\n y=(\r\n np.minimum.accumulate(best_objectives, axis=1)\r\n if exp.optimization_config.objective.minimize\r\n else np.maximum.accumulate(best_objectives, axis=1)\r\n ),\r\n # optimum=objective_optimum,\r\n title=\"Model performance vs. # of iterations\",\r\n ylabel=objective_name.capitalize(),\r\n hover_labels=hover_labels,\r\n )\r\n\r\n render(config)"
] |
[
[
"numpy.minimum.accumulate",
"numpy.maximum.accumulate"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
eozd/probability
|
[
"2b866780982182fe0bf4e5336ee09fdb74cc2b03"
] |
[
"tensorflow_probability/python/distributions/autoregressive.py"
] |
[
"# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"The Autoregressive distribution.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nfrom tensorflow_probability.python.distributions import distribution\nfrom tensorflow_probability.python.distributions import seed_stream\n\n\nclass Autoregressive(distribution.Distribution):\n \"\"\"Autoregressive distributions.\n\n The Autoregressive distribution enables learning (often) richer multivariate\n distributions by repeatedly applying a [diffeomorphic](\n https://en.wikipedia.org/wiki/Diffeomorphism) transformation (such as\n implemented by `Bijector`s). Regarding terminology,\n\n \"Autoregressive models decompose the joint density as a product of\n conditionals, and model each conditional in turn. Normalizing flows\n transform a base density (e.g. a standard Gaussian) into the target density\n by an invertible transformation with tractable Jacobian.\" [(Papamakarios et\n al., 2016)][1]\n\n In other words, the \"autoregressive property\" is equivalent to the\n decomposition, `p(x) = prod{ p(x[i] | x[0:i]) : i=0, ..., d }`. The provided\n `shift_and_log_scale_fn`, `masked_autoregressive_default_template`, achieves\n this property by zeroing out weights in its `masked_dense` layers.\n\n Practically speaking the autoregressive property means that there exists a\n permutation of the event coordinates such that each coordinate is a\n diffeomorphic function of only preceding coordinates\n [(van den Oord et al., 2016)][2].\n\n #### Mathematical Details\n\n The probability function is\n\n ```none\n prob(x; fn, n) = fn(x).prob(x)\n ```\n\n And a sample is generated by\n\n ```none\n x = fn(...fn(fn(x0).sample()).sample()).sample()\n ```\n\n where the ellipses (`...`) represent `n-2` composed calls to `fn`, `fn`\n constructs a `tfd.Distribution`-like instance, and `x0` is a\n fixed initializing `Tensor`.\n\n #### Examples\n\n ```python\n tfd = tfp.distributions\n tfb = tfp.bijectors\n\n def _normal_fn(event_size):\n n = event_size * (event_size + 1) // 2\n p = tf.Variable(tfd.Normal(loc=0., scale=1.).sample(n))\n affine = tfb.Affine(\n scale_tril=tfd.fill_triangular(0.25 * p))\n def _fn(samples):\n scale = tf.exp(affine.forward(samples))\n return tfd.Independent(\n tfd.Normal(loc=0., scale=scale, validate_args=True),\n reinterpreted_batch_ndims=1)\n return _fn\n\n batch_and_event_shape = [3, 2, 4]\n sample0 = tf.zeros(batch_and_event_shape)\n ar = tfd.Autoregressive(\n _normal_fn(batch_and_event_shape[-1]), sample0)\n x = ar.sample([6, 5])\n # ==> x.shape = [6, 5, 3, 2, 4]\n prob_x = ar.prob(x)\n # ==> x.shape = [6, 5, 3, 2]\n\n ```\n\n #### References\n\n [1]: George Papamakarios, Theo Pavlakou, and Iain Murray. Masked\n Autoregressive Flow for Density Estimation. In _Neural Information\n Processing Systems_, 2017. https://arxiv.org/abs/1705.07057\n\n [2]: Aaron van den Oord, Nal Kalchbrenner, Oriol Vinyals, Lasse Espeholt,\n Alex Graves, and Koray Kavukcuoglu. Conditional Image Generation with\n PixelCNN Decoders. In _Neural Information Processing Systems_, 2016.\n https://arxiv.org/abs/1606.05328\n \"\"\"\n\n def __init__(self,\n distribution_fn,\n sample0=None,\n num_steps=None,\n validate_args=False,\n allow_nan_stats=True,\n name=\"Autoregressive\"):\n \"\"\"Construct an `Autoregressive` distribution.\n\n Args:\n distribution_fn: Python `callable` which constructs a\n `tfd.Distribution`-like instance from a `Tensor` (e.g.,\n `sample0`). The function must respect the \"autoregressive property\",\n i.e., there exists a permutation of event such that each coordinate is a\n diffeomorphic function of on preceding coordinates.\n sample0: Initial input to `distribution_fn`; used to\n build the distribution in `__init__` which in turn specifies this\n distribution's properties, e.g., `event_shape`, `batch_shape`, `dtype`.\n If unspecified, then `distribution_fn` should be default constructable.\n num_steps: Number of times `distribution_fn` is composed from samples,\n e.g., `num_steps=2` implies\n `distribution_fn(distribution_fn(sample0).sample(n)).sample()`.\n validate_args: Python `bool`. Whether to validate input with asserts.\n If `validate_args` is `False`, and the inputs are invalid,\n correct behavior is not guaranteed.\n allow_nan_stats: Python `bool`, default `True`. When `True`, statistics\n (e.g., mean, mode, variance) use the value \"`NaN`\" to indicate the\n result is undefined. When `False`, an exception is raised if one or\n more of the statistic's batch members are undefined.\n name: Python `str` name prefixed to Ops created by this class.\n Default value: \"Autoregressive\".\n\n Raises:\n ValueError: if `num_steps` and\n `distribution_fn(sample0).event_shape.num_elements()` are both `None`.\n ValueError: if `num_steps < 1`.\n \"\"\"\n parameters = dict(locals())\n with tf.compat.v1.name_scope(name) as name:\n self._distribution_fn = distribution_fn\n self._sample0 = sample0\n self._distribution0 = (distribution_fn() if sample0 is None\n else distribution_fn(sample0))\n if num_steps is None:\n num_steps = self._distribution0.event_shape.num_elements()\n if num_steps is None:\n raise ValueError(\"distribution_fn must generate a distribution \"\n \"with fully known `event_shape`.\")\n if num_steps < 1:\n raise ValueError(\"num_steps ({}) must be at least 1.\".format(num_steps))\n self._num_steps = num_steps\n super(Autoregressive, self).__init__(\n dtype=self._distribution0.dtype,\n reparameterization_type=self._distribution0.reparameterization_type,\n validate_args=validate_args,\n allow_nan_stats=allow_nan_stats,\n parameters=parameters,\n graph_parents=self._distribution0._graph_parents, # pylint: disable=protected-access\n name=name)\n\n @property\n def distribution_fn(self):\n return self._distribution_fn\n\n @property\n def sample0(self):\n return self._sample0\n\n @property\n def num_steps(self):\n return self._num_steps\n\n @property\n def distribution0(self):\n return self._distribution0\n\n def _batch_shape(self):\n return self.distribution0.batch_shape\n\n def _batch_shape_tensor(self):\n return self.distribution0.batch_shape_tensor()\n\n def _event_shape(self):\n return self.distribution0.event_shape\n\n def _event_shape_tensor(self):\n return self.distribution0.event_shape_tensor()\n\n def _sample_n(self, n, seed=None):\n seed = seed_stream.SeedStream(seed, salt=\"Autoregressive\")()\n samples = self.distribution0.sample(n, seed=seed)\n for _ in range(self._num_steps):\n # pylint: disable=not-callable\n samples = self.distribution_fn(samples).sample(seed=seed)\n return samples\n\n def _log_prob(self, value):\n # pylint: disable=not-callable\n return self.distribution_fn(value).log_prob(value)\n\n def _prob(self, value):\n # pylint: disable=not-callable\n return self.distribution_fn(value).prob(value)\n"
] |
[
[
"tensorflow.compat.v1.name_scope"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
meyer-lab/bi-cytok
|
[
"34bac90b88d53c02e742dec3a5f663734e860f1b"
] |
[
"genFigures.py"
] |
[
"#!/usr/bin/env python3\n\nimport sys\nimport logging\nimport time\nimport matplotlib\nmatplotlib.use('AGG')\n\nfdir = './output/'\n\nlogging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)\n\nif __name__ == '__main__':\n start = time.time()\n nameOut = 'figure' + sys.argv[1]\n\n exec('from ckine.figures import ' + nameOut)\n ff = eval(nameOut + '.makeFigure()')\n ff.savefig(fdir + nameOut + '.svg', dpi=ff.dpi, bbox_inches='tight', pad_inches=0)\n\n logging.info('%s is done after %s seconds.', nameOut, time.time() - start)\n"
] |
[
[
"matplotlib.use"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kprokofi/ML_Decoder
|
[
"c01c50e0165e607afbebd8d615708ef9c084dd5b"
] |
[
"src_files/models/timm_wrapper.py"
] |
[
"import torch\nimport torch.nn as nn\nfrom torch.nn import Module as Module\nimport timm\nfrom torch.nn import Parameter\nimport torch.nn.functional as F\n\nclass AngleSimpleLinear(nn.Module):\n \"\"\"Computes cos of angles between input vectors and weights vectors\"\"\"\n\n def __init__(self, in_features, out_features):\n super().__init__()\n self.in_features = in_features\n self.out_features = out_features\n # create proxy weights\n self.weight = Parameter(torch.Tensor(in_features, out_features))\n self.weight.data.normal_().renorm_(2, 1, 1e-5).mul_(1e5)\n\n def forward(self, x):\n # cos_theta = F.cosine_similarity(x, self.weight.reshape(1, 20, -1), dim=2)\n cos_theta = F.normalize(x.view(x.shape[0], -1), dim=1).mm(F.normalize(self.weight, p=2, dim=0))\n return cos_theta.clamp(-1, 1)\n\n def get_centers(self):\n return torch.t(self.weight)\n\nclass TimmModelsWrapper(Module):\n def __init__(self,\n model_name,\n num_classes,\n pretrained=False,\n ml_decoder_used=False,\n asl_use = False):\n\n super().__init__()\n self.pretrained = pretrained\n self.is_mobilenet = True if model_name in [\"mobilenetv3_large_100_miil_in21k\", \"mobilenetv3_large_100_miil\"] else False\n self.num_classes = num_classes\n\n self.model = timm.create_model(model_name,\n pretrained=pretrained,\n num_classes=self.num_classes)\n self.num_head_features = self.model.num_features\n self.num_features = (self.model.conv_head.in_channels if self.is_mobilenet\n else self.model.num_features)\n if ml_decoder_used:\n self.model.global_pool = torch.nn.Identity()\n self.model.classifier = torch.nn.Identity()\n else:\n if asl_use:\n self.model.act2 = nn.PReLU()\n self.model.classifier = AngleSimpleLinear(self.num_head_features, self.num_classes)\n else:\n self.model.classifier = self.model.get_classifier()\n\n def forward(self, x):\n return self.model(x)\n"
] |
[
[
"torch.nn.functional.normalize",
"torch.Tensor",
"torch.nn.PReLU",
"torch.nn.Identity",
"torch.t"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
TMB-CSB/HDXer
|
[
"6ad1d73931f6a53922c3c960e6c3f67ebcbd7161"
] |
[
"HDXer/dfpred.py"
] |
[
"# Superclass for HDX deuterated fraction prediction method objects\n#\n\nimport mdtraj as md\nimport numpy as np\nimport os, glob, pickle\nfrom .functions import list_prolines\nfrom .errors import HDX_Error\n\n\nclass DfPredictor(object):\n \"\"\"Superclass for all methods that use the general rate equation:\n\n Df(t) = 1 - exp((kint/Pf)*t)\n\n making use of an intrinsic rate and protection factor to calculate\n deuteration at a given time T.\n\n This object contains functions common to all prediction models, such\n as calculation of intrinsic rates from a sequence, but it will NOT\n calculate protection factors or deuterated fractions alone. Initialises\n with a dictionary of default parameters for analysis, accessible as self.params\n\n Default parameters can either be updated directly in the self.params\n dictionary or by supplying a extra parameters as kwargs during\n initialisation of the child class, e.g.: BV(cut_nc=1.0) or PH(**param_dict)\n \n Parameters (type, default value) defined here, and common to all DfPredictor methods:\n protonly (bool, True) : Only calculate protection arising from atoms defined as part of the protein in the topology. Other atoms (ligand, lipids, ions) do not contribute to structural protection\n save_detailed (bool, False) : For each residue, write text files to disk describing the individual structural contributions (e.g. H-bonds, contacts) to protection at each trajectory frame. Useful for debugging or reweighting\n skip_first (bool, True) : Exclude the N-terminal residue in each peptide from deuteration calculations, as it is assumed to be fully back-exchanged\n kint_adjs (dict, None) : Adjustments to the default sequence-based intrinsic rates of Nguyen 2018 & Bai 1993. Each key is a residue name, and each value a list of the adjustments to the Ala intrinsic rate, in the order [ lgAL, lgAR, lgBL, lgBR ], as defined in Table 2 of Nguyen et al., J. Am. Soc. Mass Spec., 2018, 29, 1936-1939. E.g. kint_adjs = { 'GLY': [ -0.22, 0.22, -0.03, 0.17 ] }. Only adjust these parameters if you wish to adjust the intrinsic rate calculations!\n kint_params (dict, None) : Adjustments to the experimental constants & conditions used for intrinsic rate calculations. Each key/value pair corresponds to an experimental parameter. The following parameters (default value) can be adjusted: lgkAref (2.04), lgkBref (10.36), lgkWref (-1.5), EaA (14.0), EaB (17.0), EaW (19.0), R (0.001987), Tref (293), Texp (298), pKD (14.87), pD (7.4). Only adjust these parameters if you wish to adjust the intrinsic rate calculations!\n times (list, [0.167, 1.0, 10.0, 120.0]) : Labeling times in minutes at which to calculate deuteration\n segfile (str, 'segfile.txt') : File containing the peptides for deuteration calculations\n expfile (str, None) : File containing the experimental deuteration values for comparison to predicted values\n logfile (str, 'HDX_analysis.log') : File for message logging during the protection factor predictions \n outprefix (str, '') : Prefix for all output files from HDXer\n\n Additional parameters can be defined specifically for each protection factor predictive model - see the docstrings of each child class for details.\n\n \"\"\"\n\n def __init__(self, **extra_params):\n \"\"\"Initialises a deuterated fraction predictor and updates\n parameters associated with it.\n See self.params for default values\"\"\"\n # Initialise main parameters with defaults\n self.params = { 'protonly' : True,\n 'save_detailed' : False,\n 'skip_first' : True,\n 'kint_adjs' : None,\n 'kint_params' : None,\n 'times' : [ 0.167, 1.0, 10.0, 120.0],\n 'segfile' : \"segfile.txt\",\n 'expfile' : None,\n 'logfile' : \"HDX_analysis.log\",\n 'outprefix' : '' }\n self.params.update(extra_params) # Update main parameter set from kwargs\n\n # Default rate adjustments for adjacent amino acids\n # Each key is a residue name, each value is [ lgAL, lgAR, lgBL, lgBR ]\n # Values from Nguyen et al., J. Am. Soc. Mass Spec., 2018, 29, 1936-1939\n\n # Note that these are the 2018 parameters used on Englander's website\n rate_adjs = { 'ALA': [ 0.00, 0.00, 0.00, 0.00 ],\n 'ARG': [ -0.59, -0.32, 0.08, 0.22 ],\n 'ASN': [ -0.58, -0.13, 0.49, 0.32 ],\n 'ASP': [ 0.90, 0.58, 0.10, -0.18 ],\n 'ASH': [ -0.90, -0.12, 0.69, 0.60 ], # Protonated ASP \n 'CYS': [ -0.54, -0.46, 0.62, 0.55 ],\n 'CYS2': [ -0.74, -0.58, 0.55, 0.46 ], # Disulfide \n 'GLY': [ -0.22, 0.22, -0.03, 0.17 ],\n 'GLN': [ -0.47, -0.27, 0.06, 0.20 ],\n 'GLU': [ -0.90, 0.31, -0.11, -0.15 ],\n 'GLH': [ -0.60, -0.27, 0.24, 0.39 ], # Protonated GLU \n 'HIS': [ 0.00, 0.00, -0.10, 0.14 ], # Acid rates are N/D, \n # but at pH where His is deprotonated,\n # errors will be negligible \n 'HIP': [ -0.80, -0.51, 0.80, 0.83 ],\n 'ILE': [ -0.91, -0.59, -0.73, -0.23 ],\n 'LEU': [ -0.57, -0.13, -0.58, -0.21 ],\n 'LYS': [ -0.56, -0.29, -0.04, 0.12 ],\n 'MET': [ -0.64, -0.28, -0.01, 0.11 ],\n 'PHE': [ -0.52, -0.43, -0.24, 0.06 ],\n 'PRO': [ 0.00, -0.19, 0.00, -0.24 ], # Trans PRO \n 'PROC': [ 0.00, -0.85, 0.00, 0.60 ], # Cis PRO \n 'SER': [ -0.44, -0.39, 0.37, 0.30 ],\n 'THR': [ -0.79, -0.47, -0.07, 0.20 ],\n 'TRP': [ -0.40, -0.44, -0.41, -0.11 ],\n 'TYR': [ -0.41, -0.37, -0.27, 0.05 ],\n 'VAL': [ -0.74, -0.30, -0.70, -0.14 ],\n 'NT': [ 0.00, -1.32, 0.00, 1.62 ], # N-term NH3+ \n 'CT': [ 0.96, 0.00, -1.80, 0.00 ], # C-term COO- \n 'CTH': [ 0.05, 0.00, 0.00, 0.00 ], } # C-term COOH\n\n # Add updates from kint_adjs dictionary if it's given as a kwarg\n if self.params['kint_adjs'] is not None:\n rate_adjs.update(self.params['kint_adjs'])\n self.params['kint_adjs'] = rate_adjs\n\n # Adjust ordering so value is [ lgAL, lgBL, lgAR, lgBR ] for kint analysis \n ### THIS IS A DIFFERENT ORDER TO TABLE 2 IN THE REFERENCE ABOVE ###\n _reordered_rate_adjs = { k : v[:] for k, v in self.params['kint_adjs'].items() } # Deep copy\n for i in _reordered_rate_adjs.values():\n i[1], i[2] = i[2], i[1]\n self.params['_reordered_kint_adjs'] = _reordered_rate_adjs\n \n # Default parameters for ka/kb/kw estimations\n # Values from Bai et al., Proteins, 1993, 17, 75-86\n rate_params = { 'lgkAref' : 2.04,\n 'lgkBref' : 10.36,\n 'lgkWref' : -1.5,\n 'EaA' : 14.,\n 'EaB' : 17.,\n 'EaW' : 19.,\n 'R' : 0.001987,\n 'Tref' : 293,\n 'Texp' : 298,\n 'pKD' : 14.87,\n 'pD' : 7.4 }\n\n # Add updates from kint_adjs dictionary if it's given as a kwarg\n if self.params['kint_params'] is not None:\n rate_params.update(self.params['kint_params'])\n self.params['kint_params'] = rate_params\n\n def __getstate__(self):\n \"\"\"Set state of object for pickling.\n Additional attributes can be removed here\"\"\"\n odict = self.__dict__.copy()\n delparams = ['t'] # MDTraj trajectory object\n if os.path.exists(self.params['outprefix']+\"topology.pkl\"):\n delparams.append('top')\n else:\n pickle.dump(odict.pop('top'), open(self.params['outprefix']+\"topology.pkl\", 'wb'), protocol=-1)\n\n # Ignore key errors here as deepcopy in Analysis object __add__ also uses\n # this __getstate__\n for k in delparams:\n try:\n del odict[k] \n except KeyError:\n pass\n return odict\n\n def __setstate__(self, d):\n \"\"\"Set state of object after pickling.\n Additional attributes can be added here\"\"\"\n self.__dict__ = d\n if os.path.exists(self.params['outprefix']+\"topology.pkl\"):\n try:\n self.top = pickle.load(open(self.params['outprefix']+\"topology.pkl\", 'rb'))\n except (IOError, EOFError):\n raise HDX_Error(\"Can't read cached topology file %s. \"\\\n \"Re-run calculation after removing the file.\" \\\n % (self.params['outprefix']+\"topology.pkl\"))\n else:\n raise HDX_Error(\"No such cache file %s. Re-run the calculation, it should be \" \\\n \"created automatically if a Df prediction is run.\" \\\n % (self.params['outprefix']+\"topology.pkl\"))\n\n def pro_omega_indices(self, prolines):\n \"\"\"Calculates omega dihedrals (CA-C-N-CA) for all proline\n residues in a given prolines array from list_prolines.\n \n Usage: pro_omega_indices(prolines)\n Returns: (atom_indices, w_angles_by_frame)\"\"\"\n\n atom_names = ['CA', 'C', 'N', 'CA']\n offset = np.asarray([-1, -1, 0, 0])\n\n w_indices = np.zeros((len(prolines),4))\n for i, residx in enumerate(prolines[:,1]):\n curr_offset = offset + residx\n curr_atm_indices = []\n for x in zip(curr_offset, atom_names):\n # Cycle through previous CA/C, current N, CA\n curr_atm_indices.append(self.top.residue(x[0]).atom(x[1]).index)\n w_indices[i] = curr_atm_indices\n\n return w_indices, md.compute_dihedrals(self.t, w_indices)\n\n # Assignments for intrinsic rate adjustments:\n # 1) cis/trans prolines\n # 2) disulfides\n # 3) His protonation states\n # 4) N/C termini\n\n def assign_cis_proline(self):\n \"\"\"Assigns cis-proline residues on a by-frame basis\"\"\"\n\n prolines = list_prolines(self.t, log=self.params['logfile'])\n if prolines is None:\n pass\n else:\n outidxs, outangs = self.pro_omega_indices(prolines)\n for i, proidx in enumerate(prolines[:,1]):\n self.top.residue(proidx).cis_byframe = np.logical_and(outangs < np.pi/2, outangs > -1*np.pi/2)[:,i]\n if np.max(self.top.residue(proidx).cis_byframe) > 0:\n with open(self.params['logfile'], 'a') as f:\n f.write(\"Cis-proline found at frame %d for residue %s!\\n\" % (np.argmax(self.top.residue(proidx).cis_byframe) + 1, self.top.residue(proidx).resSeq))\n\n def assign_disulfide(self):\n \"\"\"Assigns residues involved in disulfide bridges\"\"\"\n\n # This assignment is what MDtraj uses for cyx detection \n def isCyx(res):\n names = [atom.name for atom in res._atoms]\n return 'SG' in names and 'HG' not in names\n\n cyx = [res for res in self.top.residues\n if res.name == 'CYS' and isCyx(res)]\n\n if len(cyx) > 0:\n sg_coords = self.t.xyz[0]\n else: # Catch empty cyx\n with open(self.params['logfile'], 'a') as f:\n f.write(\"No oxidised cysteines (CYX) found in topology.\\n\")\n return\n \n self.top.create_standard_bonds()\n self.top._bonds = list(set(self.top._bonds)) # remove duplicates\n self.top.create_disulfide_bonds(sg_coords)\n\n # Assign disulfides (identical for each frame)\n for b in self.top._bonds:\n if all(i.element.symbol == 'S' for i in b):\n b[0].residue.disulf = np.ones(self.t.n_frames, dtype=bool)\n b[1].residue.disulf = np.ones(self.t.n_frames, dtype=bool)\n with open(self.params['logfile'], 'a') as f:\n f.write(\"Disulfide found for residues %s - %s\\n\" \\\n % (b[0].residue, b[1].residue))\n\n def assign_his_protonation(self):\n \"\"\"Assigns protonation state to HIS residues\"\"\"\n\n hisidx = [ r.index for r in self.top.residues if r.code == 'H' ]\n for i in hisidx:\n names = [ a.name for a in self.top.residue(i).atoms ]\n if all(n in names for n in ['HD1','HE2']): # Atom names for doubly protonated His (Hip)\n self.top.residue(i).HIP = np.ones(self.t.n_frames, dtype=bool)\n with open(self.params['logfile'], 'a') as f:\n f.write(\"Protonated His assigned for residue %d\\n\" % self.top.residue(i).resSeq)\n# else:\n# self.top.residue(i).HIP = np.zeros(self.t.n_frames, dtype=bool)\n\n def assign_termini(self):\n \"\"\"Assigns flags to N and C terminal residues\"\"\"\n\n nterm_manual, cterm_manual = False, False\n for c in self.top.chains:\n if c.residue(0).is_protein:\n c.residue(0).nterm = np.ones(self.t.n_frames, dtype=bool)\n nterm = c.residue(0)\n else:\n nterm_manual = True\n nterm_idx = self.top.select(\"protein\")[0]\n nterm = self.top.atom(nterm_idx).residue\n nterm.nterm = np.ones(self.t.n_frames, dtype=bool)\n if c.residue(-1).is_protein:\n c.residue(-1).cterm = np.ones(self.t.n_frames, dtype=bool)\n cterm = c.residue(-1)\n else:\n cterm_manual = True\n cterm_idx = self.top.select(\"protein\")[-1]\n cterm = self.top.atom(cterm_idx).residue\n cterm.cterm = np.ones(self.t.n_frames, dtype=bool)\n with open(self.params['logfile'], 'a') as f:\n if any((nterm_manual, cterm_manual)):\n f.write(\"One or more of the chain termini is not a protein residue.\\n\"\n \"This could be because you don't have chain info in your topology,\\n\"\n \"or because ligands/waters/ions are identified as separate chains.\\n\"\n \"Selecting termini from protein residues instead, check below:\\n\")\n \n f.write(\"N-terminus identified at: %s\\nC-terminus identified at: %s\\n\" \\\n % (nterm, cterm))\n\n\n # Helper function to turn sequence-specific rate adjustments to intrinsic acid/base/water rates\n def _adj_to_rates(self, rate_adjs):\n \"\"\"Helper function for kint().\n Calculates intrinsic rates for a given set of rate adjustments\n [ log(AL), log(BL), log(AR), log(BR) ] taken from Bai et al.\n\n Usage: _adj_to_rates(rate_adjs)\n Returns: intrinsic_rate\"\"\"\n\n # Calc reference rates at experimental temperature\n # / np.log(10) = conversion from ln to log10\n lgkAexp = self.params['kint_params']['lgkAref'] - (self.params['kint_params']['EaA']\n / np.log(10) / self.params['kint_params']['R']) * \\\n (1./self.params['kint_params']['Texp'] - 1./self.params['kint_params']['Tref'])\n lgkBexp = self.params['kint_params']['lgkBref'] - (self.params['kint_params']['EaB']\n / np.log(10) / self.params['kint_params']['R']) * \\\n (1./self.params['kint_params']['Texp'] - 1./self.params['kint_params']['Tref'])\n lgkWexp = self.params['kint_params']['lgkWref'] - (self.params['kint_params']['EaW']\n / np.log(10) / self.params['kint_params']['R']) * \\\n (1./self.params['kint_params']['Texp'] - 1./self.params['kint_params']['Tref'])\n\n # Calc log(kA||kB||kW)\n lgkA = lgkAexp + rate_adjs[0] + rate_adjs[2] - self.params['kint_params']['pD']\n lgkB = lgkBexp + rate_adjs[1] + rate_adjs[3] - self.params['kint_params']['pKD'] + self.params['kint_params']['pD']\n lgkW = lgkWexp + rate_adjs[1] + rate_adjs[3]\n\n kint = 10**lgkA + 10**lgkB + 10**lgkW\n #print(lgkAexp, lgkBexp, lgkWexp, 10**lgkA, 10**lgkB, 10**lgkW)\n return kint\n\n# Intrinsic rate calc:\n def kint(self):\n \"\"\"Function for calculating intrinsic rates of residues\n in a given topology\n \n Intrinsic exchange rates k_int are computed using equations below.\n k_int = k_A + k_B + k_W\n lgk_A = lgk_A,ref + lgA_L + lgA_R - pD\n lgk_B = lgk_B,ref + lgB_L + lgB_R - pOD\n = lgk_B,ref + lgB_L + lgB_R - pK_D + pOD\n lgk_W = lgk_W,ref + lgB_L + lgB_R\n\n Default parameters for the above can be modified in the \n BV.params['kint_params'] dictionary. Sequence-based\n rate adjustments can be modified in the 'kint_adjs' and\n '_reordered_kint_adjs' dictionaries.\n\n Usage: kint()\n Returns: array of by-residue intrinsic rates\"\"\"\n\n kints = np.zeros(len(self.reslist))\n\n\n # Adjust residue names for: Cis-Pro, HIP, cystine bridges, GLH/ASH\n reslist = self.reslist.copy()\n for c in self.top.chains:\n if c.n_residues > 1: # Chain of length 1 is probably a ligand - ignore!\n firstres = c.residue(0).index\n secres = next(r.index for r in c._residues[1:] if r.name != 'PRO')\n try:\n insert_idx = reslist.tolist().index(secres)\n reslist = np.insert(reslist, insert_idx, firstres) # Insert 'prev' residue for first index of each chain, as we need to define these as NT\n except ValueError:\n pass\n oldnames = {}\n for i in reslist:\n curr = self.top.residue(i)\n try:\n if np.max(self.cis_byframe[i]): # If cis-proline is true for any frame\n oldnames[i] = curr.name\n curr.name = 'PROC'\n continue\n except AttributeError:\n pass\n try:\n if np.max(curr.HIP): # If His+ is true for any frame\n oldnames[i] = curr.name\n curr.name = 'HIP'\n continue\n except AttributeError:\n pass\n try:\n if np.max(curr.disulf): # If Cys-Cys is true for any frame\n oldnames[i] = curr.name\n curr.name = 'CYS2'\n continue\n except AttributeError:\n pass\n if curr.name == 'GLU': # If Glu has a protonated carboxylate\n try:\n curr.atom('HE2')\n oldnames[i] = curr.name\n curr.name = 'GLH'\n continue\n except KeyError:\n pass\n if curr.name == 'ASP': # If Asp has a protonated carboxylate\n try:\n curr.atom('HD2')\n oldnames[i] = curr.name\n curr.name = 'ASH'\n continue\n except KeyError:\n pass\n # Assign N/C termini\n try:\n if np.max(curr.nterm): # If nterm is true for any frame\n oldnames[i] = curr.name\n curr.name = 'NT'\n continue\n except AttributeError:\n pass\n try:\n if np.max(curr.cterm): # If cterm is true for any frame\n oldnames[i] = curr.name\n try:\n if (curr.atom('O').n_bonds > 1 or curr.atom('OXT').n_bonds > 1):\n curr.name = 'CTH'\n with open(self.params['logfile'], 'a') as f:\n f.write(\"It looks like you have a neutral C-terminus (COOH) at residue %s?\\n\" % curr)\n else:\n curr.name = 'CT'\n continue\n except KeyError:\n with open(self.params['logfile'], 'a') as f:\n f.write(\"Residue %s is defined as a C-terminus but has no atom O or OXT, is this correct?\\n\" % curr)\n curr.name = 'CT'\n continue\n except AttributeError:\n pass\n\n for c in self.top.chains:\n firstres = c.residue(0).index\n try:\n del_idx = reslist.tolist().index(firstres)\n reslist = np.delete(reslist, del_idx) # Remove 'prev' residue we inserted above\n except (ValueError, IndexError): # Not in list or no index in array\n pass\n \n try:\n if np.array_equal(reslist, self.reslist):\n pass\n else:\n raise HDX_Error(\"Your residue lists for protection factors and intrinsic rates are different. Check your inputs!\")\n except AttributeError:\n print(\"Please generate protection factors before running intrinsic rate calculations.\")\n return\n for i, r in enumerate(reslist):\n curr = self.top.residue(r)\n if r != 0:\n prev = self.top.residue(r-1)\n else:\n prev = curr\n kints[i] = np.inf\n continue\n # check for cispro\n if prev.name == 'PROC':\n with open(self.params['logfile'], 'a') as f:\n f.write(\"Performing rate calculation on a by-frame basis for residue %s\" % prev)\n adj_cis, adj_trans = self.params['_reordered_kint_adjs'][curr.name][0:2], self.params['_reordered_kint_adjs'][curr.name][0:2]\n adj_cis.extend(self.params['_reordered_kint_adjs']['PROC'][2:4])\n adj_trans.extend(self.params['_reordered_kint_adjs']['PRO'][2:4])\n kint_cis = self._adj_to_rates(adj_cis)\n kint_trans = self._adj_to_rates(adj_trans)\n kint_byframe = np.where(prev.cis_byframe, kint_cis, kint_trans)\n kints[i] = np.mean(kint_byframe) # Overall intrinsic rate is adjusted by mean population of cis-pro\n else:\n curr_adjs = self.params['_reordered_kint_adjs'][curr.name][0:2]\n curr_adjs.extend(self.params['_reordered_kint_adjs'][prev.name][2:4])\n kints[i] = self._adj_to_rates(curr_adjs)\n\n rids = np.asarray([ self.top.residue(i).resSeq for i in reslist ])\n # Save Kints to separate log file, appending filenames for trajectories read as chunks\n if os.path.exists(self.params['outprefix']+\"Intrinsic_rates.dat\"):\n filenum = len(glob.glob(self.params['outprefix']+\"Intrinsic_rates*\"))\n np.savetxt(self.params['outprefix']+\"Intrinsic_rates_chunk_%d.dat\" % (filenum+1),\n np.stack((rids, kints), axis=1), fmt=['%7d','%18.8f'],\n header=\"ResID Intrinsic rate / min^-1 \") # Use residue indices internally, print out IDs\n else: \n np.savetxt(self.params['outprefix']+\"Intrinsic_rates.dat\", np.stack((rids, kints), axis=1),\n fmt=['%7d','%18.8f'], header=\"ResID Intrinsic rate / min^-1 \") # Use residue indices internally, print out IDs\n\n for residx, oldname in oldnames.items():\n self.top.residue(residx).name = oldname\n self.oldnames = oldnames\n return kints\n\n # Deuterated fration by residue\n def dfrac(self, write=True, use_self=True, alternate_pfs=None):\n \"\"\"Function for calculating by-residue deuterated fractions, for\n a set of Protection factors, intrinsic rates, and exposure times\n previously defined for the current BV object. Optionally write\n out results.\n\n Alternatively, if use_self=False, take an alternative set of PFs\n not assigned to the current object and perform the same calculation\n on them.\n\n Usage: dfrac([write=True, use_self=True, alternate_pfs=None])\n Returns: [n_residues, n_times] 2D numpy array of deuterated fractions\"\"\"\n\n if use_self:\n try:\n curr_pfs = np.stack((np.exp(np.mean(self.lnpf_byframe, axis=1)), np.exp(np.std(self.lnpf_byframe, axis=1, ddof=1))), axis=1)\n except AttributeError:\n curr_pfs = np.stack((np.mean(self.pf_byframe, axis=1), np.std(self.pf_byframe, axis=1, ddof=1)), axis=1) # No lnPF for Persson-Halle etc\n \n if len(set(map(len,[self.reslist, self.pfs, self.rates]))) != 1: # Check that all lengths are the same (set length = 1)\n raise HDX_Error(\"Can't calculate deuterated fractions, your residue/protection factor/rates arrays are not the same length.\")\n else:\n curr_pfs = alternate_pfs\n if len(set(map(len,[self.reslist, alternate_pfs, self.rates]))) != 1: # Check that all lengths are the same (set length = 1)\n raise HDX_Error(\"Can't calculate deuterated fractions, your provided residue/protection factor/rates arrays are not the same length.\")\n\n curr_pfs[:,1][np.isinf(curr_pfs[:,1])] = 0\n\n try:\n fracs = np.zeros((len(self.reslist), len(self.params['times']), 2))\n except TypeError:\n fracs = np.zeros((len(self.reslist), 1, 2))\n for i2, t in enumerate(self.params['times']):\n def _residue_fraction(pf, k, time=t):\n logf = -k / pf[0] * time\n val = 1 - np.exp(logf)\n err = (pf[1]/pf[0]) * k/pf[0] # sd(bA^-1) = rel_sd(A) * A^-1 * b\n logerr = logf + np.log(err) + np.log(time) # sd(e^Aa) = f * sd(A) * a\n err = np.exp(logerr) # Avoid underflow \n return np.asarray([val, err])\n for i1, curr_frac in enumerate(map(_residue_fraction, curr_pfs, self.rates)):\n fracs[i1,i2,:] = curr_frac\n\n rids = np.asarray([ self.top.residue(i).resSeq for i in self.reslist ])\n rids = np.reshape(rids, (len(self.reslist),1))\n # Write resfracs to separate file, appending filenames for trajectories read as chunks\n outfracs = np.reshape(fracs.flatten(), (fracs.shape[0], fracs.shape[1] * fracs.shape[2])) # Reshape as 'Time Err Time Err...' \n if write:\n if os.path.exists(self.params['outprefix']+\"Residue_fractions.dat\"):\n filenum = len(glob.glob(self.params['outprefix']+\"Residue_fractions*\"))\n np.savetxt(self.params['outprefix']+\"Residue_fractions_chunk_%d.dat\" % (filenum+1),\n np.concatenate((rids, outfracs), axis=1),\n fmt='%7d ' + '%8.5f '*len(self.params['times']*2),\n header=\"ResID Deuterated fraction, Times, std. dev / min : %s\" \\\n % ' '.join([ str(t) for t in self.params['times'] ])) # Use residue indices internally, print out IDs\n else: \n np.savetxt(self.params['outprefix']+\"Residue_fractions.dat\",\n np.concatenate((rids, outfracs), axis=1),\n fmt='%7d ' + '%8.5f '*len(self.params['times']*2),\n header=\"ResID Deuterated fraction, Times / min: %s\" \\\n % ' '.join([ str(t) for t in self.params['times'] ])) # Use residue indices internally, print out IDs\n return fracs\n\n"
] |
[
[
"numpy.log",
"numpy.array_equal",
"numpy.logical_and",
"numpy.asarray",
"numpy.stack",
"numpy.ones",
"numpy.concatenate",
"numpy.max",
"numpy.delete",
"numpy.std",
"numpy.mean",
"numpy.insert",
"numpy.exp",
"numpy.where",
"numpy.isinf"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
flyinslowly/flyinnlp
|
[
"328e45d2952da6cdebbc1cccbb6a0aa9972859df"
] |
[
"allennlp/models/reading_comprehension/bidaf.py"
] |
[
"import logging\nfrom typing import Any, Dict, List, Optional\n\nimport torch\nfrom torch.nn.functional import nll_loss, binary_cross_entropy_with_logits, sigmoid\n\nfrom allennlp.common.checks import check_dimensions_match\nfrom allennlp.data import Vocabulary\nfrom allennlp.models.model import Model\nfrom allennlp.models.reading_comprehension.util import get_best_span\nfrom allennlp.modules import Highway\nfrom allennlp.modules import Seq2SeqEncoder, SimilarityFunction, TimeDistributed, TextFieldEmbedder\nfrom allennlp.modules.matrix_attention.legacy_matrix_attention import LegacyMatrixAttention\nfrom allennlp.nn import util, InitializerApplicator, RegularizerApplicator\nfrom allennlp.training.metrics import BooleanAccuracy, CategoricalAccuracy, SquadEmAndF1\n\nlogger = logging.getLogger(__name__)\n\n\[email protected](\"bidaf\")\nclass BidirectionalAttentionFlow(Model):\n \"\"\"\n This class implements Minjoon Seo's `Bidirectional Attention Flow model\n <https://www.semanticscholar.org/paper/Bidirectional-Attention-Flow-for-Machine-Seo-Kembhavi/7586b7cca1deba124af80609327395e613a20e9d>`_\n for answering reading comprehension questions (ICLR 2017).\n\n The basic layout is pretty simple: encode words as a combination of word embeddings and a\n character-level encoder, pass the word representations through a bi-LSTM/GRU, use a matrix of\n attentions to put question information into the passage word representations (this is the only\n part that is at all non-standard), pass this through another few layers of bi-LSTMs/GRUs, and\n do a softmax over span start and span end.\n\n Parameters\n ----------\n vocab : ``Vocabulary``\n text_field_embedder : ``TextFieldEmbedder``\n Used to embed the ``question`` and ``passage`` ``TextFields`` we get as input to the model.\n num_highway_layers : ``int``\n The number of highway layers to use in between embedding the input and passing it through\n the phrase layer.\n phrase_layer : ``Seq2SeqEncoder``\n The encoder (with its own internal stacking) that we will use in between embedding tokens\n and doing the bidirectional attention.\n similarity_function : ``SimilarityFunction``\n The similarity function that we will use when comparing encoded passage and question\n representations.\n modeling_layer : ``Seq2SeqEncoder``\n The encoder (with its own internal stacking) that we will use in between the bidirectional\n attention and predicting span start and end.\n span_end_encoder : ``Seq2SeqEncoder``\n The encoder that we will use to incorporate span start predictions into the passage state\n before predicting span end.\n dropout : ``float``, optional (default=0.2)\n If greater than 0, we will apply dropout with this probability after all encoders (pytorch\n LSTMs do not apply dropout to their last layer).\n mask_lstms : ``bool``, optional (default=True)\n If ``False``, we will skip passing the mask to the LSTM layers. This gives a ~2x speedup,\n with only a slight performance decrease, if any. We haven't experimented much with this\n yet, but have confirmed that we still get very similar performance with much faster\n training times. We still use the mask for all softmaxes, but avoid the shuffling that's\n required when using masking with pytorch LSTMs.\n initializer : ``InitializerApplicator``, optional (default=``InitializerApplicator()``)\n Used to initialize the model parameters.\n regularizer : ``RegularizerApplicator``, optional (default=``None``)\n If provided, will be used to calculate the regularization penalty during training.\n \"\"\"\n\n def __init__(\n self,\n vocab: Vocabulary,\n text_field_embedder: TextFieldEmbedder,\n num_highway_layers: int,\n phrase_layer: Seq2SeqEncoder,\n similarity_function: SimilarityFunction,\n modeling_layer: Seq2SeqEncoder,\n span_end_encoder: Seq2SeqEncoder,\n dropout: float = 0.2,\n mask_lstms: bool = True,\n initializer: InitializerApplicator = InitializerApplicator(),\n regularizer: Optional[RegularizerApplicator] = None,\n ) -> None:\n super().__init__(vocab, regularizer)\n\n self._text_field_embedder = text_field_embedder\n self._highway_layer = TimeDistributed(\n Highway(text_field_embedder.get_output_dim(), num_highway_layers)\n )\n self._phrase_layer = phrase_layer\n self._matrix_attention = LegacyMatrixAttention(similarity_function)\n self._modeling_layer = modeling_layer\n self._span_end_encoder = span_end_encoder\n\n encoding_dim = phrase_layer.get_output_dim()\n modeling_dim = modeling_layer.get_output_dim()\n span_start_input_dim = encoding_dim * 4 + modeling_dim\n self._span_start_predictor = TimeDistributed(torch.nn.Linear(span_start_input_dim, 1))\n\n span_end_encoding_dim = span_end_encoder.get_output_dim()\n span_end_input_dim = encoding_dim * 4 + span_end_encoding_dim\n self._span_end_predictor = TimeDistributed(torch.nn.Linear(span_end_input_dim, 1))\n\n # Bidaf has lots of layer dimensions which need to match up - these aren't necessarily\n # obvious from the configuration files, so we check here.\n check_dimensions_match(\n modeling_layer.get_input_dim(),\n 4 * encoding_dim,\n \"modeling layer input dim\",\n \"4 * encoding dim\",\n )\n check_dimensions_match(\n text_field_embedder.get_output_dim(),\n phrase_layer.get_input_dim(),\n \"text field embedder output dim\",\n \"phrase layer input dim\",\n )\n check_dimensions_match(\n span_end_encoder.get_input_dim(),\n 4 * encoding_dim + 3 * modeling_dim,\n \"span end encoder input dim\",\n \"4 * encoding dim + 3 * modeling dim\",\n )\n\n self._accuracy = BooleanAccuracy()\n if dropout > 0:\n self._dropout = torch.nn.Dropout(p=dropout)\n else:\n self._dropout = lambda x: x\n self._mask_lstms = mask_lstms\n\n initializer(self)\n\n def forward( # type: ignore\n self,\n question: Dict[str, torch.LongTensor],\n passage: Dict[str, torch.LongTensor],\n answer: torch.BoolTensor = None,\n metadata: List[Dict[str, Any]] = None,\n ) -> Dict[str, torch.Tensor]:\n\n \"\"\"\n Parameters\n ----------\n question : Dict[str, torch.LongTensor]\n From a ``TextField``.\n passage : Dict[str, torch.LongTensor]\n From a ``TextField``. The model assumes that this passage contains the answer to the\n question, and predicts the beginning and ending positions of the answer within the\n passage.\n span_start : ``torch.IntTensor``, optional\n From an ``IndexField``. This is one of the things we are trying to predict - the\n beginning position of the answer with the passage. This is an `inclusive` token index.\n If this is given, we will compute a loss that gets included in the output dictionary.\n span_end : ``torch.IntTensor``, optional\n From an ``IndexField``. This is one of the things we are trying to predict - the\n ending position of the answer with the passage. This is an `inclusive` token index.\n If this is given, we will compute a loss that gets included in the output dictionary.\n metadata : ``List[Dict[str, Any]]``, optional\n metadata : ``List[Dict[str, Any]]``, optional\n If present, this should contain the question tokens, passage tokens, original passage\n text, and token offsets into the passage for each instance in the batch. The length\n of this list should be the batch size, and each dictionary should have the keys\n ``question_tokens``, ``passage_tokens``, ``original_passage``, and ``token_offsets``.\n\n Returns\n -------\n An output dictionary consisting of:\n span_start_logits : torch.FloatTensor\n A tensor of shape ``(batch_size, passage_length)`` representing unnormalized log\n probabilities of the span start position.\n span_start_probs : torch.FloatTensor\n The result of ``softmax(span_start_logits)``.\n span_end_logits : torch.FloatTensor\n A tensor of shape ``(batch_size, passage_length)`` representing unnormalized log\n probabilities of the span end position (inclusive).\n span_end_probs : torch.FloatTensor\n The result of ``softmax(span_end_logits)``.\n best_span : torch.IntTensor\n The result of a constrained inference over ``span_start_logits`` and\n ``span_end_logits`` to find the most probable span. Shape is ``(batch_size, 2)``\n and each offset is a token index.\n loss : torch.FloatTensor, optional\n A scalar loss to be optimised.\n best_span_str : List[str]\n If sufficient metadata was provided for the instances in the batch, we also return the\n string from the original passage that the model thinks is the best answer to the\n question.\n \"\"\"\n embedded_question = self._highway_layer(self._text_field_embedder(question))\n embedded_passage = self._highway_layer(self._text_field_embedder(passage))\n batch_size = embedded_question.size(0)\n passage_length = embedded_passage.size(1)\n question_mask = util.get_text_field_mask(question).float()\n passage_mask = util.get_text_field_mask(passage).float()\n question_lstm_mask = question_mask if self._mask_lstms else None\n passage_lstm_mask = passage_mask if self._mask_lstms else None\n\n encoded_question = self._dropout(self._phrase_layer(embedded_question, question_lstm_mask))\n encoded_passage = self._dropout(self._phrase_layer(embedded_passage, passage_lstm_mask))\n encoding_dim = encoded_question.size(-1)\n\n # Shape: (batch_size, passage_length, question_length)\n passage_question_similarity = self._matrix_attention(encoded_passage, encoded_question)\n # Shape: (batch_size, passage_length, question_length)\n passage_question_attention = util.masked_softmax(passage_question_similarity, question_mask)\n # Shape: (batch_size, passage_length, encoding_dim)\n passage_question_vectors = util.weighted_sum(encoded_question, passage_question_attention)\n\n # We replace masked values with something really negative here, so they don't affect the\n # max below.\n masked_similarity = util.replace_masked_values(\n passage_question_similarity, question_mask.unsqueeze(1), -1e7\n )\n # Shape: (batch_size, passage_length)\n question_passage_similarity = masked_similarity.max(dim=-1)[0].squeeze(-1)\n # Shape: (batch_size, passage_length)\n question_passage_attention = util.masked_softmax(question_passage_similarity, passage_mask)\n # Shape: (batch_size, encoding_dim)\n question_passage_vector = util.weighted_sum(encoded_passage, question_passage_attention)\n # Shape: (batch_size, passage_length, encoding_dim)\n tiled_question_passage_vector = question_passage_vector.unsqueeze(1).expand(\n batch_size, passage_length, encoding_dim\n )\n\n # Shape: (batch_size, passage_length, encoding_dim * 4)\n final_merged_passage = torch.cat(\n [\n encoded_passage,\n passage_question_vectors,\n encoded_passage * passage_question_vectors,\n encoded_passage * tiled_question_passage_vector,\n ],\n dim=-1,\n )\n\n modeled_passage = self._dropout(\n self._modeling_layer(final_merged_passage, passage_lstm_mask)\n )\n modeling_dim = modeled_passage.size(-1)\n\n # Shape: (batch_size, passage_length, encoding_dim * 4 + modeling_dim))\n span_start_input = self._dropout(torch.cat([final_merged_passage, modeled_passage], dim=-1))\n # Shape: (batch_size, passage_length)\n span_start_logits = self._span_start_predictor(span_start_input).squeeze(-1)\n # Shape: (batch_size, passage_length)\n prediction_bool_logits = util.masked_max(span_start_logits, passage_mask, dim=1)\n\n output_dict = {\n \"passage_question_attention\": passage_question_attention,\n \"prediction_bool_logits\": prediction_bool_logits\n }\n\n # Compute the loss for training.\n if answer is not None:\n loss = binary_cross_entropy_with_logits(\n prediction_bool_logits, answer\n )\n threshold = 0.5\n prediction_bool_logits = torch.where(torch.sigmoid(prediction_bool_logits) > threshold,\n torch.ones_like(prediction_bool_logits), torch.zeros_like(prediction_bool_logits))\n self._accuracy(prediction_bool_logits, answer)\n output_dict[\"loss\"] = loss\n\n return output_dict\n\n def get_metrics(self, reset: bool = False) -> Dict[str, float]:\n return {\n \"acc\": self._accuracy.get_metric(reset)\n }\n"
] |
[
[
"torch.nn.Dropout",
"torch.sigmoid",
"torch.cat",
"torch.nn.functional.binary_cross_entropy_with_logits",
"torch.zeros_like",
"torch.nn.Linear",
"torch.ones_like"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
CaoZhongZ/inference
|
[
"58025f8fde679ea864d34f96ecc9f14bf70ece53",
"58025f8fde679ea864d34f96ecc9f14bf70ece53",
"58025f8fde679ea864d34f96ecc9f14bf70ece53"
] |
[
"speech_recognition/rnnt/pytorch/utils/download_librispeech.py",
"recommendation/dlrm/pytorch/python/backend_onnxruntime.py",
"speech_recognition/rnnt/pytorch/parts/segment.py"
] |
[
"#!/usr/bin/env python\n# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport os\nimport argparse\nimport pandas as pd\n\nfrom download_utils import download_file, md5_checksum, extract\n\nparser = argparse.ArgumentParser(\n description='Download, verify and extract dataset files')\nparser.add_argument('csv', type=str,\n help='CSV file with urls and checksums to download.')\nparser.add_argument('dest', type=str,\n help='Download destnation folder.')\nparser.add_argument('-e', type=str, default=None,\n help='Extraction destnation folder. Defaults to download folder if not provided')\nparser.add_argument('--skip_download', action='store_true',\n help='Skip downloading the files')\nparser.add_argument('--skip_checksum', action='store_true',\n help='Skip checksum')\nparser.add_argument('--skip_extract', action='store_true',\n help='Skip extracting files')\nargs = parser.parse_args()\nargs.e = args.e or args.dest\n\n\ndf = pd.read_csv(args.csv, delimiter=',')\n\n\nif not args.skip_download:\n for url in df.url:\n fname = url.split('/')[-1]\n print(\"Downloading %s:\" % fname)\n download_file(url=url, dest_folder=args.dest, fname=fname)\nelse:\n print(\"Skipping file download\")\n\n\nif not args.skip_checksum:\n for index, row in df.iterrows():\n url = row['url']\n md5 = row['md5']\n fname = url.split('/')[-1]\n fpath = os.path.join(args.dest, fname)\n print(\"Verifing %s: \" % fname, end='')\n ret = md5_checksum(fpath=fpath, target_hash=md5)\n if not ret:\n raise ValueError(f\"Checksum for {fname} failed!\")\n else:\n print(f\"Checksum correct for {fname}\")\nelse:\n print(\"Skipping checksum\")\n\n\nif not args.skip_extract:\n for url in df.url:\n fname = url.split('/')[-1]\n fpath = os.path.join(args.dest, fname)\n print(\"Decompressing %s:\" % fpath)\n extract(fpath=fpath, dest_folder=args.e)\nelse:\n print(\"Skipping file extraction\")\n",
"\"\"\"\nonnxruntime backend (https://github.com/microsoft/onnxruntime)\n\"\"\"\n\n# pylint: disable=unused-argument,missing-docstring,useless-super-delegation\n\nimport onnxruntime as rt\nimport numpy as np\nimport backend\nimport torch\n\n\nclass BackendOnnxruntime(backend.Backend):\n def __init__(self, m_spa, ln_emb, ln_bot, ln_top, use_gpu=False, mini_batch_size=1):\n super(BackendOnnxruntime, self).__init__()\n\n def version(self):\n return rt.__version__\n\n def name(self):\n \"\"\"Name of the runtime.\"\"\"\n return \"onnxruntime\"\n\n def load(self, model_path, inputs=None, outputs=None):\n \"\"\"Load model and find input/outputs from the model file.\"\"\"\n opt = rt.SessionOptions()\n # enable level 3 optimizations\n # FIXME: enable below once onnxruntime 0.5 is released\n # opt.set_graph_optimization_level(3)\n # print(\"onnx load\", model_path, inputs, outputs)\n self.sess = rt.InferenceSession(model_path, opt)\n # get input and output names\n if True: #not inputs:\n self.inputs = [meta.name for meta in self.sess.get_inputs()]\n else:\n self.inputs = inputs\n if True: #not outputs:\n self.outputs = [meta.name for meta in self.sess.get_outputs()]\n else:\n self.outputs = outputs\n return self\n\n def predict(self, batch_dense_X, batch_lS_o, batch_lS_i):\n \"\"\"Run the prediction.\"\"\"\n # print(\"onnx predict\")\n # print(self.inputs)\n # print(self.outputs)\n\n # force list conversion\n # if torch.is_tensor(lS_o_onnx):\n # lS_o_onnx = [lS_o_onnx[j] for j in range(len(lS_o_onnx))]\n # if torch.is_tensor(lS_i_onnx):\n # lS_i_onnx = [lS_i_onnx[j] for j in range(len(lS_i_onnx))]\n # force tensor conversion\n # if isinstance(lS_o_onnx, list):\n # lS_o_onnx = torch.stack(lS_o_onnx)\n # if isinstance(lS_i_onnx, list):\n # lS_i_onnx = torch.stack(lS_i_onnx)\n\n dict_inputs = {}\n dict_inputs[\"dense_x\"] = batch_dense_X.numpy().astype(np.float32)\n if torch.is_tensor(batch_lS_o):\n dict_inputs[\"offsets\"] = batch_lS_o.numpy().astype(np.int64)\n else: # list\n for i in range(len(batch_lS_o)):\n dict_inputs[\"offsets_\"+str(i)] = batch_lS_o[i].numpy().astype(np.int64)\n if torch.is_tensor(batch_lS_i):\n dict_inputs[\"indices\"] = batch_lS_i.numpy().astype(np.int64)\n else: # list\n for i in range(len(batch_lS_i)):\n dict_inputs[\"indices_\"+str(i)] = batch_lS_i[i].numpy().astype(np.int64)\n\n # predict and return output\n # print(\"dict_inputs\", dict_inputs)\n output = self.sess.run(output_names=self.outputs, input_feed=dict_inputs)\n output = torch.tensor(output, requires_grad=False).view(-1, 1)\n # print(\"output\", output)\n # print(\"output.shape\", output.shape)\n\n return output\n",
"# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nimport librosa\nimport soundfile as sf\n\n\nclass AudioSegment(object):\n \"\"\"Monaural audio segment abstraction.\n :param samples: Audio samples [num_samples x num_channels].\n :type samples: ndarray.float32\n :param sample_rate: Audio sample rate.\n :type sample_rate: int\n :raises TypeError: If the sample data type is not float or int.\n \"\"\"\n\n def __init__(self, samples, sample_rate, target_sr=None, trim=False,\n trim_db=60):\n \"\"\"Create audio segment from samples.\n Samples are convert float32 internally, with int scaled to [-1, 1].\n \"\"\"\n samples = self._convert_samples_to_float32(samples)\n if target_sr is not None and target_sr != sample_rate:\n samples = librosa.core.resample(samples, sample_rate, target_sr)\n sample_rate = target_sr\n if trim:\n samples, _ = librosa.effects.trim(samples, trim_db)\n self._samples = samples\n self._sample_rate = sample_rate\n if self._samples.ndim >= 2:\n self._samples = np.mean(self._samples, 1)\n\n def __eq__(self, other):\n \"\"\"Return whether two objects are equal.\"\"\"\n if type(other) is not type(self):\n return False\n if self._sample_rate != other._sample_rate:\n return False\n if self._samples.shape != other._samples.shape:\n return False\n if np.any(self.samples != other._samples):\n return False\n return True\n\n def __ne__(self, other):\n \"\"\"Return whether two objects are unequal.\"\"\"\n return not self.__eq__(other)\n\n def __str__(self):\n \"\"\"Return human-readable representation of segment.\"\"\"\n return (\"%s: num_samples=%d, sample_rate=%d, duration=%.2fsec, \"\n \"rms=%.2fdB\" % (type(self), self.num_samples, self.sample_rate,\n self.duration, self.rms_db))\n\n @staticmethod\n def _convert_samples_to_float32(samples):\n \"\"\"Convert sample type to float32.\n Audio sample type is usually integer or float-point.\n Integers will be scaled to [-1, 1] in float32.\n \"\"\"\n float32_samples = samples.astype('float32')\n if samples.dtype in np.sctypes['int']:\n bits = np.iinfo(samples.dtype).bits\n float32_samples *= (1. / 2 ** (bits - 1))\n elif samples.dtype in np.sctypes['float']:\n pass\n else:\n raise TypeError(\"Unsupported sample type: %s.\" % samples.dtype)\n return float32_samples\n\n @classmethod\n def from_file(cls, filename, target_sr=None, int_values=False, offset=0,\n duration=0, trim=False):\n \"\"\"\n Load a file supported by librosa and return as an AudioSegment.\n :param filename: path of file to load\n :param target_sr: the desired sample rate\n :param int_values: if true, load samples as 32-bit integers\n :param offset: offset in seconds when loading audio\n :param duration: duration in seconds when loading audio\n :return: numpy array of samples\n \"\"\"\n with sf.SoundFile(filename, 'r') as f:\n dtype = 'int32' if int_values else 'float32'\n sample_rate = f.samplerate\n if offset > 0:\n f.seek(int(offset * sample_rate))\n if duration > 0:\n samples = f.read(int(duration * sample_rate), dtype=dtype)\n else:\n samples = f.read(dtype=dtype)\n samples = samples.transpose()\n return cls(samples, sample_rate, target_sr=target_sr, trim=trim)\n\n @property\n def samples(self):\n return self._samples.copy()\n\n @property\n def sample_rate(self):\n return self._sample_rate\n\n @property\n def num_samples(self):\n return self._samples.shape[0]\n\n @property\n def duration(self):\n return self._samples.shape[0] / float(self._sample_rate)\n\n @property\n def rms_db(self):\n mean_square = np.mean(self._samples ** 2)\n return 10 * np.log10(mean_square)\n\n def gain_db(self, gain):\n self._samples *= 10. ** (gain / 20.)\n\n def pad(self, pad_size, symmetric=False):\n \"\"\"Add zero padding to the sample. The pad size is given in number of samples.\n If symmetric=True, `pad_size` will be added to both sides. If false, `pad_size`\n zeros will be added only to the end.\n \"\"\"\n self._samples = np.pad(self._samples,\n (pad_size if symmetric else 0, pad_size),\n mode='constant')\n\n def subsegment(self, start_time=None, end_time=None):\n \"\"\"Cut the AudioSegment between given boundaries.\n Note that this is an in-place transformation.\n :param start_time: Beginning of subsegment in seconds.\n :type start_time: float\n :param end_time: End of subsegment in seconds.\n :type end_time: float\n :raise ValueError: If start_time or end_time is incorrectly set, e.g. out\n of bounds in time.\n \"\"\"\n start_time = 0.0 if start_time is None else start_time\n end_time = self.duration if end_time is None else end_time\n if start_time < 0.0:\n start_time = self.duration + start_time\n if end_time < 0.0:\n end_time = self.duration + end_time\n if start_time < 0.0:\n raise ValueError(\"The slice start position (%f s) is out of \"\n \"bounds.\" % start_time)\n if end_time < 0.0:\n raise ValueError(\"The slice end position (%f s) is out of bounds.\" %\n end_time)\n if start_time > end_time:\n raise ValueError(\"The slice start position (%f s) is later than \"\n \"the end position (%f s).\" % (start_time, end_time))\n if end_time > self.duration:\n raise ValueError(\"The slice end position (%f s) is out of bounds \"\n \"(> %f s)\" % (end_time, self.duration))\n start_sample = int(round(start_time * self._sample_rate))\n end_sample = int(round(end_time * self._sample_rate))\n self._samples = self._samples[start_sample:end_sample]\n"
] |
[
[
"pandas.read_csv"
],
[
"torch.is_tensor",
"torch.tensor"
],
[
"numpy.pad",
"numpy.log10",
"numpy.mean",
"numpy.any",
"numpy.iinfo"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
qq2016/kubeflow_learning
|
[
"c93b792d67c8c52bc91d4ccf5fbaead4e2324331"
] |
[
"github_issue_summarization/pipelines/components/kubeflow-resources/tf-serving-gh/deploy-tf-serve.py"
] |
[
"# Copyright 2018 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# 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 argparse\nimport os\nimport time\nimport logging\nimport subprocess\nimport requests\n\nfrom tensorflow.python.lib.io import file_io #pylint: disable=no-name-in-module\n\n\ndef main():\n parser = argparse.ArgumentParser(description='ML Trainer')\n parser.add_argument(\n '--model_name',\n help='...',\n required=True)\n\n parser.add_argument(\n '--model_path',\n help='...',\n required=True)\n\n parser.add_argument('--cluster', type=str,\n help='GKE cluster set up for kubeflow. If set, zone must be provided. ' +\n 'If not set, assuming this runs in a GKE container and current ' +\n 'cluster is used.')\n parser.add_argument('--zone', type=str, help='zone of the kubeflow cluster.')\n args = parser.parse_args()\n\n KUBEFLOW_NAMESPACE = 'kubeflow'\n\n # Make sure model dir exists before proceeding\n retries = 0\n sleeptime = 5\n while retries < 20:\n try:\n model_dir = os.path.join(args.model_path, file_io.list_directory(args.model_path)[-1])\n print(\"model subdir: %s\" % model_dir)\n break\n except Exception as e: #pylint: disable=broad-except\n print(e)\n print(\"Sleeping %s seconds to sync with GCS...\" % sleeptime)\n time.sleep(sleeptime)\n retries += 1\n sleeptime *= 2\n if retries >= 20:\n print(\"could not get model subdir from %s, exiting\" % args.model_path)\n exit(1)\n\n logging.getLogger().setLevel(logging.INFO)\n args_dict = vars(args)\n if args.cluster and args.zone:\n cluster = args_dict.pop('cluster') #pylint: disable=unused-variable\n zone = args_dict.pop('zone') #pylint: disable=unused-variable\n else:\n # Get cluster name and zone from metadata\n metadata_server = \"http://metadata/computeMetadata/v1/instance/\"\n metadata_flavor = {'Metadata-Flavor' : 'Google'}\n cluster = requests.get(metadata_server + \"attributes/cluster-name\",\n headers=metadata_flavor).text\n zone = requests.get(metadata_server + \"zone\",\n headers=metadata_flavor).text.split('/')[-1]\n\n # logging.info('Getting credentials for GKE cluster %s.' % cluster)\n # subprocess.call(['gcloud', 'container', 'clusters', 'get-credentials', cluster,\n # '--zone', zone])\n\n logging.info('Generating training template.')\n\n template_file = os.path.join(\n os.path.dirname(os.path.realpath(__file__)), 'tf-serve-template.yaml')\n target_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tf-serve.yaml')\n\n with open(template_file, 'r') as f:\n with open(target_file, \"w\") as target:\n data = f.read()\n changed = data.replace('MODEL_NAME', args.model_name)\n changed1 = changed.replace('KUBEFLOW_NAMESPACE', KUBEFLOW_NAMESPACE)\n changed2 = changed1.replace('MODEL_PATH', args.model_path)\n target.write(changed2)\n\n\n logging.info('deploying model serving.')\n subprocess.call(['kubectl', 'create', '-f', '/ml/tf-serve.yaml'])\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"tensorflow.python.lib.io.file_io.list_directory"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"1.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
}
] |
BrookPurdueUniversity/CarND-Capstone
|
[
"9e226ffacee49c545fbbfcecf3a47ab6f66302ef"
] |
[
"ros/src/tl_detector/tl_detector.py"
] |
[
"#!/usr/bin/env python\nimport rospy\nfrom std_msgs.msg import Int32\nfrom geometry_msgs.msg import PoseStamped, Pose\nfrom styx_msgs.msg import TrafficLightArray, TrafficLight\nfrom styx_msgs.msg import Lane\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge\nfrom light_classification.tl_classifier import TLClassifier\nimport tf\nimport cv2\nimport yaml\nfrom scipy.spatial import KDTree\n\nfrom common_tools.helper import Helper\n\nSTATE_COUNT_THRESHOLD = 2\nSIM_MODE = True\n\nclass TLDetector(object):\n def __init__(self):\n rospy.init_node('tl_detector')\n\n config_string = rospy.get_param(\"/traffic_light_config\")\n self.config = yaml.load(config_string)\n self.is_site = self.config[\"is_site\"]\n rospy.loginfo(\"Is Site: {}\".format(self.is_site))\n\n self.pose, self.waypoints, self.camera_image, self.waypoints_2d, \\\n self.waypoints_tree = Helper.get_none_instances(5)\n\n self.lights = []\n\n self.bridge = CvBridge()\n self.light_classifier = TLClassifier(self.is_site)\n self.listener = tf.TransformListener()\n\n self.state = TrafficLight.UNKNOWN\n self.last_state = TrafficLight.UNKNOWN\n self.last_wp = -1\n self.state_count = 0\n self.prev_light_loc = None\n self.has_image = False\n\n sub1 = rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb)\n sub2 = rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb)\n\n '''\n /vehicle/traffic_lights provides you with the location of the traffic light in 3D map space and\n helps you acquire an accurate ground truth data source for the traffic light\n classifier by sending the current color state of all traffic lights in the\n simulator. When testing on the vehicle, the color state will not be available. You'll need to\n rely on the position of the light and the camera image to predict it.\n '''\n sub3 = rospy.Subscriber('/vehicle/traffic_lights', TrafficLightArray, self.traffic_cb)\n sub6 = rospy.Subscriber('/image_color', Image, self.image_cb)\n\n self.upcoming_red_light_pub = rospy.Publisher('/traffic_waypoint', Int32, queue_size=1)\n\n self.loop_rate = 10 # in Hz. \n self.loop()\n\n def loop(self):\n rate = rospy.Rate(self.loop_rate)\n while not rospy.is_shutdown():\n '''\n Publish upcoming red lights at camera frequency.\n Each predicted state has to occur `STATE_COUNT_THRESHOLD` number\n of times till we start using it. Otherwise the previous stable state is\n used.\n '''\n if self.pose and self.waypoints and self.camera_image:\n light_wpt, state = self.process_traffic_lights()\n if self.state != state:\n self.state_count = 0\n self.state = state\n elif self.state_count >= STATE_COUNT_THRESHOLD:\n self.last_state = self.state\n light_wpt = light_wpt if state == TrafficLight.RED else -1\n self.last_wp = light_wpt\n self.upcoming_red_light_pub.publish(Int32(light_wpt))\n else:\n self.upcoming_red_light_pub.publish(Int32(self.last_wp))\n self.state_count += 1\n rate.sleep()\n\n def pose_cb(self, msg):\n self.pose = msg\n\n def waypoints_cb(self, waypoints):\n self.waypoints = waypoints\n if not self.waypoints_2d:\n self.waypoints_2d = [[waypoint.pose.pose.position.x, waypoint.pose.pose.position.y] \\\n for waypoint in waypoints.waypoints]\n self.waypoints_tree = KDTree(self.waypoints_2d)\n\n def traffic_cb(self, msg):\n self.lights = msg.lights\n\n def image_cb(self, msg):\n \"\"\"Identifies red lights in the incoming camera image and publishes the index\n of the waypoint closest to the red light's stop line to /traffic_waypoint\n Args:\n msg (Image): image from car-mounted camera\n \"\"\"\n self.has_image = True\n self.camera_image = msg\n # light_wp, state = self.process_traffic_lights()\n\n def get_closest_waypoint(self, x, y):\n \"\"\"Identifies the closest path waypoint to the given position\n https://en.wikipedia.org/wiki/Closest_pair_of_points_problem\n Args:\n x: x-coordinate of the position to match a waypoint to\n y: y-coordinate of the position to match a waypoint to\n Returns:\n int: index of the closest waypoint in self.waypoints\n \"\"\"\n return self.waypoints_tree.query([x, y], 1)[1]\n\n def get_light_state(self, light):\n \"\"\"Determines the current color of the traffic light\n\n Args:\n light (TrafficLight): light to classify\n\n Returns:\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n\n \"\"\"\n if not self.has_image:\n self.prev_light_loc = None\n return False\n \n cv_image = self.bridge.imgmsg_to_cv2(self.camera_image, \"bgr8\")\n # Get classification\n return self.light_classifier.get_classification(cv_image)\n\n def process_traffic_lights(self):\n \"\"\"Finds closest visible traffic light, if one exists, and determines its\n location and color\n Returns:\n int: index of waypoint closest to the upcoming stop line for a traffic light (-1 if none exists)\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n \"\"\"\n closest_light = None\n line_wpt_index = None # In the simulator, each light comes with a stop-line waypoint index\n\n # List of positions that correspond to the line to stop in front of for a given intersection\n stop_line_positions = self.config['stop_line_positions']\n\n if self.pose and self.waypoints and self.waypoints_tree:\n car_wpt_index = self.get_closest_waypoint(self.pose.pose.position.x, self.pose.pose.position.y)\n diff = len(self.waypoints.waypoints)\n\n for i, light in enumerate(self.lights):\n # Get stop-line waypoint index\n line = stop_line_positions[i]\n tmp_wpt_index = self.get_closest_waypoint(line[0], line[1])\n d = tmp_wpt_index - car_wpt_index\n if 0 <= d < diff:\n diff = d\n closest_light = light\n line_wpt_index = tmp_wpt_index\n\n if closest_light:\n state = self.get_light_state(closest_light)\n return line_wpt_index, state\n\n return -1, TrafficLight.UNKNOWN\n\nif __name__ == '__main__':\n try:\n TLDetector()\n except rospy.ROSInterruptException:\n rospy.logerr('Could not start traffic node.')\n"
] |
[
[
"scipy.spatial.KDTree"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
5-pankajkr/ga-learner-dsmp-repo
|
[
"11d091877169c48516308a1ca3e7a5e7abf649a7"
] |
[
"Human-activity-recognition-with-smartphones/code.py"
] |
[
"# --------------\nimport pandas as pd\nfrom collections import Counter\n\n# Load dataset\ndata = pd.read_csv(path)\nprint(data.isnull().sum())\n\nprint(data.describe())\n\n\n# --------------\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nsns.set_style(style='darkgrid')\n\n# Store the label values \nlabel= data['Activity'].copy()\nchart= sns.countplot(x=label, data=data)\nchart.set_xticklabels(chart.get_xticklabels(), rotation=90)\n\n\n\n# plot the countplot\n\n\n\n# --------------\n# make the copy of dataset\ndata_copy= data.copy()\n\n# Create an empty column \ndata_copy['duration']= pd.Series()\n\n# Calculate the duration\nduration_df= (data_copy.groupby([label[(label=='WALKING_UPSTAIRS')|(label=='WALKING_DOWNSTAIRS')], 'subject'])['duration'].count() * 1.28)\n\nduration_df= pd.DataFrame(duration_df)\nprint(duration_df.head())\n\n# Sort the values of duration\nplot_data= duration_df.reset_index().sort_values('duration', ascending= False)\nplot_data['Activity']= plot_data['Activity'].map({'WALKING_UPSTAIRS': 'Upstairs', 'WALKING_DOWNSTAIRS': 'Downstairs'})\n\nplt.figure(figsize=(14,4))\nsns.barplot(data=plot_data, x='subject', y='duration', hue='Activity')\nplt.show()\n\n\n\n# --------------\n#exclude the Activity column and the subject column\nfeature_cols= data.columns[:-2]\n\n#Calculate the correlation values\ncorrelated_values= data[feature_cols].corr()\n\n#stack the data and convert to a dataframe\ncorrelated_values= correlated_values.stack().to_frame().reset_index()\ncorrelated_values = correlated_values.rename(columns={'level_0':'Feature_1', 'level_1':'Feature_2', 0:'Correlation_score'})\nprint(correlated_values.head())\n\n#create an abs_correlation column\ncorrelated_values['abs_correlation']= correlated_values['Correlation_score'].abs()\n\ns_corr_list= correlated_values.sort_values('abs_correlation', ascending= False)\nprint(s_corr_list.head())\n\n#Picking most correlated features without having self correlated pairs\ntop_corr_fields= s_corr_list[s_corr_list['abs_correlation']>0.8]\n# print(top_corr_feilds.head())\n\ntop_corr_fields= top_corr_fields[top_corr_fields['Feature_1']!=top_corr_fields['Feature_2']].reset_index(drop= True)\nprint(top_corr_fields.head())\n\n\n\n\n# --------------\n# importing neccessary libraries\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import precision_recall_fscore_support as error_metric\nfrom sklearn.metrics import confusion_matrix, accuracy_score\n\n# Encoding the target variable\nle = LabelEncoder()\ndata['Activity'] = le.fit_transform(data.Activity)\nX = data.iloc[:,:-1] \ny = data.iloc[:,-1]\n\n# split the dataset into train and test\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=40)\n\n# Baseline model \nclassifier = SVC()\nclf = classifier.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\nprecision, recall, f_score, _ = error_metric(y_test, y_pred, average = 'weighted')\nmodel1_score = accuracy_score(y_test, y_pred)\nprint(model1_score)\nprint(precision, recall, f_score)\n\n\n\n# --------------\n# importing libraries\nfrom sklearn.svm import LinearSVC\nfrom sklearn.feature_selection import SelectFromModel\n\n# Feature selection using Linear SVC\nlsvc= LinearSVC(C=0.01, penalty= 'l1', dual= False, random_state= 42)\nmodel_2= SelectFromModel(lsvc, prefit= True)\nprint(X_train.shape)\n\nlsvc.fit(X_train, y_train)\nnew_train_features= model_2.transform(X_train)\nnew_test_features= model_2.transform(X_test)\nprint(new_train_features.shape)\n\n# model building on reduced set of features\nclassifier_2= SVC()\nclf_2= classifier_2.fit(new_train_features, y_train)\ny_pred_new= clf_2.predict(new_test_features)\n\nmodel2_score= accuracy_score(y_test, y_pred_new)\nprint(model2_score)\nprecision, recall, f_score, support= error_metric(y_test, y_pred_new, average= 'weighted')\nprint(precision, recall, f_score, support)\n\n\n\n\n# --------------\n# Importing Libraries\nfrom sklearn.model_selection import GridSearchCV\n\n# Set the hyperparmeters\nparameters= {'kernel': ['linear', 'rbf'], 'C': [100, 20, 1, 0.1], }\nselector= GridSearchCV(SVC(), parameters, scoring= 'accuracy')\n\n# Usage of grid search to select the best hyperparmeters\nselector.fit(new_train_features, y_train)\nprint('Best HyperParam: ', selector.best_params_)\n\nmean= selector.best_score_\nmeans= selector.cv_results_['mean_test_score']\nstds= selector.cv_results_['std_test_score']\nstd= selector.cv_results_['std_test_score'][selector.best_index_]\n\nfor m, s, p in zip(means, stds, selector.cv_results_['params']):\n print('%0.3f (+/-%0.03f) for %r' % (m, s * 2, p))\n print('-'*20)\n\nprint(mean, std)\n# Model building after Hyperparameter tuning\nbest_ker= selector.best_params_['kernel']\nbest_c= selector.best_params_['C']\nprint('-'*30)\nprint(best_c, best_ker)\n\nclassifier_3= SVC(kernel=best_ker , C=best_c)\nclf_3= classifier_3.fit(new_train_features, y_train)\ny_pred_final= clf_3.predict(new_test_features)\n\nmodel3_score= accuracy_score(y_test, y_pred_final)\nprint(model3_score)\nprecision, recall, f_score, support= error_metric(y_test, y_pred_final, average= 'weighted')\nprint(precision, recall, f_score, support)\n\n\n\n"
] |
[
[
"pandas.read_csv",
"pandas.Series",
"sklearn.metrics.accuracy_score",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame",
"sklearn.preprocessing.LabelEncoder",
"sklearn.metrics.precision_recall_fscore_support",
"sklearn.svm.SVC",
"sklearn.svm.LinearSVC",
"sklearn.feature_selection.SelectFromModel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
nimu77/lambdata-nirmal
|
[
"bc69505aada975c8056fefa06b510d276ce9fd50"
] |
[
"my_lambdata/my_mod_one.py"
] |
[
"import pandas as pd\n\n\ndef checks_null(a):\n '''checks to see if dataframe has null values'''\n a = pd.DataFrame(a)\n\n if a.isnull().values.any():\n print(f'DataFrame has some null values, please replace it or drop it.')\n else:\n print(f'DataFrame is good to go. No null values.')\n\n\nif __name__ == '__main__':\n y = pd.DataFrame(value)\n print(checks(y))\n"
] |
[
[
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
link-kut/deeplink_public
|
[
"688c379bfeb63156e865d78d0428f97d7d203cc1",
"688c379bfeb63156e865d78d0428f97d7d203cc1",
"688c379bfeb63156e865d78d0428f97d7d203cc1"
] |
[
"1.DeepLearning/01.Multiple_Neurons/or_gate_three_neurons_target_learning.py",
"1.DeepLearning/deeplink/optimizers.py",
"2.ReinforcementLearning/FrozenLake/FrozenLake-1.py"
] |
[
"from __future__ import print_function\nimport numpy as np\nimport random\nimport math\n\nclass Neuron1:\n def __init__(self):\n self.w1 = np.array([random.random(), random.random()]) # weight of one input\n self.b1 = random.random() # bias\n print(\"Neuron1 - Initial w1: {0}, b1: {1}\".format(self.w1, self.b1))\n\n def u1(self, input):\n return np.dot(self.w1, input) + self.b1\n\n def f(self, u1):\n return max(0.0, u1)\n\n def z1(self, input):\n u1 = self.u1(input)\n return self.f(u1)\n\nclass Neuron2:\n def __init__(self):\n self.w2 = np.array([random.random(), random.random()]) # weight of one input\n self.b2 = random.random() # bias\n print(\"Neuron2 - Initial w2: {0}, b2: {1}\".format(self.w2, self.b2))\n\n def u2(self, input):\n return np.dot(self.w2, input) + self.b2\n\n def f(self, u2):\n return max(0.0, u2)\n\n def z2(self, input):\n u2 = self.u2(input)\n return self.f(u2)\n\nclass Neuron3:\n def __init__(self, n1, n2):\n self.w3 = np.array([random.random(), random.random()]) # weight of one input\n self.b3 = random.random() # bias\n self.n1 = n1\n self.n2 = n2\n print(\"Neuron2 - Initial w3: {0}, b3: {1}\".format(self.w3, self.b3))\n\n def u3(self, input):\n z1 = self.n1.z1(input)\n z2 = self.n2.z2(input)\n z = np.array([z1, z2])\n return np.dot(self.w3, z) + self.b3\n\n def f(self, u3):\n return max(0.0, u3)\n\n def z3(self, input):\n u3 = self.u3(input)\n return self.f(u3)\n\n def squared_error(self, input, z_target):\n return 1.0 / 2.0 * math.pow(self.z3(input) - z_target, 2)\n\n def d_E_over_d_w3(self, input, z_target):\n u3 = self.u3(input)\n if u3 >= 0.0:\n z3 = self.z3(input)\n z1 = self.n1.z1(input)\n z2 = self.n2.z2(input)\n z = np.array([z1, z2])\n return (z3 - z_target) * z\n else:\n return 0.0\n\n def d_E_over_d_b3(self, input, z_target):\n u3 = self.u3(input)\n if u3 >= 0.0:\n z3 = self.z3(input)\n return z3 - z_target\n else:\n return 0.0\n\n def d_E_over_d_w2(self, input, z_target):\n u3 = self.u3(input)\n u2 = self.n2.u2(input)\n if u3 >= 0.0 and u2 >= 0.0:\n return (self.f(u3) - z_target) * self.w3[1] * input\n else:\n return 0.0\n\n def d_E_over_d_b2(self, input, z_target):\n u3 = self.u3(input)\n u2 = self.n2.u2(input)\n if u3 >= 0.0 and u2 >= 0.0:\n return (self.f(u3) - z_target) * self.w3[1]\n else:\n return 0.0\n\n def d_E_over_d_w1(self, input, z_target):\n u3 = self.u3(input)\n u1 = self.n1.u1(input)\n if u3 >= 0.0 and u1 >= 0.0:\n return (self.f(u3) - z_target) * self.w3[0] * input\n else:\n return 0.0\n\n def d_E_over_d_b1(self, input, z_target):\n u3 = self.u3(input)\n u1 = self.n1.u1(input)\n if u3 >= 0.0 and u1 >= 0.0:\n return (self.f(u3) - z_target) * self.w3[0]\n else:\n return 0.0\n\n def learning(self, alpha, maxEpoch, data):\n for i in xrange(maxEpoch):\n for idx in xrange(data.numTrainData):\n input = data.training_input_value[idx]\n z_target = data.training_z_target[idx]\n\n self.n1.w1 = self.n1.w1 - alpha * self.d_E_over_d_w1(input, z_target)\n self.n1.b1 = self.n1.b1 - alpha * self.d_E_over_d_b1(input, z_target)\n self.n2.w2 = self.n2.w2 - alpha * self.d_E_over_d_w2(input, z_target)\n self.n2.b2 = self.n2.b2 - alpha * self.d_E_over_d_b2(input, z_target)\n self.w3 = self.w3 - alpha * self.d_E_over_d_w3(input, z_target)\n self.b3 = self.b3 - alpha * self.d_E_over_d_b3(input, z_target)\n\n sum = 0.0\n for idx in xrange(data.numTrainData):\n sum = sum + self.squared_error(data.training_input_value[idx], data.training_z_target[idx])\n print(\"Epoch {0}: Error: {1}, w1: {2}, b1: {3}, w2: {4}, b2: {5}, w3: {6}, b3: {7}\".format(i, sum / data.numTrainData, self.n1.w1, self.n1.b1, self.n2.w2, self.n2.b2, self.w3, self.b3))\n\nclass Data:\n def __init__(self):\n self.training_input_value = np.array([(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)])\n self.training_z_target = np.array([0.0, 1.0, 1.0, 1.0])\n self.numTrainData = len(self.training_input_value)\n\nif __name__ == '__main__':\n n1 = Neuron1()\n n2 = Neuron2()\n n3 = Neuron3(n1, n2)\n d = Data()\n for idx in xrange(d.numTrainData):\n input = d.training_input_value[idx]\n z3 = n3.z3(input)\n z_target = d.training_z_target[idx]\n error = n3.squared_error(input, z_target)\n print(\"x: {0}, z3: {1}, z_target: {2}, error: {3}\".format(input, z3, z_target, error))\n\n n3.learning(0.05, 1000, d)\n\n for idx in xrange(d.numTrainData):\n input = d.training_input_value[idx]\n z3 = n3.z3(input)\n z_target = d.training_z_target[idx]\n error = n3.squared_error(input, z_target)\n print(\"x: {0}, z3: {1}, z_target: {2}, error: {3}\".format(input, z3, z_target, error))",
"# coding: utf-8\nimport numpy as np\n\nclass SGD:\n def __init__(self, lr=0.01):\n self.lr = lr\n \n def update(self, params, grads):\n for key in params.keys():\n params[key] -= self.lr * grads[key] \n\n\nclass Momentum:\n def __init__(self, lr=0.01, momentum=0.9):\n self.lr = lr\n self.momentum = momentum\n self.v = None\n \n def update(self, params, grads):\n if self.v is None:\n self.v = {}\n for key, val in params.items(): \n self.v[key] = np.zeros_like(val)\n \n for key in params.keys():\n self.v[key] = self.momentum*self.v[key] - self.lr*grads[key] \n params[key] += self.v[key]\n\n\nclass Nesterov:\n def __init__(self, lr=0.01, momentum=0.9):\n self.lr = lr\n self.momentum = momentum\n self.v = None\n \n def update(self, params, grads):\n if self.v is None:\n self.v = {}\n for key, val in params.items():\n self.v[key] = np.zeros_like(val)\n \n for key in params.keys():\n self.v[key] *= self.momentum\n self.v[key] -= self.lr * grads[key]\n params[key] += self.momentum * self.momentum * self.v[key]\n params[key] -= (1 + self.momentum) * self.lr * grads[key]\n\n\nclass AdaGrad:\n def __init__(self, lr=0.01):\n self.lr = lr\n self.h = None\n \n def update(self, params, grads):\n if self.h is None:\n self.h = {}\n for key, val in params.items():\n self.h[key] = np.zeros_like(val)\n \n for key in params.keys():\n self.h[key] += grads[key] * grads[key]\n params[key] -= self.lr * grads[key] / (np.sqrt(self.h[key]) + 1e-7)\n\n\nclass RMSprop:\n def __init__(self, lr=0.01, decay_rate = 0.99):\n self.lr = lr\n self.decay_rate = decay_rate\n self.h = None\n \n def update(self, params, grads):\n if self.h is None:\n self.h = {}\n for key, val in params.items():\n self.h[key] = np.zeros_like(val)\n \n for key in params.keys():\n self.h[key] *= self.decay_rate\n self.h[key] += (1 - self.decay_rate) * grads[key] * grads[key]\n params[key] -= self.lr * grads[key] / (np.sqrt(self.h[key]) + 1e-7)\n\n\nclass Adam:\n def __init__(self, lr=0.001, beta1=0.9, beta2=0.999):\n self.lr = lr\n self.beta1 = beta1\n self.beta2 = beta2\n self.iter = 0\n self.m = None\n self.v = None\n \n def update(self, params, grads):\n if self.m is None:\n self.m, self.v = {}, {}\n for key, val in params.items():\n self.m[key] = np.zeros_like(val)\n self.v[key] = np.zeros_like(val)\n \n self.iter += 1\n lr_t = self.lr * np.sqrt(1.0 - self.beta2**self.iter) / (1.0 - self.beta1**self.iter) \n \n for key in params.keys():\n self.m[key] += (1 - self.beta1) * (grads[key] - self.m[key])\n self.v[key] += (1 - self.beta2) * (grads[key]**2 - self.v[key])\n params[key] -= lr_t * self.m[key] / (np.sqrt(self.v[key]) + 1e-7)\n",
"# Dummy Q-Table learning algorithm\nfrom __future__ import print_function\n\nimport gym\nfrom gym.envs.registration import register\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\n\nregister(\n id = 'FrozenLake-v3',\n entry_point = 'gym.envs.toy_text:FrozenLakeEnv',\n kwargs={\n 'map_name': '4x4',\n 'is_slippery': False\n }\n)\n\ndef rargmax(vector):\n # vector: [ 0. 1. 1. 0.]\n # Return the maximum number of an array element.\n m = np.amax(vector) # m = 1.\n # Return the list of indices of the elements that are non-zero and the given condition is True\n indices = np.nonzero(vector == m)[0] # indices = [1, 2]\n return random.choice(indices)\n\nenv = gym.make(\"FrozenLake-v3\")\nenv.render()\n\nprint(\"env.observation_space.n:\", env.observation_space.n)\nprint(\"env.action_space.n:\", env.action_space.n)\n\nQ = np.zeros([env.observation_space.n, env.action_space.n])\n\nmax_episodes = 2000\n\n# list to contain total rewards and steps per episode\nrList = []\n\nfor i in range(max_episodes):\n # Reset environment and get first new observation\n state = env.reset()\n rAll = 0\n done = False\n\n # The Q-Table learning algorithm\n while not done:\n action = rargmax(Q[state, :])\n\n # Get new state and reward from environment\n new_state, reward, done, info = env.step(action)\n\n # Update Q-Table with new knowledge using learning rate\n Q[state, action] = reward + np.max(Q[new_state, :])\n\n rAll += reward\n state = new_state\n\n rList.append(rAll)\n\nprint(\"Success rate: \" + str(sum(rList)/max_episodes))\nprint(\"Final Q-Table Values\")\nprint(\"LEFT DOWN RIGHT UP\")\nfor i in range(16):\n for j in range(4):\n print(\"%6.4f\" % Q[i][j], end=\", \")\n print()\nplt.plot(rList)\nplt.ylim(-0.5, 1.5)\nplt.show()"
] |
[
[
"numpy.dot",
"numpy.array"
],
[
"numpy.zeros_like",
"numpy.sqrt"
],
[
"numpy.amax",
"numpy.nonzero",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.plot",
"numpy.max",
"matplotlib.pyplot.show",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
3DAlgoLab/vispy
|
[
"91972307cf336674aad58198fb26b9e46f8f9ca1",
"91972307cf336674aad58198fb26b9e46f8f9ca1",
"91972307cf336674aad58198fb26b9e46f8f9ca1",
"91972307cf336674aad58198fb26b9e46f8f9ca1",
"91972307cf336674aad58198fb26b9e46f8f9ca1"
] |
[
"vispy/visuals/histogram.py",
"vispy/visuals/tests/test_image.py",
"vispy/app/tests/test_ipython.py",
"examples/demo/gloo/camera.py",
"examples/demo/gloo/galaxy.py"
] |
[
"# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n# -----------------------------------------------------------------------------\n\nimport numpy as np\n\nfrom .mesh import MeshVisual\n\n\nclass HistogramVisual(MeshVisual):\n \"\"\"Visual that calculates and displays a histogram of data\n\n Parameters\n ----------\n data : array-like\n Data to histogram. Currently only 1D data is supported.\n bins : int | array-like\n Number of bins, or bin edges.\n color : instance of Color\n Color of the histogram.\n orientation : {'h', 'v'}\n Orientation of the histogram.\n \"\"\"\n\n def __init__(self, data, bins=10, color='w', orientation='h'):\n # 4-5\n # | |\n # 1-2/7-8\n # |/| | |\n # 0-3-6-9\n data = np.asarray(data)\n if data.ndim != 1:\n raise ValueError('Only 1D data currently supported')\n if not isinstance(orientation, str) or \\\n orientation not in ('h', 'v'):\n raise ValueError('orientation must be \"h\" or \"v\", not %s'\n % (orientation,))\n X, Y = (0, 1) if orientation == 'h' else (1, 0)\n\n # do the histogramming\n data, bin_edges = np.histogram(data, bins)\n # construct our vertices\n rr = np.zeros((3 * len(bin_edges) - 2, 3), np.float32)\n rr[:, X] = np.repeat(bin_edges, 3)[1:-1]\n rr[1::3, Y] = data\n rr[2::3, Y] = data\n bin_edges.astype(np.float32)\n # and now our tris\n tris = np.zeros((2 * len(bin_edges) - 2, 3), np.uint32)\n offsets = 3 * np.arange(len(bin_edges) - 1,\n dtype=np.uint32)[:, np.newaxis]\n tri_1 = np.array([0, 2, 1])\n tri_2 = np.array([2, 0, 3])\n tris[::2] = tri_1 + offsets\n tris[1::2] = tri_2 + offsets\n MeshVisual.__init__(self, rr, tris, color=color)\n",
"# -*- coding: utf-8 -*-\nfrom unittest import mock\n\nfrom vispy.scene.visuals import Image\nfrom vispy.testing import (requires_application, TestingCanvas,\n run_tests_if_main)\nfrom vispy.testing.image_tester import assert_image_approved, downsample\n\nimport numpy as np\nimport pytest\n\n\n@requires_application()\[email protected]('is_3d', [True, False])\ndef test_image(is_3d):\n \"\"\"Test image visual\"\"\"\n size = (100, 50)\n with TestingCanvas(size=size, bgcolor='w') as c:\n image = Image(cmap='grays', clim=[0, 1], parent=c.scene)\n shape = (size[1]-10, size[0]-10) + ((3,) if is_3d else ())\n np.random.seed(379823)\n data = np.random.rand(*shape)\n image.set_data(data)\n assert_image_approved(c.render(), \"visuals/image%s.png\" %\n (\"_rgb\" if is_3d else \"_mono\"))\n\n\ndef _make_test_data(shape, input_dtype):\n data = np.random.random_sample(shape)\n if data.ndim == 3 and data.shape[-1] == 4:\n # RGBA - make alpha fully opaque\n data[..., -1] = 1.0\n max_val = _max_for_dtype(input_dtype)\n if max_val != 1:\n data *= max_val\n data = data.astype(input_dtype)\n return data\n\n\ndef _compare_render(orig_data, rendered_data, previous_render=None, atol=1):\n predicted = _make_rgba(orig_data)\n np.testing.assert_allclose(rendered_data.astype(float), predicted.astype(float), atol=atol)\n if previous_render is not None:\n # assert not allclose\n pytest.raises(AssertionError, np.testing.assert_allclose,\n rendered_data, previous_render, atol=10)\n\n\ndef _set_image_data(image, data, should_fail):\n if should_fail:\n pytest.raises(ValueError, image.set_data, data)\n return\n image.set_data(data)\n\n\ndef _max_for_dtype(input_dtype):\n if np.issubdtype(input_dtype, np.integer):\n max_val = np.iinfo(input_dtype).max\n else:\n max_val = 1.0\n return max_val\n\n\ndef _get_orig_and_new_clims(input_dtype):\n new_clim = (0.3, 0.8)\n max_val = _max_for_dtype(input_dtype)\n if np.issubdtype(input_dtype, np.integer):\n new_clim = (int(new_clim[0] * max_val), int(new_clim[1] * max_val))\n return (0, max_val), new_clim\n\n\n@requires_application()\[email protected]('data_on_init', [False, True])\[email protected]('clim_on_init', [False, True])\[email protected]('num_channels', [0, 1, 3, 4])\[email protected]('texture_format', [None, '__dtype__', 'auto'])\[email protected]('input_dtype', [np.uint8, np.uint16, np.float32, np.float64])\ndef test_image_clims_and_gamma(input_dtype, texture_format, num_channels,\n clim_on_init, data_on_init):\n \"\"\"Test image visual with clims and gamma on shader.\"\"\"\n size = (40, 40)\n if texture_format == '__dtype__':\n texture_format = input_dtype\n shape = size + (num_channels,) if num_channels > 0 else size\n np.random.seed(0)\n data = _make_test_data(shape, input_dtype)\n orig_clim, new_clim = _get_orig_and_new_clims(input_dtype)\n # 16-bit integers and above seem to have precision loss when scaled on the CPU\n is_16int_cpu_scaled = (np.dtype(input_dtype).itemsize >= 2 and\n np.issubdtype(input_dtype, np.integer) and\n texture_format is None)\n clim_atol = 2 if is_16int_cpu_scaled else 1\n gamma_atol = 3 if is_16int_cpu_scaled else 2\n\n kwargs = {}\n if clim_on_init:\n kwargs['clim'] = orig_clim\n if data_on_init:\n kwargs['data'] = data\n # default is RGBA, anything except auto requires reformat\n set_data_fails = (num_channels != 4 and\n texture_format is not None and\n texture_format != 'auto')\n\n with TestingCanvas(size=size[::-1], bgcolor=\"w\") as c:\n image = Image(cmap='grays', texture_format=texture_format,\n parent=c.scene, **kwargs)\n if not data_on_init:\n _set_image_data(image, data, set_data_fails)\n if set_data_fails:\n return\n rendered = c.render()\n _dtype = rendered.dtype\n shape_ratio = rendered.shape[0] // data.shape[0]\n rendered1 = downsample(rendered, shape_ratio, axis=(0, 1)).astype(_dtype)\n _compare_render(data, rendered1)\n\n # adjust color limits\n image.clim = new_clim\n rendered2 = downsample(c.render(), shape_ratio, axis=(0, 1)).astype(_dtype)\n scaled_data = (np.clip(data, new_clim[0], new_clim[1]) - new_clim[0]) / (new_clim[1] - new_clim[0])\n _compare_render(scaled_data, rendered2, rendered1, atol=clim_atol)\n\n # adjust gamma\n image.gamma = 2\n rendered3 = downsample(c.render(), shape_ratio, axis=(0, 1)).astype(_dtype)\n _compare_render(scaled_data ** 2, rendered3, rendered2, atol=gamma_atol)\n\n\n@requires_application()\ndef test_image_vertex_updates():\n \"\"\"Test image visual coordinates are only built when needed.\"\"\"\n size = (40, 40)\n with TestingCanvas(size=size, bgcolor=\"w\") as c:\n shape = size + (3,)\n np.random.seed(0)\n image = Image(cmap='grays', clim=[0, 1], parent=c.scene)\n with mock.patch.object(\n image, '_build_vertex_data',\n wraps=image._build_vertex_data) as build_vertex_mock:\n data = np.random.rand(*shape)\n image.set_data(data)\n c.render()\n build_vertex_mock.assert_called_once()\n build_vertex_mock.reset_mock() # reset the count to 0\n\n # rendering again shouldn't cause vertex coordinates to be built\n c.render()\n build_vertex_mock.assert_not_called()\n\n # changing to data of the same shape shouldn't cause it\n data = np.zeros_like(data)\n image.set_data(data)\n c.render()\n build_vertex_mock.assert_not_called()\n\n # changing to another shape should\n data = data[:-5, :-5]\n image.set_data(data)\n c.render()\n build_vertex_mock.assert_called_once()\n\n\ndef _make_rgba(data_in):\n max_val = _max_for_dtype(data_in.dtype)\n if data_in.ndim == 3 and data_in.shape[-1] == 1:\n data_in = data_in.squeeze()\n\n if data_in.ndim == 2:\n out = np.stack([data_in] * 4, axis=2)\n out[:, :, 3] = max_val\n elif data_in.shape[-1] == 3:\n out = np.concatenate((data_in, np.ones((*data_in.shape[:2], 1)) * max_val), axis=2)\n else:\n out = data_in\n return np.round((out.astype(np.float) * 255 / max_val)).astype(np.uint8)\n\n\nrun_tests_if_main()\n",
"# -*- coding: utf-8 -*-\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n\"\"\"Tests for Vispy's IPython bindings\"\"\"\n\n# from vispy import IPython\nfrom numpy.testing import assert_equal, assert_raises\nfrom vispy.testing import requires_ipython\n\n\n@requires_ipython(2.0)\ndef test_webgl_loading():\n \"\"\"Test if the vispy.ipython extension loads the webGL backend\n on IPython 3.0 and greater.\n\n Test if it fails to load the webGL backend for IPython versions\n less that 3.0\n \"\"\"\n import IPython\n from distutils.version import LooseVersion\n from IPython.testing.globalipapp import get_ipython\n\n ipy = get_ipython()\n ipy.run_cell(\"from vispy import app\")\n\n if LooseVersion(IPython.__version__) >= LooseVersion(\"3.0.0\"):\n ipy.run_cell(\"%load_ext vispy.ipython\")\n ipy.run_cell(\"backend_name = app.use_app().backend_name\")\n # make sure that the webgl backend got loaded\n assert_equal(ipy.user_ns[\"backend_name\"], \"ipynb_webgl\")\n else:\n ipy.run_cell(\"%load_ext vispy.ipython\")\n ipy.run_cell(\"backend_name = app.use_app().backend_name\")\n\n # the above call should have failed, and thus the key\n # backend_name should not exist in the namespace\n\n def invalid_backend_access(ipy):\n ipy.user_ns[\"backend_name\"]\n\n assert_raises(KeyError, invalid_backend_access, ipy)\n",
"# -*- coding: utf-8 -*-\n# vispy: testskip\n# -----------------------------------------------------------------------------\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n# -----------------------------------------------------------------------------\n\"\"\"Display a live webcam feed. Require OpenCV (Python 2 only).\n\"\"\"\n\ntry:\n import cv2\nexcept Exception:\n raise ImportError(\"You need OpenCV for this example.\")\n\nimport numpy as np\nfrom vispy import app\nfrom vispy import gloo\n\nvertex = \"\"\"\n attribute vec2 position;\n attribute vec2 texcoord;\n varying vec2 v_texcoord;\n void main()\n {\n gl_Position = vec4(position, 0.0, 1.0);\n v_texcoord = texcoord;\n }\n\"\"\"\n\nfragment = \"\"\"\n uniform sampler2D texture;\n varying vec2 v_texcoord;\n void main()\n {\n gl_FragColor = texture2D(texture, v_texcoord);\n\n // HACK: the image is in BGR instead of RGB.\n float temp = gl_FragColor.r;\n gl_FragColor.r = gl_FragColor.b;\n gl_FragColor.b = temp;\n }\n\"\"\"\n\n\nclass Canvas(app.Canvas):\n def __init__(self):\n app.Canvas.__init__(self, size=(640, 480), keys='interactive')\n self.program = gloo.Program(vertex, fragment, count=4)\n self.program['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]\n self.program['texcoord'] = [(1, 1), (1, 0), (0, 1), (0, 0)]\n self.program['texture'] = np.zeros((480, 640, 3)).astype(np.uint8)\n\n width, height = self.physical_size\n gloo.set_viewport(0, 0, width, height)\n\n self.cap = cv2.VideoCapture(0)\n if not self.cap.isOpened():\n raise Exception(\"There's no available camera.\")\n self._timer = app.Timer('auto', connect=self.on_timer, start=True)\n\n self.show()\n\n def on_resize(self, event):\n width, height = event.physical_size\n gloo.set_viewport(0, 0, width, height)\n\n def on_draw(self, event):\n gloo.clear('black')\n _, im = self.cap.read()\n self.program['texture'][...] = im\n self.program.draw('triangle_strip')\n\n def on_timer(self, event):\n self.update()\n\nc = Canvas()\napp.run()\nc.cap.release()\n",
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# vispy: gallery 30\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n\n\"\"\"\nJust a very fake galaxy.\nAstronomers and cosmologists will kill me !\n\"\"\"\n\nimport numpy as np\n\nfrom vispy import gloo\nfrom vispy import app\nfrom vispy.util.transforms import perspective, translate, rotate\n\n# Manual galaxy creation\n# (did you really expect a simulation in less than 250 python lines ?)\n\n\ndef make_arm(n, angle):\n R = np.linspace(10, 450 + 50 * np.random.uniform(.5, 1.), n)\n R += 40 * np.random.normal(0, 2., n) * np.linspace(1, .1, n)\n T = angle + np.linspace(0, 2.5 * np.pi, n) + \\\n np.pi / 6 * np.random.normal(0, .5, n)\n S = 8 + 2 * np.abs(np.random.normal(0, 1, n))\n S *= np.linspace(1, .85, n)\n P = np.zeros((n, 3), dtype=np.float32)\n X, Y, Z = P[:, 0], P[:, 1], P[:, 2]\n X[...] = R * np.cos(T)\n Y[...] = R * np.sin(T) * 1.1\n D = np.sqrt(X * X + Y * Y)\n Z[...] = 8 * np.random.normal(0, 2 - D / 512., n)\n X += (D * np.random.uniform(0, 1, n) > 250) * \\\n (.05 * D * np.random.uniform(-1, 1, n))\n Y += (D * np.random.uniform(0, 1, n) > 250) * \\\n (.05 * D * np.random.uniform(-1, 1, n))\n Z += (D * np.random.uniform(0, 1, n) > 250) * \\\n (.05 * D * np.random.uniform(-1, 1, n))\n D = (D - D.min()) / (D.max() - D.min())\n\n return P / 256, S / 2, D\np = 50000\nn = 3 * p\n\n# Very simple colormap\ncmap = np.array([[255, 124, 0], [255, 163, 76],\n [255, 192, 130], [255, 214, 173],\n [255, 232, 212], [246, 238, 237],\n [237, 240, 253], [217, 228, 255],\n [202, 219, 255], [191, 212, 255],\n [182, 206, 255], [174, 202, 255],\n [168, 198, 255], [162, 195, 255],\n [158, 192, 255], [155, 189, 255],\n [151, 187, 255], [148, 185, 255],\n [145, 183, 255], [143, 182, 255],\n [141, 181, 255], [140, 179, 255],\n [139, 179, 255],\n [137, 177, 255]], dtype=np.uint8).reshape(1, 24, 3)\n\n\nVERT_SHADER = \"\"\"\n#version 120\n// Uniforms\n// ------------------------------------\nuniform mat4 u_model;\nuniform mat4 u_view;\nuniform mat4 u_projection;\nuniform float u_size;\n\n\n// Attributes\n// ------------------------------------\nattribute vec3 a_position;\nattribute float a_size;\nattribute float a_dist;\n\n// Varyings\n// ------------------------------------\nvarying float v_size;\nvarying float v_dist;\n\nvoid main (void) {\n v_size = a_size*u_size*.75;\n v_dist = a_dist;\n gl_Position = u_projection * u_view * u_model * vec4(a_position,1.0);\n gl_PointSize = v_size;\n}\n\"\"\"\n\nFRAG_SHADER = \"\"\"\n#version 120\n// Uniforms\n// ------------------------------------\nuniform sampler2D u_colormap;\n\n// Varyings\n// ------------------------------------\nvarying float v_size;\nvarying float v_dist;\n\n// Main\n// ------------------------------------\nvoid main()\n{\n float a = 2*(length(gl_PointCoord.xy - vec2(0.5,0.5)) / sqrt(2.0));\n vec3 color = texture2D(u_colormap, vec2(v_dist,.5)).rgb;\n gl_FragColor = vec4(color,(1-a)*.25);\n}\n\"\"\"\n\n\nclass Canvas(app.Canvas):\n\n def __init__(self):\n app.Canvas.__init__(self, keys='interactive', size=(800, 600))\n ps = self.pixel_scale\n\n self.title = \"A very fake galaxy [mouse scroll to zoom]\"\n\n data = np.zeros(n, [('a_position', np.float32, 3),\n ('a_size', np.float32),\n ('a_dist', np.float32)])\n\n for i in range(3):\n P, S, D = make_arm(p, i * 2 * np.pi / 3)\n data['a_dist'][(i + 0) * p:(i + 1) * p] = D\n data['a_position'][(i + 0) * p:(i + 1) * p] = P\n data['a_size'][(i + 0) * p:(i + 1) * p] = S*ps\n\n self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)\n self.model = np.eye(4, dtype=np.float32)\n self.projection = np.eye(4, dtype=np.float32)\n self.theta, self.phi = 0, 0\n\n self.translate = 5\n self.view = translate((0, 0, -self.translate))\n\n self.program.bind(gloo.VertexBuffer(data))\n self.program['u_colormap'] = gloo.Texture2D(cmap)\n self.program['u_size'] = 5. / self.translate\n self.program['u_model'] = self.model\n self.program['u_view'] = self.view\n\n self.apply_zoom()\n\n gloo.set_state(depth_test=False, blend=True,\n blend_func=('src_alpha', 'one'), clear_color='black')\n\n # Start the timer upon initialization.\n self.timer = app.Timer('auto', connect=self.on_timer)\n self.timer.start()\n\n self.show()\n\n def on_key_press(self, event):\n if event.text == ' ':\n if self.timer.running:\n self.timer.stop()\n else:\n self.timer.start()\n\n def on_timer(self, event):\n self.theta += .11\n self.phi += .13\n self.model = np.dot(rotate(self.theta, (0, 0, 1)),\n rotate(self.phi, (0, 1, 0)))\n self.program['u_model'] = self.model\n self.update()\n\n def on_resize(self, event):\n self.apply_zoom()\n\n def on_mouse_wheel(self, event):\n self.translate -= event.delta[1]\n self.translate = max(2, self.translate)\n self.view = translate((0, 0, -self.translate))\n self.program['u_view'] = self.view\n self.program['u_size'] = 5 / self.translate\n self.update()\n\n def on_draw(self, event):\n gloo.clear()\n self.program.draw('points')\n\n def apply_zoom(self):\n gloo.set_viewport(0, 0, self.physical_size[0], self.physical_size[1])\n self.projection = perspective(45.0, self.size[0] /\n float(self.size[1]), 1.0, 1000.0)\n self.program['u_projection'] = self.projection\n\nif __name__ == '__main__':\n c = Canvas()\n app.run()\n"
] |
[
[
"numpy.asarray",
"numpy.repeat",
"numpy.array",
"numpy.histogram"
],
[
"numpy.random.seed",
"numpy.clip",
"numpy.issubdtype",
"numpy.random.random_sample",
"numpy.stack",
"numpy.dtype",
"numpy.ones",
"numpy.zeros_like",
"numpy.random.rand",
"numpy.iinfo"
],
[
"numpy.testing.assert_equal",
"numpy.testing.assert_raises"
],
[
"numpy.zeros"
],
[
"numpy.sqrt",
"numpy.linspace",
"numpy.eye",
"numpy.cos",
"numpy.sin",
"numpy.random.normal",
"numpy.random.uniform",
"numpy.array",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
TrainingByPackt/Beginning-Python-AI
|
[
"b1e68d892e65b1f7b347330ef2a90a1b546bdd25",
"b1e68d892e65b1f7b347330ef2a90a1b546bdd25",
"b1e68d892e65b1f7b347330ef2a90a1b546bdd25",
"b1e68d892e65b1f7b347330ef2a90a1b546bdd25"
] |
[
"Lesson04/Activity 08 Increasing the Accuracy of Credit Scoring/credit_scoring.py",
"Lesson03/polynomial_prediction.py",
"Lesson03/first.py",
"Lesson03/support_vector_regression_degree_3_polynomial_kernel.py"
] |
[
"import pandas\nimport numpy as np\nfrom sklearn import model_selection\nfrom sklearn import preprocessing\nfrom sklearn import neighbors\n\n# 1. Loading data\ndata_frame = pandas.read_csv('german.data', sep=' ')\ndata_frame.replace('NA', -1000000, inplace=True)\n\n# 2. Label encoding\nlabels = {\n 'CheckingAccountStatus': ['A11', 'A12', 'A13', 'A14'],\n 'CreditHistory': ['A30', 'A31', 'A32', 'A33', 'A34'],\n 'CreditPurpose': ['A40', 'A41', 'A42', 'A43', 'A44', 'A45', 'A46', 'A47', 'A48', 'A49', 'A410'],\n 'SavingsAccount': ['A61', 'A62', 'A63', 'A64', 'A65'],\n 'EmploymentSince': ['A71', 'A72', 'A73', 'A74', 'A75'],\n 'PersonalStatusSex': ['A91', 'A92', 'A93', 'A94', 'A95'],\n 'OtherDebtors': ['A101', 'A102', 'A103'],\n 'Property': ['A121', 'A122', 'A123', 'A124'],\n 'OtherInstallmentPlans': ['A141', 'A142', 'A143'],\n 'Housing': ['A151', 'A152', 'A153'],\n 'Job': ['A171', 'A172', 'A173', 'A174'],\n 'Phone': ['A191', 'A192'],\n 'ForeignWorker': ['A201', 'A202']\n}\nlabel_encoders = {}\ndata_frame_encoded = pandas.DataFrame()\n\nfor column in data_frame:\n if column in labels:\n label_encoders[column] = preprocessing.LabelEncoder()\n label_encoders[column].fit(labels[column])\n data_frame_encoded[column] = label_encoders[column].transform(\n data_frame[column])\n else:\n data_frame_encoded[column] = data_frame[column]\n\n# 3. Identification of features and labels\nfeatures = np.array(data_frame_encoded.drop(['CreditScore'], 1))\nlabel = np.array(data_frame_encoded['CreditScore'])\n\n# 4. Scaling features\nscaled_features = preprocessing.MinMaxScaler(\n feature_range=(0, 1)).fit_transform(features)\n\n# 5. Splitting training and testing data\nfeatures_train, features_test, label_train, label_test = model_selection.train_test_split(\n scaled_features,\n label,\n test_size=0.2\n)\n\n# 6. Classification\nclassifier = neighbors.KNeighborsClassifier(n_neighbors=10)\nclassifier.fit(features_train, label_train)\n\nprint('Model score: ', classifier.score(features_test, label_test))\n",
"import numpy as np\nimport quandl\nfrom sklearn import preprocessing\nfrom sklearn import model_selection\nfrom sklearn import linear_model\nfrom matplotlib import pyplot as plot\nfrom sklearn.preprocessing import PolynomialFeatures\n\ndata_frame = quandl.get(\"YALE/SPCOMP\")\n\ndata_frame.fillna(-100, inplace=True)\n\n# We shift the price data to be predicted 20 years forward\ndata_frame['Real Price Label'] = data_frame['Real Price'].shift(-240)\n\n# Then exclude the label column from the features\nfeatures = np.array(data_frame.drop('Real Price Label', 1))\n\n# We scale before dropping the last 240 rows from the features\nscaled_features = preprocessing.scale(features)\n\n# Save the last 240 rows before dropping them\nscaled_features_latest_240 = scaled_features[-240:]\n\n# Exclude the last 240 rows from the data used for model building\nscaled_features = scaled_features[:-240]\n\n# Now we can drop the last 240 rows from the data frame\ndata_frame.dropna(inplace=True)\n\n# Then build the labels from the remaining data\nlabel = np.array(data_frame['Real Price Label'])\n\n# Create a polynomial regressor model and fit it to the training data\npoly_regressor = PolynomialFeatures(degree=3)\npoly_scaled_features = poly_regressor.fit_transform(scaled_features)\n\n# Split to training and testing data\n(poly_features_train, poly_features_test, poly_label_train,\n poly_label_test) = model_selection.train_test_split(poly_scaled_features, label, test_size=0.1)\n\n# Apply linear regression\nmodel = linear_model.LinearRegression()\nmodel.fit(poly_features_train, poly_label_train)\n\n# Model score\nprint('Score: ', model.score(poly_features_test, poly_label_test))\n\n# Prediction\npoly_label_predicted = model.predict(poly_features_test)\nplot.scatter(poly_label_test, poly_label_predicted)\n",
"import matplotlib.pyplot as plot\nimport numpy as np\n\n# First dataset:\nx1 = np.array(range(1, 14))\ny1 = np.array([2, 8, 8, 18, 25, 21, 32, 44, 32, 48, 61, 45, 62])\n\ndeg1 = np.polyfit(x1, y1, 1)\n# array([ 4.85714286, -2.76923077])\nf1 = np.poly1d(deg1)\n\ndeg2 = np.polyfit(x1, y1, 2)\n# array([-0.03196803, 5.3046953 , -3.88811189])\nf2 = np.poly1d(deg2)\n\ndeg3 = np.polyfit(x1, y1, 3)\n# array([-0.01136364, 0.20666833, 3.91833167, -1.97902098])\nf3 = np.poly1d(deg3)\n\nplot.plot(\n x1, y1, 'o',\n x1, f1(x1),\n x1, f2(x1),\n x1, f3(x1)\n)\nplot.show()\n",
"import numpy as np\nimport quandl\nfrom sklearn import preprocessing\nfrom sklearn import model_selection\nfrom sklearn import svm\nfrom matplotlib import pyplot as plot\n\ndata_frame = quandl.get(\"YALE/SPCOMP\")\n\ndata_frame.fillna(-100, inplace=True)\n\n# We shift the price data to be predicted 20 years forward\ndata_frame['Real Price Label'] = data_frame['Real Price'].shift(-240)\n\n# Then exclude the label column from the features\nfeatures = np.array(data_frame.drop('Real Price Label', 1))\n\n# We scale before dropping the last 240 rows from the features\nscaled_features = preprocessing.scale(features)\n\n# Save the last 240 rows before dropping them\nscaled_features_latest_240 = scaled_features[-240:]\n\n# Exclude the last 240 rows from the data used for model building\nscaled_features = scaled_features[:-240]\n\n# Now we can drop the last 240 rows from the data frame\ndata_frame.dropna(inplace=True)\n\n# Then build the labels from the remaining data\nlabel = np.array(data_frame['Real Price Label'])\n\n# The rest of the model building stays the same\n(features_train, features_test, label_train,\n label_test) = model_selection.train_test_split(scaled_features, label, test_size=0.1)\n\nmodel = svm.SVR(kernel='poly')\nmodel.fit(features_train, label_train)\n\nlabel_predicted = model.predict(features_test)\n\nprint('Score: ', model.score(features_test, label_test))\n\nplot.plot(label_test, label_predicted, 'o')\n"
] |
[
[
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame",
"sklearn.neighbors.KNeighborsClassifier",
"sklearn.preprocessing.LabelEncoder",
"numpy.array",
"sklearn.preprocessing.MinMaxScaler"
],
[
"matplotlib.pyplot.scatter",
"sklearn.model_selection.train_test_split",
"sklearn.preprocessing.PolynomialFeatures",
"sklearn.linear_model.LinearRegression",
"sklearn.preprocessing.scale",
"numpy.array"
],
[
"numpy.poly1d",
"numpy.polyfit",
"numpy.array",
"matplotlib.pyplot.show"
],
[
"sklearn.model_selection.train_test_split",
"sklearn.svm.SVR",
"matplotlib.pyplot.plot",
"sklearn.preprocessing.scale",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
firasm/pysketcher
|
[
"ef0c25b11b739197e254d714c69c86e107059be3"
] |
[
"tests/test_point.py"
] |
[
"from math import inf\n\nfrom conftest import isclose\nfrom hypothesis import assume, HealthCheck, note, settings\nimport numpy as np\nimport pytest\n\nfrom pysketcher import Angle, Point\nfrom tests.utils import given_inferred\n\n\nclass TestPoint:\n @given_inferred\n def test_coordinates(self, x: float, y: float) -> None:\n p = Point(x, y)\n assert p.x == x\n assert p.y == y\n\n @given_inferred\n def test_equality(self, x: float, y: float) -> None:\n assert Point(x, y) == Point(x, y)\n\n @given_inferred\n def test_adding(self, x1: float, x2: float, y1: float, y2: float):\n a = Point(x1, y1)\n b = Point(x2, y2)\n assert a + b == Point(x1 + x2, y1 + y2)\n\n @given_inferred\n def test_translation(self, x1: float, x2: float, y1: float, y2: float):\n a = Point(x1, y1)\n b = Point(x2, y2)\n assert a + b == Point(x1 + x2, y1 + y2)\n\n @given_inferred\n def test_subtraction(self, x1: float, x2: float, y1: float, y2: float):\n a = Point(x1, y1)\n b = Point(x2, y2)\n assert a - b == Point(x1 - x2, y1 - y2)\n\n @given_inferred\n def test_multiplication(self, x: float, y: float, s: float):\n a = Point(x, y)\n assert a * s == Point(x * s, y * s)\n\n @given_inferred\n def test_scale(self, x: float, y: float, s: float):\n a = Point(x, y)\n assert a.scale(s) == Point(x * s, y * s)\n\n @given_inferred\n def test_abs(self, x: float, y: float):\n assume(x * x != inf)\n assume(y * y != inf)\n a = Point(x, y)\n assert abs(a) == np.hypot(x, y)\n\n @given_inferred\n @settings(suppress_health_check=[HealthCheck.filter_too_much])\n def test_angle(self, a: Point):\n if a.x != 0.0:\n assume(abs(a.y / a.x) < 1e4)\n if a.y != 0.0:\n assume(abs(a.x / a.y) < 1e4)\n angle = a.angle()\n note(angle)\n b = Point(abs(a), 0.0).rotate(angle, Point(0.0, 0.0))\n note(f\"The angle is : {np.format_float_scientific(a.angle())}\")\n note(f\"The length is : {np.format_float_scientific(abs(a))}\")\n assert b == a\n assert -np.pi <= angle <= np.pi\n\n @given_inferred\n def test_unit_vector(self, x: float, y: float):\n a = Point(x, y)\n if isclose(abs(a), 0.0):\n with pytest.raises(ZeroDivisionError):\n a.unit_vector()\n else:\n b = a.unit_vector()\n note(f\"angle of a: {np.format_float_scientific(a.angle())}\")\n note(f\"angle of b: {np.format_float_scientific(b.angle())}\")\n assert isclose(a.angle(), b.angle())\n note(f\"magnitude of b: {abs(b)}\")\n assert isclose(abs(b), 1.0)\n\n @given_inferred\n def test_normal_vector(self, a: Point):\n if isclose(abs(a), 0.0):\n with pytest.raises(ZeroDivisionError):\n a.normal()\n else:\n angle = a.normal().angle() - a.angle()\n assert isclose(angle, np.pi / 2.0)\n\n @given_inferred\n def test_rotation_about_zero(self, a: Point, angle: Angle):\n assume(abs(a) != 0)\n b = a.rotate(angle, Point(0.0, 0.0))\n aa = a.angle()\n bb = b.angle()\n note(f\"a angle: {aa}\")\n note(f\"b angle: {bb}\")\n assert isclose(bb - aa, angle)\n\n @given_inferred\n @settings(suppress_health_check=[HealthCheck.filter_too_much])\n def test_rotation(self, a: Point, angle: Angle, center: Point):\n assume(abs(a - center) != 0)\n b = a.rotate(angle, center)\n new_angle = (b - center).angle() - (a - center).angle()\n note(angle)\n note(new_angle)\n assert isclose(angle, angle)\n\n\n#\n#\n# from_coordinate_lists_data = [\n# ([1, 2, 3, 4], [1, 2, 3, 4], [Point(1, 1), Point(2, 2), Point(3, 3), Point(4, 4)])\n# ]\n#\n#\n# @pytest.mark.parametrize(\"xs, ys, expected\", from_coordinate_lists_data)\n# def test_from_coordinate_lists(xs: List[float],\n# ys: List[float],\n# expected: List[Point]):\n# assert Point.from_coordinate_lists(xs, ys) == expected\n#\n#\n# @pytest.mark.parametrize(\"xs, ys, expected\", from_coordinate_lists_data)\n# def test_to_coordinate_lists(xs, ys, expected):\n# assert Point.to_coordinate_lists(expected) == (xs, ys)\n"
] |
[
[
"numpy.hypot"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
manusimidt/deep-reinforcement-learning
|
[
"814f83b162c445744874be56e6bc4e84aba2a207"
] |
[
"dqn/exercise/dqn_agent.py"
] |
[
"import numpy as np\nimport random\nfrom collections import namedtuple, deque\n\nfrom model import QNetwork\n\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nBUFFER_SIZE = int(1e5) # replay buffer size\nBATCH_SIZE = 64 # minibatch size\nGAMMA = 0.99 # discount factor\nTAU = 1e-3 # for soft update of target parameters\nLR = 5e-4 # learning rate \nUPDATE_EVERY = 4 # how often to update the network\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass Agent():\n \"\"\"Interacts with and learns from the environment.\"\"\"\n\n def __init__(self, state_size, action_size, seed):\n \"\"\"Initialize an Agent object.\n \n Params\n ======\n state_size (int): dimension of each state\n action_size (int): dimension of each action\n seed (int): random seed\n \"\"\"\n self.state_size = state_size\n self.action_size = action_size\n self.seed = random.seed(seed)\n\n # Q-Network\n self.qnetwork_local = QNetwork(state_size, action_size, seed).to(device)\n self.qnetwork_target = QNetwork(state_size, action_size, seed).to(device)\n self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR)\n\n # Replay memory\n self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed)\n # Initialize time step (for updating every UPDATE_EVERY steps)\n self.t_step = 0\n\n def step(self, state, action, reward, next_state, done):\n # Save experience in replay memory\n self.memory.add(state, action, reward, next_state, done)\n\n # Learn every UPDATE_EVERY time steps.\n self.t_step = (self.t_step + 1) % UPDATE_EVERY\n if self.t_step == 0:\n # If enough samples are available in memory, get random subset and learn\n if len(self.memory) > BATCH_SIZE:\n experiences = self.memory.sample()\n self.learn(experiences, GAMMA)\n\n def act(self, state, eps=0.):\n \"\"\"Returns actions for given state as per current policy.\n \n Params\n ======\n state (array_like): current state\n eps (float): epsilon, for epsilon-greedy action selection\n \"\"\"\n state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n self.qnetwork_local.eval()\n with torch.no_grad():\n action_values = self.qnetwork_local(state)\n self.qnetwork_local.train()\n\n # Epsilon-greedy action selection\n if random.random() > eps:\n return np.argmax(action_values.cpu().data.numpy())\n else:\n return random.choice(np.arange(self.action_size))\n\n def learn(self, experiences, gamma):\n \"\"\"Update value parameters using given batch of experience tuples.\n\n Params\n ======\n experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples \n gamma (float): discount factor\n \"\"\"\n states, actions, rewards, next_states, dones = experiences\n # Get max predicted Q values (for next states) from target model\n Q_targets_next = self.qnetwork_target.forward(next_states).detach().max(1)[0].unsqueeze(1)\n # Compute Q targets for current states \n Q_targets = rewards + (gamma * Q_targets_next * (1 - dones))\n\n # Get expected Q values from local model\n Q_expected = self.qnetwork_local.forward(states).gather(1, actions)\n\n # Compute loss\n loss = F.mse_loss(Q_expected, Q_targets)\n # Minimize the loss\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n # ------------------- update target network ------------------- #\n self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU)\n\n def soft_update(self, local_model, target_model, tau):\n \"\"\"Soft update model parameters.\n θ_target = τ*θ_local + (1 - τ)*θ_target\n\n Params\n ======\n local_model (PyTorch model): weights will be copied from\n target_model (PyTorch model): weights will be copied to\n tau (float): interpolation parameter \n \"\"\"\n for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):\n target_param.data.copy_(tau * local_param.data + (1.0 - tau) * target_param.data)\n\n\nclass ReplayBuffer:\n \"\"\"Fixed-size buffer to store experience tuples.\"\"\"\n\n def __init__(self, action_size, buffer_size, batch_size, seed):\n \"\"\"Initialize a ReplayBuffer object.\n\n Params\n ======\n action_size (int): dimension of each action\n buffer_size (int): maximum size of buffer\n batch_size (int): size of each training batch\n seed (int): random seed\n \"\"\"\n self.action_size = action_size\n self.memory = deque(maxlen=buffer_size)\n self.batch_size = batch_size\n self.experience = namedtuple(\"Experience\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"])\n self.seed = random.seed(seed)\n\n def add(self, state, action, reward, next_state, done):\n \"\"\"Add a new experience to memory.\"\"\"\n e = self.experience(state, action, reward, next_state, done)\n self.memory.append(e)\n\n def sample(self):\n \"\"\"Randomly sample a batch of experiences from memory.\"\"\"\n experiences = random.sample(self.memory, k=self.batch_size)\n\n states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device)\n actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).long().to(device)\n rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(device)\n next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(\n device)\n dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(\n device)\n\n return (states, actions, rewards, next_states, dones)\n\n def __len__(self):\n \"\"\"Return the current size of internal memory.\"\"\"\n return len(self.memory)\n"
] |
[
[
"numpy.arange",
"torch.from_numpy",
"torch.nn.functional.mse_loss",
"torch.no_grad",
"torch.cuda.is_available",
"numpy.vstack"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mpes-kit/pesfit
|
[
"d7a0a4d0ee3cc35d9c9ffb87e156bb5ad2802f81"
] |
[
"pesfit/metrics.py"
] |
[
"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport pandas as pd\nimport numpy as np\n\n\nclass GroupMetrics(object):\n \"\"\" Group-wise evaluation metrics calculator.\n \"\"\"\n \n def __init__(self, fres, nband):\n self.fres = fres\n self.nband = nband\n \n @property\n def nfres(self):\n return len(self.fres)\n \n def load_data(self, file, varname, shape):\n \"\"\" Load a set of reconstruction data.\n \"\"\"\n \n res = []\n for i in range(1, self.nband+1):\n fitres = pd.read_hdf(file)\n res.append(fitres['lp{}_{}'.format(i,varname)].values.reshape(shape))\n \n return np.array(res)\n \n def load_all_data(self, varname, shape):\n \"\"\" Load all reconstruction data.\n \"\"\"\n \n self.res = list(map(lambda f: self.load_data(f, varname, shape), self.fres))\n \n def rmse(self, result, ground_truth):\n \"\"\" Calculate root-mean-square error.\n \"\"\"\n \n rmserr = np.linalg.norm(result - ground_truth)\n return rmserr\n \n def group_rmse(self, ground_truth, form='averaged'):\n \"\"\" Calculate group-wise root-mean-square error.\n \"\"\"\n \n rmserrs = list(map(lambda r: self.rmse(r, ground_truth), self.res))\n if form == 'accumulated':\n self.group_rmserr = np.array(rmserrs)\n elif form == 'averaged':\n self.group_rmserr = np.array(rmserrs) / self.nband\n\n def instability(self, result, ground_truth):\n \"\"\" Calculate reconstruction instability.\n \"\"\"\n \n diff = result - ground_truth\n instab = np.var(diff)\n return instab\n \n def group_instability(self, ground_truth, form='averaged'):\n \"\"\" Calculate the group-wise reconstruction instability.\n \"\"\"\n \n instabs = list(map(lambda r: self.instability(r, ground_truth), self.res))\n if form == 'accumulated':\n self.group_instab = np.array(instabs)\n elif form == 'averaged':\n self.group_instab = np.array(instabs) / self.nband"
] |
[
[
"numpy.var",
"pandas.read_hdf",
"numpy.array",
"numpy.linalg.norm"
]
] |
[
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.24",
"1.13",
"1.16",
"1.9",
"1.18",
"1.23",
"1.21",
"1.22",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
zhxtu/ours_video
|
[
"2762501e4d3795872ffabc49fa3c73fdde10af8b",
"2762501e4d3795872ffabc49fa3c73fdde10af8b",
"2762501e4d3795872ffabc49fa3c73fdde10af8b",
"2762501e4d3795872ffabc49fa3c73fdde10af8b",
"2762501e4d3795872ffabc49fa3c73fdde10af8b"
] |
[
"models/modeling/net_utils.py",
"models/model_vid_re.py",
"train_vid.py",
"models/backbones/resnet_models.py",
"test_vid.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport pdb\n\nclass LayerNorm(nn.Module):\n\tdef __init__(self, eps=1e-5):\n\t\tsuper().__init__()\n\t\tself.register_parameter('gamma', None)\n\t\tself.register_parameter('beta', None)\n\t\tself.eps = eps\n\n\tdef forward(self, x):\n\t\tif self.gamma is None:\n\t\t\tself.gamma = nn.Parameter(torch.ones(x.size()).cuda())\n\t\tif self.beta is None:\n\t\t\tself.beta = nn.Parameter(torch.zeros(x.size()).cuda())\n\t\tmean = torch.min(x, 1, keepdim=True)[0]\n\t\tstd = x.std(1, keepdim=True)\n\t\treturn self.gamma * (x - mean) / (std + self.eps) + self.beta\n\nclass NLM(nn.Module):\n\t\"\"\"NLM layer, output affinity\"\"\"\n\tdef __init__(self, is_norm = False, iso1 = True):\n\t\tsuper(NLM, self).__init__()\n\t\tself.is_norm = is_norm\n\t\tif is_norm:\n\t\t\tself.norm = LayerNorm()\n\t\tself.softmax = nn.Softmax(dim=1)\n\t\tself.iso1 = iso1\n\n\tdef forward(self, in1, in2, return_unorm=False):\n\t\tn,c,h,w = in1.size()\n\t\tN = h*w\n\t\tin1 = in1.view(n,c,N)\n\t\tin2 = in2.view(n,c,N)\n\t\taffinity = torch.bmm(in1.permute(0,2,1), in2)\n\n\t\tfor ii in range(n):\n\t\t\tif self.iso1:\n\t\t\t\taffinity[ii] = affinity[ii] - 0.5*torch.diag(affinity[ii]).view(-1,1).repeat(1,N) - 0.5*torch.diag(affinity[ii]).view(1,-1).repeat(N,1)\n\t\t\telse:\n\t\t\t\tdiag_ = torch.diag(affinity[ii])\n\t\t\t\tfor xx in range(N):\n\t\t\t\t\taffinity[ii,xx] -= 0.5 * diag_\n\t\t\t\tfor yy in range(N):\n\t\t\t\t\taffinity[ii, :, yy] -= 0.5 * diag_\n\t\taff = self.softmax(affinity)\n\t\tif(return_unorm):\n\t\t\treturn aff,affinity\n\t\telse:\n\t\t\treturn aff\n\ndef featureL2Norm(feature):\n\tepsilon = 1e-6\n\tnorm = torch.pow(torch.sum(torch.pow(feature,2),1)+epsilon,0.5).unsqueeze(1).expand_as(feature)\n\treturn torch.div(feature,norm)\n\n\nclass NLM_dot(nn.Module):\n\t\"\"\"NLM layer, output affinity\"\"\"\n\tdef __init__(self, is_norm = False, temp = 1, l2_norm = False):\n\t\tsuper(NLM_dot, self).__init__()\n\t\tself.is_norm = is_norm\n\t\tself.l2_norm = l2_norm\n\t\tif is_norm:\n\t\t\tself.norm = LayerNorm()\n\t\tself.softmax = nn.Softmax(dim=1)\n\t\tself.temp = temp\n\n\tdef forward(self, in1, in2):\n\t\tn,c,h,w = in1.size()\n\t\tN = h*w\n\t\tin1 = in1.view(n,c,N)\n\t\tin2 = in2.view(n,c,N)\n\t\tif self.is_norm:\n\t\t\tin1 = self.norm(in1)\n\t\t\tin2 = self.norm(in2)\n\n\t\tif self.l2_norm:\n\t\t\tin1 = featureL2Norm(in1)\n\t\t\tin2 = featureL2Norm(in2)\n\n\t\taffinity = torch.bmm(in1.permute(0,2,1), in2)\n\t\taffinity = self.softmax(affinity*self.temp) # n*N*N\n\t\treturn affinity\n\n\nclass NLM_woSoft(nn.Module):\n\t\"\"\"NLM layer, output affinity, no softmax\"\"\"\n\tdef __init__(self, is_norm = False, l2_norm = False):\n\t\tsuper(NLM_woSoft, self).__init__()\n\t\tself.is_norm = is_norm\n\t\tself.l2_norm = l2_norm\n\t\tif is_norm:\n\t\t\tself.norm = LayerNorm()\n\n\tdef forward(self, in1, in2):\n\t\tn,c,h,w = in1.size()\n\t\tN = h*w\n\t\tin1 = in1.view(n,c,-1)\n\t\tin2 = in2.view(n,c,-1)\n\t\tif self.is_norm:\n\t\t\tin1 = self.norm(in1)\n\t\t\tin2 = self.norm(in2)\n\n\t\tif self.l2_norm:\n\t\t\tin1 = featureL2Norm(in1)\n\t\t\tin2 = featureL2Norm(in2)\n\n\t\taffinity = torch.bmm(in1.permute(0,2,1), in2)\n\t\treturn affinity\n\n\ndef MutualMatching(affinity):\n # mutual matching\n\tbatch_size, h, w = affinity.size()\n\t# get max\n\taffinity_B_max, _ = torch.max(affinity, dim=1, keepdim=True)\n\taffinity_A_max, _ = torch.max(affinity, dim=2, keepdim=True)\n\teps = 1e-5\n\taffinity_A = affinity/(affinity_A_max + eps)\n\taffinity_B = affinity/(affinity_B_max + eps)\n\taffinity = affinity*(affinity_A*affinity_B)\n\treturn affinity\n\n\nclass NLM_NC_woSoft(nn.Module):\n\t\"\"\"NLM layer, output affinity, no softmax\"\"\"\n\tdef __init__(self, is_norm = False, l2_norm = False):\n\t\tsuper(NLM_NC_woSoft, self).__init__()\n\t\tself.is_norm = is_norm\n\t\tself.l2_norm = l2_norm\n\t\tif is_norm:\n\t\t\tself.norm = LayerNorm()\n\n\tdef forward(self, in1, in2):\n\t\tb,c,h1,w1 = in1.size()\n\t\tb,c,h2,w2 = in2.size()\n\t\t# reshape features for matrix multiplication\n\t\tin1 = in1.view(b,c,h1*w1).transpose(1,2) # size [b,c,h*w]\n\t\tin2 = in2.view(b,c,h2*w2) # size [b,c,h*w]\n\t\t# perform matrix mult.\n\t\tfeature_mul = torch.bmm(in1, in2)\n\t\taffinity = MutualMatching(feature_mul)\n\t\treturn affinity\n\n\nclass Batch_Contrastive(nn.Module):\n\t\"\"\" Feaure contrastive loss on batch \"\"\"\n\tdef __init__(self, temp = 1, is_norm = False, l2_norm = False):\n\t\tsuper(Batch_Contrastive, self).__init__()\n\t\tself.is_norm = is_norm\n\t\tself.l2_norm = l2_norm\n\t\tself.temp = temp\n\t\tself.MSE_Loss = torch.nn.MSELoss(reduction = 'mean')\n\t\tself.L1_Loss = torch.nn.L1Loss(reduction = 'mean')\n\t\tif is_norm:\n\t\t\tself.norm = LayerNorm()\n\n\tdef forward(self, feat_2, feat_1, Fcolor1):\n\t\t# feat_2: target feature to be reconstructed feat_1 and Fcolor1: source features\n\t\tb, feat_c, feat_h, feat_w = feat_1.size()\n\n\t\t# contrastive learning\n\t\tfeat_1 = feat_1.permute(0,2,3,1).contiguous() # dim: [B, Dim, H, W] -> [B, H, W, Dim]\n\t\tfeat_1 = feat_1.view(-1, feat_c) # [Num_embedding (B*H*W), dim]\n\t\tfeat_2 = feat_2.permute(0,2,3,1).contiguous() \n\t\tfeat_2 = feat_2.view(-1, feat_c) \n\n\t\t_, color_c, _, _ = Fcolor1.size() \n\t\tFcolor1 = Fcolor1.permute(0,2,3,1).contiguous() \n\t\tFcolor1 = Fcolor1.view(-1, color_c) \n\n\t\tbatch_affinity = feat_2.mm(feat_1.t())\n\t\tnorm_batch_affinity = F.softmax(batch_affinity * self.temp, dim=-1)\n\t\tcolor_2_est = norm_batch_affinity.mm(Fcolor1)\n\t\tcolor_2_est = color_2_est.view(b, feat_h, feat_w, color_c).permute(0,3,1,2)\n\n\t\t# the mask to ignore the correlations of other batches\n\t\tmask = torch.zeros([b*feat_h*feat_w, b*feat_h*feat_w]).cuda()\n\t\tbatch_len = feat_h * feat_w\n\t\tfor i in range(b):\n\t\t\tstart_x = i * batch_len\n\t\t\tstart_y = i * batch_len\n\t\t\tmask[start_x:(start_x + batch_len), start_y:(start_y + batch_len)] = 1\n\n\t\tbatch_sim = (norm_batch_affinity * mask).sum(-1)\n\t\tbatch_loss = self.L1_Loss(batch_sim, torch.ones(b*feat_h*feat_w).cuda())\n\t\treturn color_2_est, batch_loss\n\n",
"import math, time\nfrom itertools import chain\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\nfrom base import BaseModel\nfrom utils.losses import *\nfrom models.encoder import Encoder\nfrom models.modeling.deeplab import DeepLab as DeepLab_v3p\n# from models.modeling.net_utils import NLM, NLM_dot, NLM_woSoft, NLM_NC_woSoft, Batch_Contrastive\nimport numpy as np\nimport cv2\nimport kornia\nfrom models.feature_memory import *\nfrom memory_profiler import profile\nfrom lib.models.tools.module_helper import ModuleHelper\nEPS = 1e-20\nclass VCL(BaseModel):\n def __init__(self, num_classes, conf, sup_loss=None, ignore_index=None, testing=False, pretrained=True):\n\n super(VCL, self).__init__()\n assert int(conf['supervised']) + int(conf['semi']) == 1, 'one mode only'\n if conf['supervised']:\n self.mode = 'supervised'\n elif conf['semi']:\n self.mode = 'semi'\n else:\n raise ValueError('No such mode choice {}'.format(self.mode))\n\n self.ignore_index = ignore_index\n\n self.num_classes = num_classes\n self.sup_loss_w = conf['supervised_w']\n self.sup_loss = sup_loss\n self.downsample = conf['downsample']\n self.backbone = conf['backbone']\n self.layers = conf['layers']\n self.out_dim = conf['out_dim']\n self.proj_final_dim = conf['proj_final_dim']\n self._xent_targets = dict()\n self.edgedrop_rate=0.1\n self.temperature = 0.07\n self.base_temperature = 0.07\n self.ignore_mask = -100\n self.xent = nn.CrossEntropyLoss(ignore_index=self.ignore_mask,reduction=\"none\")\n self.queue_len = conf['queue_len']\n self.max_samples = conf['max_samples']\n # self.gpu_mem = open(\"/home/zhengyu/ours_video/gpu_memory.txt\", 'w+')\n self.register_buffer(\"segment_queue\", torch.randn(num_classes, self.queue_len, self.proj_final_dim))\n self.segment_queue = F.normalize(self.segment_queue, p=2, dim=2)\n self.register_buffer(\"segment_queue_ptr\", torch.zeros(num_classes, dtype=torch.long))\n # feature_memory = FeatureMemory(num_samples=labeled_samples, dataset=dataset, memory_per_class=256,\n # feature_size=256, n_classes=num_classes)\n # self.segment_queue =\n self.pos_sample_num = 500\n self.neg_sample_num = 1000\n assert self.layers in [50, 101]\n\n if self.backbone == 'deeplab_v3+':\n self.encoder = DeepLab_v3p(backbone='resnet{}'.format(self.layers))\n self.classifier = nn.Sequential(nn.Dropout(0.1), nn.Conv2d(256, num_classes, kernel_size=1, stride=1))\n for m in self.classifier.modules():\n if isinstance(m, nn.Conv2d):\n torch.nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.SyncBatchNorm):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif self.backbone == 'psp':\n self.encoder = Encoder(pretrained=pretrained)\n self.classifier = nn.Conv2d(self.out_dim, num_classes, kernel_size=1, stride=1)\n else:\n raise ValueError(\"No such backbone {}\".format(self.backbone))\n\n if self.mode == 'semi':\n self.project = nn.Sequential(\n nn.Conv2d(self.out_dim, self.out_dim, kernel_size=1, stride=1),\n ModuleHelper.BNReLU(self.out_dim, bn_type='torchsyncbn'),\n nn.Conv2d(self.out_dim, self.proj_final_dim, kernel_size=1, stride=1)\n )\n # self.nlm = NLM_woSoft()\n self.weight_unsup = conf['weight_unsup']\n self.weight_cycle = conf['weight_cycle']\n self.weight_inter = conf['weight_inter']\n self.temp = conf['temp']\n self.epoch_start_unsup = conf['epoch_start_unsup']\n self.epoch_start_cycle = conf['epoch_start_cycle']\n self.selected_num = conf['selected_num']\n self.step_save = conf['step_save']\n self.step_count = 0\n self.feature_bank = []\n self.pseudo_label_bank = []\n self.pos_thresh_value = conf['pos_thresh_value']\n self.stride = conf['stride']\n def affinity(self, x1, x2):\n in_t_dim = x1.ndim\n if in_t_dim < 4: # add in time dimension if not there\n x1, x2 = x1.unsqueeze(-2), x2.unsqueeze(-2)\n A = torch.einsum('btnc,btmc->btnm', x1, x2)\n # if self.restrict is not None:\n # A = self.restrict(A)\n return A.squeeze(1) if in_t_dim < 4 else A\n def stoch_mat(self, A, zero_diagonal=False, do_dropout=True, do_sinkhorn=False):\n ''' Affinity -> Stochastic Matrix '''\n if zero_diagonal:\n A = self.zeroout_diag(A)\n\n if do_dropout and self.edgedrop_rate > 0:\n A[torch.rand_like(A) < self.edgedrop_rate] = -1e20\n\n return F.softmax(A/self.temperature, dim=-1)\n\n # @profile(precision=4, stream=open('/home/zhengyu/ours_video/memory/memory_modelforward.log', 'w+'))\n def forward(self, x_l=None, target_l=None, x_ul=None, target_ul=None, c_f=None, c_b=None, curr_iter=None, epoch=None, gpu=None, gt_l=None, ul1=None, br1=None, \\\n ul2=None, br2=None, flip=None, theta=None,):\n if not self.training:\n enc = self.encoder(x_l)\n enc = self.classifier(enc)\n return F.interpolate(enc, size=x_l.size()[2:], mode='bilinear', align_corners=True)\n\n if self.mode == 'supervised':\n enc = self.encoder(x_l)\n enc = self.classifier(enc)\n output_l = F.interpolate(enc, size=x_l.size()[2:], mode='bilinear', align_corners=True)\n \n loss_sup = self.sup_loss(output_l, target_l, ignore_index=self.ignore_index, temperature=1.0) * self.sup_loss_w\n \n curr_losses = {'loss_sup': loss_sup}\n outputs = {'sup_pred': output_l}\n total_loss = loss_sup\n return total_loss, curr_losses, outputs\n\n elif self.mode == 'semi':\n # supervised\n enc = self.encoder(x_l) #4*256*80*80\n enc_logit = self.classifier(enc) #4*17*80*80\n output_l = F.interpolate(enc_logit, size=x_l.size()[2:], mode='bilinear', align_corners=True)\n loss_sup = self.sup_loss(output_l, target_l, ignore_index=self.ignore_index, temperature=1.0) * self.sup_loss_w\n\n curr_losses = {'loss_sup': loss_sup}\n outputs = {'sup_pred': output_l}\n total_loss = loss_sup\n # if epoch < self.epoch_start_cycle:\n # return total_loss, curr_losses, outputs\n #####################Memory Construction############################################\n # print(\"1:{}\".format(torch.cuda.memory_allocated(0)), file=self.gpu_mem)\n # model.eval()\n # proj_labeled_features_correct = model.projection_head(labeled_features_correct)\n # model.train()\n # with torch.no_grad():\n if epoch < 5:\n with torch.no_grad():\n enc_l=self.project(enc.detach())\n else:\n enc_l = self.project(enc)\n enc_l = F.normalize(enc_l, 2, 1)\n key = enc_l.detach()#enc.detach()\n lb_key = target_l.detach()\n pred_key = enc_logit.detach()\n self._dequeue_and_enqueue(key, lb_key, pred_key,\n segment_queue=self.segment_queue,\n segment_queue_ptr=self.segment_queue_ptr)\n if epoch < 5:\n return total_loss, curr_losses, outputs\n # print(\"2:{}\".format(torch.cuda.memory_allocated(0)), file=self.gpu_mem)\n # ##################### intra-video loss #############################################\n # B, T, C, h, w = c_f.shape\n # # f_clip=c_f[batch_idx, :, :, :, :]\n # # b_clip = c_b[batch_idx, :, :, :, :]\n # f_encs = self.encoder(c_f.flatten(0, 1)) # B*T,256,80,80\n # b_encs = self.encoder(c_b.flatten(0, 1)) # (B*T*256)*80*80\n # if self.downsample:\n # f_encs = F.avg_pool2d(f_encs, kernel_size=2, stride=2)\n # b_encs = F.avg_pool2d(b_encs, kernel_size=2, stride=2)\n # f_encs_out = self.project(f_encs) # [b, c, h, w] #B*T,128,80,80\n # f_encs_out = F.normalize(f_encs_out, 2, 1)\n #\n # f1_encs = f_encs_out[1].unsqueeze(0)\n # b, c, fh, fw = f_encs_out.shape\n # for i in range(1, B): f1_encs = torch.cat((f1_encs, f_encs_out[5 * i].unsqueeze(0)), 0)\n # f1_encs_warp = kornia.geometry.transform.warp_affine(f1_encs, theta, [fw, fh], mode='bilinear')\n # f_encs_new = f_encs_out.clone()\n # for i in range(0, B): f_encs_new[5 * i] = f1_encs_warp[i]\n # f_encs_new_flatten = f_encs_new.flatten(-2, -1).view(B, T, f_encs_new.size(1), -1).permute(0, 1, 3, 2)\n #\n # b_encs_out = self.project(b_encs) # [b, c, h, w]\n # b_encs_out = F.normalize(b_encs_out, 2, 1)\n # b_encs_flatten = b_encs_out.flatten(-2, -1).view(B, T, b_encs_out.size(1), -1).permute(0, 1, 3,\n # 2) # 4*5*6400*256\n # b_encs_flip_flatten = torch.flip(b_encs_flatten, dims=[1])\n #\n # new_seq = torch.cat((f_encs_new_flatten, b_encs_flip_flatten), dim=1) # 4*10*6400*256\n #\n # # Compute walks\n # M = torch.ones(B, 1, fh, fw).cuda()\n # mask_prob = kornia.geometry.transform.warp_affine(M, theta, [fw, fh], mode='bilinear')\n # ignore_ind = (mask_prob <= 0.5).flatten() # .type(torch.float)\n #\n # walks = dict()\n # A_fb = self.affinity(new_seq[:, :-1], new_seq[:, 1:]) # affinity矩阵 前后帧\n # A12s = [self.stoch_mat(A_fb[:, i], do_dropout=True) for i in range(2 * T - 1)] # softmax归一化的随机矩阵A\n # # A21s = [self.stoch_mat(A_fb[:, i].transpose(-1, -2), do_dropout=True) for i in range(2 * T - 1)]\n # A_mm = self.affinity(f_encs_new_flatten[:, 1:], b_encs_flatten[:, 1:]) # 对应帧\n # # A_mm = self.affinity(f_encs_new[:, 1:-1], b_encs[:, 1:-1]) #对应帧\n # # A_mm = torch.cat((A_mm,A_fb[:,T-1].unsqueeze(1)),dim=1)\n # A12m = [self.stoch_mat(A_mm[:, i], do_dropout=True) for i in range(T - 1)]\n #\n # AAs = []\n # for i in range(1, T - 1): #\n # g = A12s[:i + 1]\n # g.append(A12m[i])\n # g.extend(A12s[-(i + 1):]) # list相加为cat,构成闭环 #print(a[::-1]) ### 取从后向前的元素\n # aar = g[0]\n # for _a in g[1:]:\n # aar = aar @ _a\n # AAs.append((f\"r{i}\", aar))\n # for i, aa in AAs:\n # walks[f\"cyc {i}\"] = [aa, self.xent_targets(aa)] # xent_targets为0到1599的数据并重复B次,一维tensor\n # # Compute loss\n # xents = [torch.tensor([0.]).cuda()]\n # # diags = dict()\n #\n # for name, (A, targets) in walks.items():\n # logits = torch.log(A + EPS).flatten(0, -2)\n # target = targets.clone()\n # target[ignore_ind] = self.ignore_mask\n # loss = self.xent(logits, target).mean()\n # # acc = (torch.argmax(logit, dim=-1) == target).float().mean()\n # # diags.update({f\"{h} xent {name}\": loss.detach(),\n # # f\"{h} acc {name}\": acc})\n # xents += [loss]\n # loss_cycle = self.weight_cycle * sum(xents[1:]) / max(1, len(xents) - 1)\n # curr_losses['loss_cycle'] = loss_cycle\n # total_loss = total_loss + loss_cycle\n # if epoch < self.epoch_start_unsup:\n # return total_loss, curr_losses, outputs\n\n ##################### unsup loss #############################################\n # x_ul: [batch_size, 2, 3, H, W]\n x_ul1 = x_ul[:, 0, :, :, :]\n x_ul2 = x_ul[:, 1, :, :, :]\n\n enc_ul1_up = self.encoder(x_ul1)\n output_ul1_up = self.project(enc_ul1_up)\n output_ul1_up = F.normalize(output_ul1_up, 2, 1)\n # #if self.downsample:\n # enc_ul1 = F.avg_pool2d(enc_ul1_up, kernel_size=2, stride=2)\n # output_ul1 = self.project(enc_ul1) #[b, c, h, w]\n # output_ul1 = F.normalize(output_ul1, 2, 1)\n\n enc_ul2_up = self.encoder(x_ul2)\n output_ul2_up = self.project(enc_ul2_up)\n output_ul2_up = F.normalize(output_ul2_up, 2, 1)\n # # if self.downsample:\n # enc_ul2 = F.avg_pool2d(enc_ul2_up, kernel_size=2, stride=2)\n # output_ul2 = self.project(enc_ul2) #[b, c, h, w]\n # output_ul2 = F.normalize(output_ul2, 2, 1)\n\n # compute pseudo label\n with torch.no_grad():\n # logits1 = self.classifier(enc_ul1) #[batch_size, num_classes, h, w]\n # logits2 = self.classifier(enc_ul2)\n # pseudo_logits_1 = F.softmax(logits1, 1).max(1)[0].detach() #[batch_size, h, w]\n # pseudo_logits_2 = F.softmax(logits2, 1).max(1)[0].detach()\n # pseudo_label1 = logits1.max(1)[1].detach() #[batch_size, h, w]\n # pseudo_label2 = logits2.max(1)[1].detach()\n\n logits1_up = self.classifier(enc_ul1_up) # [batch_size, num_classes, h, w]\n logits2_up = self.classifier(enc_ul2_up)\n pseudo_logits1_up = F.softmax(logits1_up, 1).max(1)[0].detach() #[batch_size, h, w]\n pseudo_logits2_up = F.softmax(logits2_up, 1).max(1)[0].detach()\n pseudo_label1_up = logits1_up.max(1)[1].detach() # [batch_size, h, w]\n pseudo_label2_up = logits2_up.max(1)[1].detach()\n\n # get overlap part\n output_feature_list1 = []\n output_feature_list2 = []\n pseudo_label_list1 = []\n pseudo_label_list2 = []\n pseudo_logits_list1 = []\n pseudo_logits_list2 = []\n enc_feature_list1_up = []\n enc_feature_list2_up = []\n pseudo_logits_list1_up = []\n pseudo_logits_list2_up = []\n pseudo_label_list1_up = []\n pseudo_label_list2_up = []\n for idx in range(x_ul1.size(0)):\n # output_ul1_idx = output_ul1[idx]\n # output_ul2_idx = output_ul2[idx]\n enc_ul1_idx_up = output_ul1_up[idx]\n enc_ul2_idx_up = output_ul2_up[idx]\n # pseudo_label1_idx = pseudo_label1[idx]\n # pseudo_label2_idx = pseudo_label2[idx]\n # pseudo_logits_1_idx = pseudo_logits_1[idx]\n # pseudo_logits_2_idx = pseudo_logits_2[idx]\n pseudo_label1_idx_up = pseudo_label1_up[idx]\n pseudo_label2_idx_up = pseudo_label2_up[idx]\n pseudo_logits_1_idx_up = pseudo_logits1_up[idx]\n pseudo_logits_2_idx_up = pseudo_logits2_up[idx]\n if flip[0][idx] == True:\n # output_ul1_idx = torch.flip(output_ul1_idx, dims=(2,))\n enc_ul1_idx_up = torch.flip(enc_ul1_idx_up, dims=(2,))\n # pseudo_label1_idx = torch.flip(pseudo_label1_idx, dims=(1,))\n # pseudo_logits_1_idx = torch.flip(pseudo_logits_1_idx, dims=(1,))\n pseudo_label1_idx_up = torch.flip(pseudo_label1_idx_up, dims=(1,))\n pseudo_logits_1_idx_up = torch.flip(pseudo_logits_1_idx_up, dims=(1,))\n if flip[1][idx] == True:\n # output_ul2_idx = torch.flip(output_ul2_idx, dims=(2,))\n enc_ul2_idx_up = torch.flip(enc_ul2_idx_up, dims=(2,))\n # pseudo_label2_idx = torch.flip(pseudo_label2_idx, dims=(1,))\n # pseudo_logits_2_idx = torch.flip(pseudo_logits_2_idx, dims=(1,))\n pseudo_label2_idx_up = torch.flip(pseudo_label2_idx_up, dims=(1,))\n pseudo_logits_2_idx_up = torch.flip(pseudo_logits_2_idx_up, dims=(1,))\n # 因为原图320,特征缩小了8倍,80×80,所以对应的原图空间特征也要/8\n ul1_t, br1_t, ul2_t, br2_t = torch.stack(ul1, 0), torch.stack(br1, 0), torch.stack(ul2, 0), torch.stack(br2, 0)\n ul1_f, br1_f, ul2_f, br2_f = ul1_t // 8, br1_t // 8, ul2_t // 8, br2_t // 8\n ul1_f_up, br1_f_up, ul2_f_up, br2_f_up = ul1_t // 4, br1_t // 4, ul2_t // 4, br2_t // 4\n # output_feature_list1.append(output_ul1_idx[:, ul1_f[0, idx]:br1_f[0, idx], ul1_f[1, idx]:br1_f[1, idx]].permute(1, 2, 0).contiguous().view(-1, output_ul1.size(1)))\n # output_feature_list2.append(output_ul2_idx[:, ul2_f[0, idx]:br2_f[0, idx], ul2_f[1, idx]:br2_f[1, idx]].permute(1, 2, 0).contiguous().view(-1, output_ul2.size(1)))\n enc_feature_list1_up.append(enc_ul1_idx_up[:, ul1_f_up[0, idx]:br1_f_up[0, idx], ul1_f_up[1, idx]:br1_f_up[1, idx]].permute(1, 2, 0).contiguous().view(-1, output_ul1_up.size(1)))\n enc_feature_list2_up.append(enc_ul2_idx_up[:, ul2_f_up[0, idx]:br2_f_up[0, idx], ul2_f_up[1, idx]:br2_f_up[1, idx]].permute(1, 2, 0).contiguous().view(-1, output_ul2_up.size(1)))\n\n # pseudo_label_list1.append(pseudo_label1_idx[ul1_f[0, idx]:br1_f[0, idx], ul1_f[1, idx]:br1_f[1, idx]].contiguous().view(-1))\n # pseudo_label_list2.append(pseudo_label2_idx[ul2_f[0, idx]:br2_f[0, idx], ul2_f[1, idx]:br2_f[1, idx]].contiguous().view(-1))\n # pseudo_logits_list1.append(pseudo_logits_1_idx[ul1_f[0, idx]:br1_f[0, idx], ul1_f[1, idx]:br1_f[1, idx]].contiguous().view(-1))\n # pseudo_logits_list2.append(pseudo_logits_2_idx[ul2_f[0, idx]:br2_f[0, idx], ul2_f[1, idx]:br2_f[1, idx]].contiguous().view(-1))\n pseudo_label_list1_up.append(pseudo_label1_idx_up[ul1_f_up[0, idx]:br1_f_up[0, idx], ul1_f_up[1, idx]:br1_f_up[1, idx]].contiguous().view(-1))\n pseudo_label_list2_up.append(pseudo_label2_idx_up[ul2_f_up[0, idx]:br2_f_up[0, idx], ul2_f_up[1, idx]:br2_f_up[1, idx]].contiguous().view(-1))\n pseudo_logits_list1_up.append(pseudo_logits_1_idx_up[ul1_f_up[0, idx]:br1_f_up[0, idx], ul1_f_up[1, idx]:br1_f_up[1, idx]].contiguous().view(-1))\n pseudo_logits_list2_up.append(pseudo_logits_2_idx_up[ul2_f_up[0, idx]:br2_f_up[0, idx], ul2_f_up[1, idx]:br2_f_up[1, idx]].contiguous().view(-1))\n\n # output_feat1 = torch.cat(output_feature_list1, 0) #[n, c] 所有重叠区域像素特征集合\n # output_feat2 = torch.cat(output_feature_list2, 0) #[n, c]\n # pseudo_label1_overlap = torch.cat(pseudo_label_list1, 0) #[n,] #所有重叠区域像素伪标签集合\n # pseudo_label2_overlap = torch.cat(pseudo_label_list2, 0) #[n,]\n # pseudo_logits1_overlap = torch.cat(pseudo_logits_list1, 0) #[n,]\n # pseudo_logits2_overlap = torch.cat(pseudo_logits_list2, 0) #[n,]\n # assert output_feat1.size(0) == output_feat2.size(0)\n # assert pseudo_label1_overlap.size(0) == pseudo_label2_overlap.size(0)\n # assert output_feat1.size(0) == pseudo_label1_overlap.size(0)\n\n # concat across multi-gpus\n b, c, h, w = enc_ul1_up.size()\n # selected_num = self.selected_num\n # output_ul1_flatten = output_ul1.permute(0, 2, 3, 1).contiguous().view(b*h*w, c)\n # output_ul2_flatten = output_ul2.permute(0, 2, 3, 1).contiguous().view(b*h*w, c)\n # selected_idx1 = np.random.choice(range(b*h*w), selected_num, replace=False)\n # selected_idx2 = np.random.choice(range(b*h*w), selected_num, replace=False)\n # output_ul1_flatten_selected = output_ul1_flatten[selected_idx1]\n # output_ul2_flatten_selected = output_ul2_flatten[selected_idx2]\n # output_ul_flatten_selected = torch.cat([output_ul1_flatten_selected, output_ul2_flatten_selected], 0) #[2*kk, c]\n # output_ul_all = self.concat_all_gather(output_ul_flatten_selected) #[2*N, c]\n #\n # pseudo_label1_flatten_selected = pseudo_label1.view(-1)[selected_idx1]\n # pseudo_label2_flatten_selected = pseudo_label2.view(-1)[selected_idx2]\n # pseudo_label_flatten_selected = torch.cat([pseudo_label1_flatten_selected, pseudo_label2_flatten_selected], 0) #[2*kk]\n # pseudo_label_all = self.concat_all_gather(pseudo_label_flatten_selected) #[2*N]\n #\n # self.feature_bank.append(output_ul_all)\n # self.pseudo_label_bank.append(pseudo_label_all)\n # if self.step_count > self.step_save:\n # self.feature_bank = self.feature_bank[1:]\n # self.pseudo_label_bank = self.pseudo_label_bank[1:]\n # else:\n # self.step_count += 1\n # output_ul_all = torch.cat(self.feature_bank, 0)\n # pseudo_label_all = torch.cat(self.pseudo_label_bank, 0)\n #\n # eps = 1e-8\n # pos1 = (output_feat1 * output_feat2.detach()).sum(-1, keepdim=True) / self.temp #[n, 1] 共3573个重叠点 不同view的相同点为pos\n # pos2 = (output_feat1.detach() * output_feat2).sum(-1, keepdim=True) / self.temp #[n, 1]\n #\n # # compute loss1\n # b = 8000\n # def run1(pos, output_feat1, output_ul_idx, pseudo_label_idx, pseudo_label1_overlap, neg_max1):\n # # print(\"gpu: {}, i_1: {}\".format(gpu, i))\n # mask1_idx = (pseudo_label_idx.unsqueeze(0) != pseudo_label1_overlap.unsqueeze(-1)).float() #[n, b] 找到3573个重叠点与view中所有点不同label的点作为neg\n # neg1_idx = (output_feat1 @ output_ul_idx.T) / self.temp #[n, b] #将自身点之外的所有点当做neg 求相似度\n # logits1_neg_idx = (torch.exp(neg1_idx - neg_max1) * mask1_idx).sum(-1) #[n, ]\n # return logits1_neg_idx\n #\n # def run1_0(pos, output_feat1, output_ul_idx, pseudo_label_idx, pseudo_label1_overlap):\n # # print(\"gpu: {}, i_1_0: {}\".format(gpu, i))\n # mask1_idx = (pseudo_label_idx.unsqueeze(0) != pseudo_label1_overlap.unsqueeze(-1)).float() #[n, b] 找到3573个重叠点与view中所有点不同label的点作为neg\n # neg1_idx = (output_feat1 @ output_ul_idx.T) / self.temp #[n, b] #将自身点之外的所有点当做neg 求相似度\n # neg1_idx = torch.cat([pos, neg1_idx], 1) #[n, 1+b] 将pos与neg串起来\n # mask1_idx = torch.cat([torch.ones(mask1_idx.size(0), 1).float().cuda(), mask1_idx], 1) #[n, 1+b]\n # neg_max1 = torch.max(neg1_idx, 1, keepdim=True)[0] #[n, 1]\n # logits1_neg_idx = (torch.exp(neg1_idx - neg_max1) * mask1_idx).sum(-1) #[n, ]\n # return logits1_neg_idx, neg_max1\n #\n # N = output_ul_all.size(0)\n # logits1_down = torch.zeros(pos1.size(0)).float().cuda()\n # for i in range((N-1)//b + 1):\n # # print(\"gpu: {}, i: {}\".format(gpu, i))\n # pseudo_label_idx = pseudo_label_all[i*b:(i+1)*b] #每次8000个点\n # output_ul_idx = output_ul_all[i*b:(i+1)*b]\n # if i == 0:\n # logits1_neg_idx, neg_max1 = torch.utils.checkpoint.checkpoint(run1_0, pos1, output_feat1, output_ul_idx, pseudo_label_idx, pseudo_label1_overlap)\n # else:\n # logits1_neg_idx = torch.utils.checkpoint.checkpoint(run1, pos1, output_feat1, output_ul_idx, pseudo_label_idx, pseudo_label1_overlap, neg_max1)\n # logits1_down += logits1_neg_idx\n #\n # logits1 = torch.exp(pos1 - neg_max1).squeeze(-1) / (logits1_down + eps)\n #\n # pos_mask_1 = ((pseudo_logits2_overlap > self.pos_thresh_value) & (pseudo_logits1_overlap < pseudo_logits2_overlap)).float()\n # loss1 = -torch.log(logits1 + eps)\n # loss1 = (loss1 * pos_mask_1).sum() / (pos_mask_1.sum() + 1e-12)\n #\n # # compute loss2\n # def run2(pos, output_feat2, output_ul_idx, pseudo_label_idx, pseudo_label2_overlap, neg_max2):\n # # print(\"gpu: {}, i_2: {}\".format(gpu, i))\n # mask2_idx = (pseudo_label_idx.unsqueeze(0) != pseudo_label2_overlap.unsqueeze(-1)).float() #[n, b]\n # neg2_idx = (output_feat2 @ output_ul_idx.T) / self.temp #[n, b]\n # logits2_neg_idx = (torch.exp(neg2_idx - neg_max2) * mask2_idx).sum(-1) #[n, ]\n # return logits2_neg_idx\n #\n # def run2_0(pos, output_feat2, output_ul_idx, pseudo_label_idx, pseudo_label2_overlap):\n # # print(\"gpu: {}, i_2_0: {}\".format(gpu, i))\n # mask2_idx = (pseudo_label_idx.unsqueeze(0) != pseudo_label2_overlap.unsqueeze(-1)).float() #[n, b]\n # neg2_idx = (output_feat2 @ output_ul_idx.T) / self.temp #[n, b]\n # neg2_idx = torch.cat([pos, neg2_idx], 1) #[n, 1+b]\n # mask2_idx = torch.cat([torch.ones(mask2_idx.size(0), 1).float().cuda(), mask2_idx], 1) #[n, 1+b]\n # neg_max2 = torch.max(neg2_idx, 1, keepdim=True)[0] #[n, 1]\n # logits2_neg_idx = (torch.exp(neg2_idx - neg_max2) * mask2_idx).sum(-1) #[n, ]\n # return logits2_neg_idx, neg_max2\n #\n # N = output_ul_all.size(0)\n # logits2_down = torch.zeros(pos2.size(0)).float().cuda()\n # for i in range((N-1)//b + 1):\n # pseudo_label_idx = pseudo_label_all[i*b:(i+1)*b]\n # output_ul_idx = output_ul_all[i*b:(i+1)*b]\n # if i == 0:\n # logits2_neg_idx, neg_max2 = torch.utils.checkpoint.checkpoint(run2_0, pos2, output_feat2, output_ul_idx, pseudo_label_idx, pseudo_label2_overlap)\n # else:\n # logits2_neg_idx = torch.utils.checkpoint.checkpoint(run2, pos2, output_feat2, output_ul_idx, pseudo_label_idx, pseudo_label2_overlap, neg_max2)\n # logits2_down += logits2_neg_idx\n #\n # logits2 = torch.exp(pos2 - neg_max2).squeeze(-1) / (logits2_down + eps)\n #\n # pos_mask_2 = ((pseudo_logits1_overlap > self.pos_thresh_value) & (pseudo_logits2_overlap < pseudo_logits1_overlap)).float()\n #\n # loss2 = -torch.log(logits2 + eps)\n # loss2 = (loss2 * pos_mask_2).sum() / (pos_mask_2.sum() + 1e-12)\n #\n # loss_unsup = self.weight_unsup * (loss1 + loss2)\n # curr_losses['loss1'] = loss1\n # curr_losses['loss2'] = loss2\n # curr_losses['loss_unsup'] = loss_unsup\n # total_loss = total_loss + loss_unsup\n # if epoch < self.epoch_start_inter:\n # return total_loss, curr_losses, outputs\n # # return total_loss, curr_losses, outputs\n ##################### inter-video loss #############################################\n\n feats_, labels_ = self._anchor_sampling(enc_l, pred_key, target_l, output_ul1_up, output_ul2_up, pseudo_logits1_up,pseudo_logits2_up,pseudo_label1_up,pseudo_label2_up,\n enc_feature_list1_up, enc_feature_list2_up, pseudo_label_list1_up, pseudo_label_list2_up,\n pseudo_logits_list1_up, pseudo_logits_list2_up, ul1_f_up, ul2_f_up, br1_f_up, br2_f_up,epoch)\n feats_norm = F.normalize(feats_, dim=-1)\n #loss\n loss_inter = self.weight_inter * self._contrastive(feats_norm, labels_.squeeze(0), queue=self.segment_queue)\n curr_losses['loss_inter'] = loss_inter\n total_loss = total_loss + loss_inter\n # if epoch < self.epoch_start_inter:\n return total_loss, curr_losses, outputs\n\n\n\n\n\n\n else:\n raise ValueError(\"No such mode {}\".format(self.mode))\n\n\n\n\n def _contrastive(self, X_anchor, y_anchor, queue=None):\n anchor_num, n_view = X_anchor.shape[0], X_anchor.shape[1] # 22*46*256 anchor_num:batch中所有class的个数, n_view:每个class中sample的个数\n\n y_anchor = y_anchor.contiguous().view(-1, 1) #22\n anchor_count = n_view #每个class中sample的个数\n anchor_feature = torch.cat(torch.unbind(X_anchor, dim=1), dim=0)#unbind 从dim进行切片,并返回切片的结果,返回的结果里面没有dim这个维度 得到n_view个class_num*n_dim的tensor\n # 再进行cat,就是将所有sample的特征并了起来,结合起来相当于从每个class依次取一个sample,循环往复拼接了起来(22*46)*256\n # X_contrast, y_contrast = self._sample_negative(\n # queue) # 将19*1000*256的memory变成了19000*256的memopry,标签也是按顺序 y则为1000个0接1000个1接1000个2\n # y_contrast = y_contrast.contiguous().view(-1, 1) # 19*1000\n # contrast_count = 1\n # contrast_feature = X_contrast # memory的特征(19*1000)*256\n\n contrast_feature = queue.view(-1, queue.shape[-1]) #将19*1000*256的memory变成了19000*256的memopry,标签也是按顺序 y则为1000个0接1000个1接1000个2\n y_contrast = torch.arange(self.num_classes).unsqueeze(1).repeat(1, self.queue_len)\n y_contrast =y_contrast.contiguous().view(-1, 1).cuda() #19000\n contrast_count = 1\n\n mask = torch.eq(y_anchor, y_contrast.T).float() #torch.eq对两个tensor逐元素比较 个位置的0 1 #把一横一竖的tensor比较得到N*N的tensor,即标签一致的位置为1 22*19000\n mask = mask.repeat(anchor_count, contrast_count).cuda() # 将22*19000扩展到(22*49)*19000,所有anchor和sample的对应关系,所有正样本,即所有标签一致的对\n anchor_dot_contrast = torch.div(torch.matmul(anchor_feature, contrast_feature.T), self.temperature) #(22*46)*256 * 256*(19*1000) = (22*46)*(19*1000) div除法除以temperature,每个anchor与memory中每个sample相乘的结果\n logits_max, _ = torch.max(anchor_dot_contrast, dim=1, keepdim=True)\n logits = anchor_dot_contrast - logits_max.detach() #减去最大相似度 1012*19000\n\n anchor_size = mask.shape[0]\n # positive sample\n pos_indice=torch.ones(anchor_size, self.queue_len)\n for i in range(anchor_size): pos_indice[i]=torch.randperm(self.queue_len)\n pos_indice=pos_indice[:, :self.pos_sample_num].long().flatten()\n pos_rand_x = torch.arange(anchor_size).unsqueeze(1).repeat([1, self.pos_sample_num]).flatten()\n pos_mask_all = mask.nonzero()[:, 1].view(anchor_size, -1)\n pos_rand_y = pos_mask_all[pos_rand_x, pos_indice]\n pos_sample_mask = torch.zeros_like(mask)\n pos_sample_mask[pos_rand_x, pos_rand_y] = 1\n\n\n # negative sample\n neg_mask = 1 - mask # 所有标签不一致的pair\n neg_indice = torch.ones(anchor_size, self.queue_len * (self.num_classes - 1))\n for i in range(anchor_size): neg_indice[i] = torch.randperm(self.queue_len * (self.num_classes - 1))\n neg_indice = neg_indice[:, :self.neg_sample_num].long().flatten()\n neg_rand_x = torch.arange(anchor_size).unsqueeze(1).repeat([1, self.neg_sample_num]).flatten()\n neg_mask_all = neg_mask.nonzero()[:, 1].view(anchor_size, -1)\n neg_rand_y = neg_mask_all[neg_rand_x, neg_indice]\n neg_sample_mask = torch.zeros_like(neg_mask)\n neg_sample_mask[neg_rand_x, neg_rand_y] = 1\n\n neg_logits = torch.exp(logits) * neg_sample_mask\n neg_logits = neg_logits.sum(1, keepdim=True) #每个anchor所有负样本的和(22*46)*1\n\n exp_logits = torch.exp(logits) #1012*19000\n\n log_prob = logits - torch.log(exp_logits + neg_logits) #1012*19000+1012*1 把每个sample都与neg的和相加,\n # 在下面的计算中与pos的mask一乘则能得到infonce的分母exp(pos)+sum(exp(neg)),因为infonce每一个pos都要与所有neg相加,而不是pos的和加neg的和\n\n mean_log_prob_pos = (pos_sample_mask * log_prob).sum(1) / pos_sample_mask.sum(1)\n\n loss = - (self.temperature / self.base_temperature) * mean_log_prob_pos\n loss = loss.mean()\n\n return loss\n def xent_targets(self, A):\n B, N = A.shape[:2] #A=aar B N N\n key = '%s:%sx%s' % (str(A.device), B,N) #CUDA:0:4X1600\n\n if key not in self._xent_targets:\n I = torch.arange(A.shape[-1])[None].repeat(B, 1)\n # arrange生成0-1599的数字,[None]将他变成1*1600维的矩阵,再repeat变成B*1600的矩阵,每行都为0-1599的数字\n self._xent_targets[key] = I.view(-1).to(A.device) #0.....1599,0,....1599,0,...1599,0....1599\n\n return self._xent_targets[key]\n def concat_all_gather(self, tensor):\n \"\"\"\n Performs all_gather operation on the provided tensors.\n *** Warning ***: torch.distributed.all_gather has no gradient.\n \"\"\"\n with torch.no_grad():\n tensors_gather = [torch.ones_like(tensor)\n for _ in range(torch.distributed.get_world_size())]\n torch.distributed.all_gather(tensors_gather, tensor, async_op=False)\n\n output = torch.cat(tensors_gather, dim=0)\n return output\n\n def get_backbone_params(self):\n return self.encoder.get_backbone_params()\n\n def get_other_params(self):\n if self.mode == 'supervised':\n return chain(self.encoder.get_module_params(), self.classifier.parameters())\n elif self.mode == 'semi':\n return chain(self.encoder.get_module_params(), self.classifier.parameters(), self.project.parameters())\n else:\n raise ValueError(\"No such mode {}\".format(self.mode))\n\n def _dequeue_and_enqueue(self, keys, labels, preds,\n segment_queue, segment_queue_ptr):\n with torch.no_grad():\n batch_size = keys.shape[0]\n feat_dim = keys.shape[1]\n class_num = preds.shape[1]\n\n # labels = labels[:, ::self.network_stride, ::self.network_stride]\n labels_down = F.interpolate(labels.float().unsqueeze(1),\n size=(keys.shape[2], keys.shape[3]),\n mode='nearest').squeeze(1)\n probs=torch.softmax(preds, dim=1)\n _, pred_labels = torch.max(probs,dim=1)\n for bs in range(batch_size):\n this_feat = keys[bs].contiguous().view(feat_dim, -1).T\n this_label = labels_down[bs].contiguous().view(-1)\n this_label_ids = torch.unique(this_label)\n this_label_ids = [x for x in this_label_ids if x < 255]\n this_preds = pred_labels[bs].contiguous().view(-1)\n this_probs = probs[bs].contiguous().view(class_num,-1)\n\n for lb in this_label_ids:\n # idxs = (this_label == lb).nonzero()\n lb=lb.long()\n idxs_easy = ((this_label == lb).float() * (this_preds == lb).float()).nonzero().squeeze(-1)\n new_feat = this_feat[idxs_easy, :]\n # new_weight = torch.softmax(torch.cat([weight_easy, weight_hard]), dim=0)\n feat = torch.mean(new_feat, dim=0)\n ptr = int(segment_queue_ptr[lb])\n K=idxs_easy.shape[0]\n if ptr+K <= self.queue_len:\n segment_queue[lb, ptr:ptr + K, :] = F.normalize(this_feat[idxs_easy, :], dim=1)\n segment_queue_ptr[lb] = segment_queue_ptr[lb] + K\n elif ptr < self.queue_len and ptr+K > self.queue_len:\n permK = torch.randperm(K)\n segment_queue[lb, ptr:, :] = F.normalize(this_feat[permK[:(self.queue_len - ptr)], :], dim=1)\n segment_queue_ptr[lb] = self.queue_len\n elif ptr == self.queue_len:\n segment_queue[lb, :, :] =torch.cat([segment_queue[lb, 1:, :], F.normalize(feat.unsqueeze(0), dim=1)], 0)\n def _anchor_sampling(self, enc_l, pred_key,target_l, output_ul1_up, output_ul2_up,pseudo_logits1_up,pseudo_logits2_up, pseudo_label1_up, pseudo_label2_up, enc_feature_list1_up, enc_feature_list2_up, pseudo_label_list1_up, pseudo_label_list2_up,\n pseudo_logits_list1_up, pseudo_logits_list2_up,ul1_f_up, ul2_f_up,br1_f_up, br2_f_up ,epoch):\n # prob_l = F.softmax(pred_key, 1).max(1)[0].detach()\n b,c,w,h=output_ul1_up.size()\n n_anchor = self.max_samples\n feats_ = torch.zeros(0, n_anchor, c).cuda()\n labels_ = torch.zeros(0).cuda()\n\n alpha_t=20\n easy_thresh=0.95\n hard_thresh=0.85\n # with torch.no_grad():\n # # prob = torch.softmax(enc_feature_list1_up, dim=1)\n # entropy = -torch.sum(pseudo_logits_list1_up * torch.log(pseudo_logits_list1_up + 1e-10), dim=1)\n # low_thresh = np.percentile(\n # entropy.cpu().numpy().flatten(), alpha_t\n # )\n\n # supervised anchor sample\n target_l_down=F.interpolate(target_l.float().unsqueeze(1), size=enc_l.size()[2:], mode='nearest').squeeze(1)\n for idx in range(b):\n this_feat_l = enc_l[idx].contiguous().view(enc_l.shape[1], -1).permute(1, 0)\n this_y_pred = pred_key[idx].max(0)[1].contiguous().view(-1)\n this_y_l = target_l_down[idx].contiguous().view(-1)\n this_classes_l = torch.unique(this_y_l)\n this_classes_l = [x for x in this_classes_l if x != self.ignore_index]\n this_classes_l = [x for x in this_classes_l if (this_y_l == x).nonzero().shape[0] > n_anchor] #删除样本数太少的样本\n for cls_id in this_classes_l:\n hard_indices = ((this_y_l == cls_id) & (this_y_pred != cls_id)).nonzero().squeeze(1) #预测与标签不一致的anchor\n easy_indices = ((this_y_l == cls_id) & (this_y_pred == cls_id)).nonzero().squeeze(1) #预测与标签一致的anchor\n num_hard = hard_indices.shape[0]\n num_easy = easy_indices.shape[0]\n\n if num_hard >= n_anchor / 2 and num_easy >= n_anchor / 2:\n num_hard_keep = n_anchor // 2\n num_easy_keep = n_anchor - num_hard_keep\n elif num_hard >= n_anchor / 2:\n num_easy_keep = num_easy\n num_hard_keep = n_anchor - num_easy_keep\n elif num_easy >= n_anchor / 2:\n num_hard_keep = num_hard\n num_easy_keep = n_anchor - num_hard_keep\n else:\n # Log.info('this shoud be never touched! {} {} {}'.format(num_hard, num_easy, n_view))\n raise Exception\n perm = torch.randperm(num_hard)\n hard_indices = hard_indices[perm[:num_hard_keep]]\n perm = torch.randperm(num_easy)\n easy_indices = easy_indices[perm[:num_easy_keep]]\n # indices = torch.cat((hard_indices, easy_indices), dim=0)\n this_class_feat = torch.cat([this_feat_l[hard_indices, :], this_feat_l[easy_indices, :]], 0)\n feats_ = torch.cat([feats_, this_class_feat.unsqueeze(0)], 0)\n labels_ = torch.cat([labels_, cls_id.unsqueeze(0)], 0)\n\n # # unsupervised anchor sample\n if epoch >= 50:\n for idx in range(b):\n inx_mask = torch.ones([h, w], device=pseudo_logits1_up.device)\n x_ul1_mask_idx = inx_mask.clone()\n x_ul1_mask_idx[ul1_f_up[0, idx]:br1_f_up[0, idx], ul1_f_up[1, idx]:br1_f_up[1, idx]] = 0\n\n x_ul1_anchor_idx = (x_ul1_mask_idx*(pseudo_logits1_up[idx]>=easy_thresh)).nonzero()\n x_ul1_anchors_feat_idx = output_ul1_up[idx, :, x_ul1_anchor_idx[:, 0], x_ul1_anchor_idx[:, 1]].permute(1, 0)\n x_ul1_anchors_lb_idx = pseudo_label1_up[idx, x_ul1_anchor_idx[:, 0], x_ul1_anchor_idx[:, 1]]\n\n pseudo_logits_list_max, max_logit_idx_of_12 = torch.max(torch.stack([pseudo_logits_list1_up[idx],pseudo_logits_list2_up[idx]],0),0)\n enc_feature_together=torch.stack([enc_feature_list1_up[idx],enc_feature_list2_up[idx]],0)\n enc_feature_max=enc_feature_together[max_logit_idx_of_12, range(enc_feature_together.shape[1]), :]\n\n easy_anchor_idx = ((pseudo_label_list1_up[idx] == pseudo_label_list2_up[idx])*(pseudo_logits_list_max>=easy_thresh)).nonzero().squeeze(-1)\n easy_anchor_feat_idx = enc_feature_max[easy_anchor_idx, :]\n easy_anchor_prob_idx = pseudo_logits_list_max[easy_anchor_idx]\n easy_anchor_lb_idx = pseudo_label_list1_up[idx][easy_anchor_idx]\n\n random_ul_anchor_feat = torch.cat(\n [x_ul1_anchors_feat_idx, easy_anchor_feat_idx], 0)\n random_ul_anchor_lb = torch.cat(\n [x_ul1_anchors_lb_idx, easy_anchor_lb_idx], 0)\n\n hard_ul_anchor_idx = ((pseudo_label_list1_up[idx] != pseudo_label_list2_up[idx])*(pseudo_logits_list_max>=hard_thresh)).nonzero().squeeze(-1)\n hard_ul_anchor_feat = enc_feature_max[hard_ul_anchor_idx, :]\n hard_ul_anchor_lb = pseudo_label_list1_up[idx][hard_ul_anchor_idx]\n\n this_classes = torch.unique(torch.cat([hard_ul_anchor_lb, random_ul_anchor_lb]))\n this_classes = [x for x in this_classes if x != self.ignore_index]\n # this_classes = [x for x in this_classes if self.segment_queue_ptr[x] == self.queue_len]\n this_classes = [x for x in this_classes if (random_ul_anchor_lb == x).float().sum() + (\n hard_ul_anchor_lb == x).float().sum() > n_anchor]\n for cls_id in this_classes:\n hard_indices = (hard_ul_anchor_lb == cls_id).nonzero().squeeze(-1)\n random_indices = (random_ul_anchor_lb == cls_id).nonzero().squeeze(-1)\n num_hard = hard_indices.shape[0]\n num_random = random_indices.shape[0]\n if num_hard >= n_anchor / 2 and num_random >= n_anchor / 2:\n num_hard_keep = n_anchor // 2\n num_random_keep = n_anchor - num_hard_keep\n elif num_hard >= n_anchor / 2:\n num_random_keep = num_random\n num_hard_keep = n_anchor - num_random_keep\n elif num_random >= n_anchor / 2:\n num_hard_keep = num_hard\n num_random_keep = n_anchor - num_hard_keep\n else:\n raise Exception('this shoud be never touched! {} {} {}'.format(num_hard, num_random, n_anchor))\n perm = torch.randperm(num_hard)\n hard_indices = hard_indices[perm[:num_hard_keep]]\n perm = torch.randperm(num_random)\n random_indices = random_indices[perm[:num_random_keep]]\n # indices = torch.cat((hard_indices, random_indices), dim=0)\n this_class_feat = torch.cat(\n [hard_ul_anchor_feat[hard_indices, :], random_ul_anchor_feat[random_indices, :]], 0)\n feats_ = torch.cat([feats_, this_class_feat.unsqueeze(0)], 0)\n labels_ = torch.cat([labels_, cls_id.unsqueeze(0)], 0)\n\n\n return feats_, labels_",
"import random\nimport numpy as np\nimport os\nimport json\nimport argparse\nimport torch\nimport dataloaders\n# from models.model_reco import VCL\nfrom models.model_vid import VCL\nimport math\nimport copy\nfrom utils import Logger\nfrom trainer_vid import TrainerVid\nfrom trainer import Trainer\nimport torch.nn.functional as F\nfrom utils.losses import abCE_loss, CE_loss, consistency_weight\n\nimport torch.multiprocessing as mp\nimport torch.distributed as dist\n\n\ndef get_instance(module, name, config, *args):\n # GET THE CORRESPONDING CLASS / FCT\n return getattr(module, config[name]['type'])(*args, **config[name]['args'])\n\n\ndef main(gpu, ngpus_per_node, config, resume, test):\n if gpu == 0:\n train_logger = Logger()\n test_logger = Logger()\n else:\n train_logger = None\n test_logger = None\n\n config['rank'] = gpu + ngpus_per_node * config['n_node']\n # iter_per_epoch = 86\n iter_per_epoch = config['n_labeled_examples'] * config['n_unlabeled_ratio'] // config['train_unsupervised'][\n 'batch_size']\n torch.cuda.set_device(gpu)\n assert config['train_supervised']['batch_size'] % config['n_gpu'] == 0\n assert config['train_unsupervised']['batch_size'] % config['n_gpu'] == 0\n assert config['train_vid']['batch_size'] % config['n_gpu'] == 0\n assert config['val_loader']['batch_size'] % config['n_gpu'] == 0\n config['train_supervised']['batch_size'] = int(config['train_supervised']['batch_size'] / config['n_gpu'])\n config['train_unsupervised']['batch_size'] = int(config['train_unsupervised']['batch_size'] / config['n_gpu'])\n config['train_vid']['batch_size'] = int(config['train_vid']['batch_size'] / config['n_gpu'])\n config['val_loader']['batch_size'] = int(config['val_loader']['batch_size'] / config['n_gpu'])\n config['train_supervised']['num_workers'] = int(config['train_supervised']['num_workers'] / config['n_gpu'])\n config['train_unsupervised']['num_workers'] = int(config['train_unsupervised']['num_workers'] / config['n_gpu'])\n config['train_vid']['num_workers'] = int(config['train_vid']['num_workers'] / config['n_gpu'])\n config['val_loader']['num_workers'] = int(config['val_loader']['num_workers'] / config['n_gpu'])\n dist.init_process_group(backend='nccl', init_method=config['dist_url'], world_size=config['world_size'],\n rank=config['rank'])\n\n seed = config['random_seed']\n\n np.random.seed(seed)\n random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.\n\n # DATA LOADERS\n config['train_supervised']['n_labeled_examples'] = config['n_labeled_examples']\n config['train_supervised']['n_unlabeled_ratio'] = config['n_unlabeled_ratio']\n config['train_vid']['n_labeled_examples'] = config['n_labeled_examples']\n config['train_vid']['n_unlabeled_ratio'] = config['n_unlabeled_ratio']\n config['train_vid']['clip_size'] = config['clip_size']\n config['train_unsupervised']['n_labeled_examples'] = config['n_labeled_examples']\n config['train_unsupervised']['n_unlabeled_ratio'] = config['n_unlabeled_ratio']\n config['train_unsupervised']['use_weak_lables'] = config['use_weak_lables']\n config['train_supervised']['data_dir'] = config['data_dir']\n config['train_unsupervised']['data_dir'] = config['data_dir']\n config['train_vid']['data_dir'] = config['data_dir']\n config['val_loader']['data_dir'] = config['data_dir']\n config['train_supervised']['datalist'] = config['datalist']\n config['train_unsupervised']['datalist'] = config['datalist']\n config['train_vid']['datalist'] = config['datalist']\n config['val_loader']['datalist'] = config['datalist']\n config['test_loader'] = copy.deepcopy(config['val_loader'])\n config['test_loader']['split'] = 'test'\n config['test_loader']['num_workers'] = 1\n if config['dataset'] == 'voc':\n sup_dataloader = dataloaders.VOC\n unsup_dataloader = dataloaders.PairVOC\n elif config['dataset'] == 'cityscapes':\n sup_dataloader = dataloaders.City\n unsup_dataloader = dataloaders.PairCity\n elif config['dataset'] == 'thermal':\n sup_dataloader = dataloaders.Thermal\n unsup_dataloader = dataloaders.PairThermal\n elif config['dataset'] == 'thermalseq':\n sup_dataloader = dataloaders.ThermalSeq\n unsup_dataloader = dataloaders.PairThermalSeq\n elif config['dataset'] == 'thermalour':\n sup_dataloader = dataloaders.ThermalOur\n unsup_dataloader = dataloaders.PairThermalOur\n elif config['dataset'] == 'thermalvid':\n sup_dataloader = dataloaders.ThermalVid\n unsup_dataloader = dataloaders.PairThermalVid\n vid_loader = dataloaders.ClipThermalVid\n\n supervised_loader = sup_dataloader(config['train_supervised'])\n unsupervised_loader = unsup_dataloader(config['train_unsupervised'])\n clip_loader = vid_loader(config['train_vid'])\n val_loader = sup_dataloader(config['val_loader'])\n test_loader = sup_dataloader(config['test_loader'])\n\n sup_loss = CE_loss\n model = VCL(num_classes=val_loader.dataset.num_classes, conf=config['model'],\n sup_loss=sup_loss, ignore_index=val_loader.dataset.ignore_index)\n if gpu == 0:\n print(f'\\n{model}\\n')\n\n # TRAINING\n trainer = TrainerVid(\n model=model,\n resume=resume,\n config=config,\n supervised_loader=supervised_loader,\n unsupervised_loader=unsupervised_loader,\n clip_loader=clip_loader,\n val_loader=val_loader,\n test_loader=test_loader,\n iter_per_epoch=iter_per_epoch,\n train_logger=train_logger,\n test_logger=test_logger,\n gpu=gpu,\n test=test)\n\n trainer.train()\n\n\ndef find_free_port():\n import socket\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # Binding to port 0 will cause the OS to find an available port for us\n sock.bind((\"\", 0))\n port = sock.getsockname()[1]\n sock.close()\n # NOTE: there is still a chance the port could be taken by other processes.\n\n return port\n\n\nif __name__ == '__main__':\n # PARSE THE ARGS\n os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'\n parser = argparse.ArgumentParser(description='PyTorch Training')\n parser.add_argument('-c', '--config', default='configs/thermalseq_cac_deeplabv3+_resnet101_1over8_datalist0.json',type=str,\n help='Path to the config file')\n # parser.add_argument('-r', '--resume', default='runs/thermalvid_cac_deeplabv3+_resnet50_1over4_datalist0/04-20_15-56/best_model.pth', type=str,\n # help='Path to the .pth model checkpoint to resume training')\n parser.add_argument('-r', '--resume', default='', type=str,\n help='Path to the .pth model checkpoint to resume training')\n parser.add_argument('-t', '--test', default=False, type=bool,\n help='whether to test')\n args = parser.parse_args()\n\n config = json.load(open(args.config))\n torch.backends.cudnn.benchmark = True\n # port = find_free_port()\n port = '52234'\n config['dist_url'] = f\"tcp://127.0.0.1:{port}\"\n config['n_node'] = 0 # only support 1 node\n config['world_size'] = config['n_gpu']\n mp.spawn(main, nprocs=config['n_gpu'], args=(config['n_gpu'], config, args.resume, args.test))\n\n\n\n",
"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author: Donny You([email protected])\n\n\nimport math\nimport torch.nn as nn\nfrom collections import OrderedDict\n\nfrom models.backbones.module_helper import ModuleHelper\n\n\nmodel_urls = {\n 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n}\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, norm_type=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = ModuleHelper.BatchNorm2d(norm_type=norm_type)(planes)\n self.relu = nn.ReLU(inplace=False)#True\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = ModuleHelper.BatchNorm2d(norm_type=norm_type)(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, norm_type=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = ModuleHelper.BatchNorm2d(norm_type=norm_type)(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = ModuleHelper.BatchNorm2d(norm_type=norm_type)(planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.bn3 = ModuleHelper.BatchNorm2d(norm_type=norm_type)(planes * 4)\n self.relu = nn.ReLU(inplace=False)#True\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n\n def __init__(self, block, layers, num_classes=1000, deep_base=False, norm_type=None):\n super(ResNet, self).__init__()\n self.inplanes = 128 if deep_base else 64\n if deep_base:\n self.prefix = nn.Sequential(OrderedDict([\n ('conv1', nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False)),\n ('bn1', ModuleHelper.BatchNorm2d(norm_type=norm_type)(64)),\n ('relu1', nn.ReLU(inplace=False)),\n ('conv2', nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False)),\n ('bn2', ModuleHelper.BatchNorm2d(norm_type=norm_type)(64)),\n ('relu2', nn.ReLU(inplace=False)),\n ('conv3', nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1, bias=False)),\n ('bn3', ModuleHelper.BatchNorm2d(norm_type=norm_type)(self.inplanes)),\n ('relu3', nn.ReLU(inplace=False))]\n ))\n else:\n self.prefix = nn.Sequential(OrderedDict([\n ('conv1', nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)),\n ('bn1', ModuleHelper.BatchNorm2d(norm_type=norm_type)(self.inplanes)),\n ('relu', nn.ReLU(inplace=False))]\n ))\n\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1, ceil_mode=False) # change.\n\n self.layer1 = self._make_layer(block, 64, layers[0], norm_type=norm_type)\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2, norm_type=norm_type)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2, norm_type=norm_type)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2, norm_type=norm_type)\n self.avgpool = nn.AvgPool2d(7, stride=1)\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, ModuleHelper.BatchNorm2d(norm_type=norm_type, ret_cls=True)):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_layer(self, block, planes, blocks, stride=1, norm_type=None):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n ModuleHelper.BatchNorm2d(norm_type=norm_type)(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample, norm_type=norm_type))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, norm_type=norm_type))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.prefix(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n\n return x\n\n\ndef resnet18(num_classes=1000, pretrained=None, norm_type='batchnorm', **kwargs):\n \"\"\"Constructs a ResNet-18 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on Places\n norm_type (str): choose norm type\n \"\"\"\n model = ResNet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes, deep_base=False, norm_type=norm_type)\n model = ModuleHelper.load_model(model, pretrained=pretrained)\n return model\n\ndef deepbase_resnet18(num_classes=1000, pretrained=None, norm_type='batchnorm', **kwargs):\n \"\"\"Constructs a ResNet-18 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on Places\n \"\"\"\n model = ResNet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes, deep_base=True, norm_type=norm_type)\n model = ModuleHelper.load_model(model, pretrained=pretrained)\n return model\n\ndef resnet34(num_classes=1000, pretrained=None, norm_type='batchnorm', **kwargs):\n \"\"\"Constructs a ResNet-34 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on Places\n \"\"\"\n model = ResNet(BasicBlock, [3, 4, 6, 3], num_classes=num_classes, deep_base=False, norm_type=norm_type)\n model = ModuleHelper.load_model(model, pretrained=pretrained)\n return model\n\ndef deepbase_resnet34(num_classes=1000, pretrained=None, norm_type='batchnorm', **kwargs):\n \"\"\"Constructs a ResNet-34 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on Places\n \"\"\"\n model = ResNet(BasicBlock, [3, 4, 6, 3], num_classes=num_classes, deep_base=True, norm_type=norm_type)\n model = ModuleHelper.load_model(model, pretrained=pretrained)\n return model\n\ndef resnet50(num_classes=1000, pretrained=None, norm_type='batchnorm', **kwargs):\n# def resnet50(num_classes=1000, pretrained=None, norm_type='encsync_batchnorm', **kwargs):\n \"\"\"Constructs a ResNet-50 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on Places\n # \"\"\"\n # print(\"entered\")\n # input()\n model = ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, deep_base=False, norm_type=norm_type)\n model = ModuleHelper.load_model(model, pretrained=pretrained)\n return model\n\ndef deepbase_resnet50(num_classes=1000, pretrained=None, norm_type='batchnorm', **kwargs):\n# def deepbase_resnet50(num_classes=1000, pretrained=None, norm_type='encsync_batchnorm', **kwargs):\n# def deepbase_resnet50(num_classes=1000, pretrained=None, norm_type='lib', **kwargs):\n \"\"\"Constructs a ResNet-50 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on Places\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, deep_base=True, norm_type=norm_type)\n model = ModuleHelper.load_model(model, pretrained=pretrained)\n return model\n\ndef resnet101(num_classes=1000, pretrained=None, norm_type='batchnorm', **kwargs):\n \"\"\"Constructs a ResNet-101 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on Places\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes, deep_base=False, norm_type=norm_type)\n model = ModuleHelper.load_model(model, pretrained=pretrained)\n return model\n\ndef deepbase_resnet101(num_classes=1000, pretrained=None, norm_type='batchnorm', **kwargs):\n \"\"\"Constructs a ResNet-101 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on Places\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes, deep_base=True, norm_type=norm_type)\n model = ModuleHelper.load_model(model, pretrained=pretrained)\n return model\n\ndef resnet152(num_classes=1000, pretrained=None, norm_type='batchnorm', **kwargs):\n \"\"\"Constructs a ResNet-152 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on Places\n \"\"\"\n model = ResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes, deep_base=False, norm_type=norm_type)\n model = ModuleHelper.load_model(model, pretrained=pretrained)\n return model\n\ndef deepbase_resnet152(num_classes=1000, pretrained=None, norm_type='batchnorm', **kwargs):\n \"\"\"Constructs a ResNet-152 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on Places\n \"\"\"\n model = ResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes, deep_base=True, norm_type=norm_type)\n model = ModuleHelper.load_model(model, pretrained=pretrained)\n return model\n",
"import random\nimport numpy as np\nimport os\nimport json\nimport argparse\nimport torch\nimport dataloaders\n# from models.model_reco import VCL\nfrom models.model_vid import VCL\nimport math\nimport copy\nfrom utils import Logger\nfrom trainer_vid import TrainerVid\nfrom trainer import Trainer\nimport torch.nn.functional as F\nfrom utils.losses import abCE_loss, CE_loss, consistency_weight\n\nimport torch.multiprocessing as mp\nimport torch.distributed as dist\n\n\ndef get_instance(module, name, config, *args):\n # GET THE CORRESPONDING CLASS / FCT\n return getattr(module, config[name]['type'])(*args, **config[name]['args'])\n\n\ndef main(gpu, ngpus_per_node, config, resume, test):\n if gpu == 0:\n train_logger = Logger()\n test_logger = Logger()\n else:\n train_logger = None\n test_logger = None\n\n config['rank'] = gpu + ngpus_per_node * config['n_node']\n # iter_per_epoch = 86\n iter_per_epoch = config['n_labeled_examples'] * config['n_unlabeled_ratio'] // config['train_unsupervised'][\n 'batch_size']\n torch.cuda.set_device(gpu)\n assert config['train_supervised']['batch_size'] % config['n_gpu'] == 0\n assert config['train_unsupervised']['batch_size'] % config['n_gpu'] == 0\n assert config['train_vid']['batch_size'] % config['n_gpu'] == 0\n assert config['val_loader']['batch_size'] % config['n_gpu'] == 0\n config['train_supervised']['batch_size'] = int(config['train_supervised']['batch_size'] / config['n_gpu'])\n config['train_unsupervised']['batch_size'] = int(config['train_unsupervised']['batch_size'] / config['n_gpu'])\n config['train_vid']['batch_size'] = int(config['train_vid']['batch_size'] / config['n_gpu'])\n config['val_loader']['batch_size'] = int(config['val_loader']['batch_size'] / config['n_gpu'])\n config['train_supervised']['num_workers'] = int(config['train_supervised']['num_workers'] / config['n_gpu'])\n config['train_unsupervised']['num_workers'] = int(config['train_unsupervised']['num_workers'] / config['n_gpu'])\n config['train_vid']['num_workers'] = int(config['train_vid']['num_workers'] / config['n_gpu'])\n config['val_loader']['num_workers'] = int(config['val_loader']['num_workers'] / config['n_gpu'])\n dist.init_process_group(backend='nccl', init_method=config['dist_url'], world_size=config['world_size'],\n rank=config['rank'])\n\n seed = config['random_seed']\n\n np.random.seed(seed)\n random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.\n\n # DATA LOADERS\n config['train_supervised']['n_labeled_examples'] = config['n_labeled_examples']\n config['train_supervised']['n_unlabeled_ratio'] = config['n_unlabeled_ratio']\n config['train_vid']['n_labeled_examples'] = config['n_labeled_examples']\n config['train_vid']['n_unlabeled_ratio'] = config['n_unlabeled_ratio']\n config['train_vid']['clip_size'] = config['clip_size']\n config['train_unsupervised']['n_labeled_examples'] = config['n_labeled_examples']\n config['train_unsupervised']['n_unlabeled_ratio'] = config['n_unlabeled_ratio']\n config['train_unsupervised']['use_weak_lables'] = config['use_weak_lables']\n config['train_supervised']['data_dir'] = config['data_dir']\n config['train_unsupervised']['data_dir'] = config['data_dir']\n config['train_vid']['data_dir'] = config['data_dir']\n config['val_loader']['data_dir'] = config['data_dir']\n config['train_supervised']['datalist'] = config['datalist']\n config['train_unsupervised']['datalist'] = config['datalist']\n config['train_vid']['datalist'] = config['datalist']\n config['val_loader']['datalist'] = config['datalist']\n config['test_loader'] = copy.deepcopy(config['val_loader'])\n config['test_loader']['split'] = 'test'\n config['test_loader']['num_workers'] = 1\n if config['dataset'] == 'voc':\n sup_dataloader = dataloaders.VOC\n unsup_dataloader = dataloaders.PairVOC\n elif config['dataset'] == 'cityscapes':\n sup_dataloader = dataloaders.City\n unsup_dataloader = dataloaders.PairCity\n elif config['dataset'] == 'thermal':\n sup_dataloader = dataloaders.Thermal\n unsup_dataloader = dataloaders.PairThermal\n elif config['dataset'] == 'thermalseq':\n sup_dataloader = dataloaders.ThermalSeq\n unsup_dataloader = dataloaders.PairThermalSeq\n elif config['dataset'] == 'thermalour':\n sup_dataloader = dataloaders.ThermalOur\n unsup_dataloader = dataloaders.PairThermalOur\n elif config['dataset'] == 'thermalvid':\n sup_dataloader = dataloaders.ThermalVid\n unsup_dataloader = dataloaders.PairThermalVid\n vid_loader = dataloaders.ClipThermalVid\n\n supervised_loader = sup_dataloader(config['train_supervised'])\n unsupervised_loader = unsup_dataloader(config['train_unsupervised'])\n clip_loader = vid_loader(config['train_vid'])\n val_loader = sup_dataloader(config['val_loader'])\n test_loader = sup_dataloader(config['test_loader'])\n\n sup_loss = CE_loss\n model = VCL(num_classes=val_loader.dataset.num_classes, conf=config['model'],\n sup_loss=sup_loss, ignore_index=val_loader.dataset.ignore_index)\n if gpu == 0:\n print(f'\\n{model}\\n')\n\n # TRAINING\n trainer = TrainerVid(\n model=model,\n resume=resume,\n config=config,\n supervised_loader=supervised_loader,\n unsupervised_loader=unsupervised_loader,\n clip_loader=clip_loader,\n val_loader=val_loader,\n test_loader=test_loader,\n iter_per_epoch=iter_per_epoch,\n train_logger=train_logger,\n test_logger=test_logger,\n gpu=gpu,\n test=test)\n\n trainer.train()\n\n\ndef find_free_port():\n import socket\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # Binding to port 0 will cause the OS to find an available port for us\n sock.bind((\"\", 0))\n port = sock.getsockname()[1]\n sock.close()\n # NOTE: there is still a chance the port could be taken by other processes.\n\n return port\n\n\nif __name__ == '__main__':\n # PARSE THE ARGS\n os.environ['CUDA_VISIBLE_DEVICES'] = '3'\n parser = argparse.ArgumentParser(description='PyTorch Training')\n parser.add_argument('-c', '--config', default='configs/thermalvid_cac_deeplabv3+_resnet50_1over4_datalist0.json',type=str,\n help='Path to the config file')\n parser.add_argument('-r', '--resume', default='runs/thermalvid_cac_deeplabv3+_resnet50_1over4_datalist0/04-12_11-33/checkpoint.pth', type=str,\n help='Path to the .pth model checkpoint to resume training')\n # parser.add_argument('-r', '--resume', default='', type=str,\n # help='Path to the .pth model checkpoint to resume training')\n parser.add_argument('-t', '--test', default=True, type=bool,\n help='whether to test')\n args = parser.parse_args()\n\n config = json.load(open(args.config))\n torch.backends.cudnn.benchmark = True\n # port = find_free_port()\n port = '52234'\n config['dist_url'] = f\"tcp://127.0.0.1:{port}\"\n config['n_node'] = 0 # only support 1 node\n config['world_size'] = config['n_gpu']\n mp.spawn(main, nprocs=config['n_gpu'], args=(config['n_gpu'], config, args.resume, args.test))\n\n\n\n"
] |
[
[
"torch.div",
"torch.nn.Softmax",
"torch.nn.functional.softmax",
"torch.ones",
"torch.max",
"torch.zeros",
"torch.min",
"torch.pow",
"torch.bmm",
"torch.nn.L1Loss",
"torch.diag",
"torch.nn.MSELoss"
],
[
"torch.mean",
"torch.nn.functional.softmax",
"torch.max",
"torch.rand_like",
"torch.zeros",
"torch.randperm",
"torch.cat",
"torch.unique",
"torch.no_grad",
"torch.nn.CrossEntropyLoss",
"torch.softmax",
"torch.ones",
"torch.nn.Dropout",
"torch.eq",
"torch.einsum",
"torch.randn",
"torch.arange",
"torch.ones_like",
"torch.nn.Conv2d",
"torch.zeros_like",
"torch.exp",
"torch.log",
"torch.stack",
"torch.flip",
"torch.distributed.get_world_size",
"torch.nn.functional.normalize",
"torch.distributed.all_gather",
"torch.matmul",
"torch.unbind",
"torch.nn.init.kaiming_normal_"
],
[
"torch.distributed.init_process_group",
"torch.cuda.manual_seed",
"numpy.random.seed",
"torch.cuda.set_device",
"torch.manual_seed",
"torch.multiprocessing.spawn",
"torch.cuda.manual_seed_all"
],
[
"torch.nn.Sequential",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.MaxPool2d",
"torch.nn.AvgPool2d",
"torch.nn.ReLU"
],
[
"torch.distributed.init_process_group",
"torch.cuda.manual_seed",
"numpy.random.seed",
"torch.cuda.set_device",
"torch.manual_seed",
"torch.multiprocessing.spawn",
"torch.cuda.manual_seed_all"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
duncanriach-nvidia/tensorflow-models
|
[
"f95f014e6192434f405b7d6209c885072a3f6b6d",
"f95f014e6192434f405b7d6209c885072a3f6b6d",
"f95f014e6192434f405b7d6209c885072a3f6b6d",
"f95f014e6192434f405b7d6209c885072a3f6b6d",
"f95f014e6192434f405b7d6209c885072a3f6b6d",
"f95f014e6192434f405b7d6209c885072a3f6b6d",
"f95f014e6192434f405b7d6209c885072a3f6b6d"
] |
[
"research/object_detection/tpu_exporters/utils_test.py",
"official/projects/deepmac_maskrcnn/configs/deep_mask_head_rcnn_config_test.py",
"official/projects/vit/modeling/vit.py",
"official/vision/serving/detection_test.py",
"official/vision/beta/projects/centernet/modeling/centernet_model_test.py",
"official/projects/volumetric_models/tasks/semantic_segmentation_3d_test.py",
"official/projects/deepmac_maskrcnn/modeling/maskrcnn_model_test.py"
] |
[
"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Test for Utility functions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom six.moves import range\nimport tensorflow.compat.v1 as tf\n\nfrom object_detection.tpu_exporters import utils\n\n\nclass UtilsTest(tf.test.TestCase):\n\n def testBfloat16ToFloat32(self):\n bfloat16_tensor = tf.random.uniform([2, 3], dtype=tf.bfloat16)\n float32_tensor = utils.bfloat16_to_float32(bfloat16_tensor)\n self.assertEqual(float32_tensor.dtype, tf.float32)\n\n def testOtherDtypesNotConverted(self):\n int32_tensor = tf.ones([2, 3], dtype=tf.int32)\n converted_tensor = utils.bfloat16_to_float32(int32_tensor)\n self.assertEqual(converted_tensor.dtype, tf.int32)\n\n def testBfloat16ToFloat32Nested(self):\n tensor_dict = {\n 'key1': tf.random.uniform([2, 3], dtype=tf.bfloat16),\n 'key2': [\n tf.random.uniform([1, 2], dtype=tf.bfloat16) for _ in range(3)\n ],\n 'key3': tf.ones([2, 3], dtype=tf.int32),\n }\n tensor_dict = utils.bfloat16_to_float32_nested(tensor_dict)\n\n self.assertEqual(tensor_dict['key1'].dtype, tf.float32)\n for t in tensor_dict['key2']:\n self.assertEqual(t.dtype, tf.float32)\n self.assertEqual(tensor_dict['key3'].dtype, tf.int32)\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2022 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\"\"\"Check that the config is set correctly.\"\"\"\n\nimport tensorflow as tf\n\nfrom official.projects.deepmac_maskrcnn.configs import deep_mask_head_rcnn\n\n\nclass DeepMaskHeadRcnnConfigTest(tf.test.TestCase):\n\n def test_config(self):\n config = deep_mask_head_rcnn.deep_mask_head_rcnn_resnetfpn_coco()\n self.assertIsInstance(config.task, deep_mask_head_rcnn.DeepMaskHeadRCNNTask)\n\n def test_config_spinenet(self):\n config = deep_mask_head_rcnn.deep_mask_head_rcnn_spinenet_coco()\n self.assertIsInstance(config.task, deep_mask_head_rcnn.DeepMaskHeadRCNNTask)\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2022 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\"\"\"VisionTransformer models.\"\"\"\nimport tensorflow as tf\n\nfrom official.modeling import activations\nfrom official.projects.vit.modeling import nn_blocks\nfrom official.vision.modeling.backbones import factory\nfrom official.vision.modeling.layers import nn_layers\n\n\nlayers = tf.keras.layers\n\nVIT_SPECS = {\n 'vit-ti16':\n dict(\n hidden_size=192,\n patch_size=16,\n transformer=dict(mlp_dim=768, num_heads=3, num_layers=12),\n ),\n 'vit-s16':\n dict(\n hidden_size=384,\n patch_size=16,\n transformer=dict(mlp_dim=1536, num_heads=6, num_layers=12),\n ),\n 'vit-b16':\n dict(\n hidden_size=768,\n patch_size=16,\n transformer=dict(mlp_dim=3072, num_heads=12, num_layers=12),\n ),\n 'vit-b32':\n dict(\n hidden_size=768,\n patch_size=32,\n transformer=dict(mlp_dim=3072, num_heads=12, num_layers=12),\n ),\n 'vit-l16':\n dict(\n hidden_size=1024,\n patch_size=16,\n transformer=dict(mlp_dim=4096, num_heads=16, num_layers=24),\n ),\n 'vit-l32':\n dict(\n hidden_size=1024,\n patch_size=32,\n transformer=dict(mlp_dim=4096, num_heads=16, num_layers=24),\n ),\n 'vit-h14':\n dict(\n hidden_size=1280,\n patch_size=14,\n transformer=dict(mlp_dim=5120, num_heads=16, num_layers=32),\n ),\n 'vit-g14':\n dict(\n hidden_size=1664,\n patch_size=14,\n transformer=dict(mlp_dim=8192, num_heads=16, num_layers=48),\n ),\n}\n\n\nclass AddPositionEmbs(tf.keras.layers.Layer):\n \"\"\"Adds (optionally learned) positional embeddings to the inputs.\"\"\"\n\n def __init__(self, posemb_init=None, **kwargs):\n super().__init__(**kwargs)\n self.posemb_init = posemb_init\n\n def build(self, inputs_shape):\n pos_emb_shape = (1, inputs_shape[1], inputs_shape[2])\n self.pos_embedding = self.add_weight(\n 'pos_embedding', pos_emb_shape, initializer=self.posemb_init)\n\n def call(self, inputs, inputs_positions=None):\n # inputs.shape is (batch_size, seq_len, emb_dim).\n pos_embedding = tf.cast(self.pos_embedding, inputs.dtype)\n\n return inputs + pos_embedding\n\n\nclass TokenLayer(tf.keras.layers.Layer):\n \"\"\"A simple layer to wrap token parameters.\"\"\"\n\n def build(self, inputs_shape):\n self.cls = self.add_weight(\n 'cls', (1, 1, inputs_shape[-1]), initializer='zeros')\n\n def call(self, inputs):\n cls = tf.cast(self.cls, inputs.dtype)\n cls = cls + tf.zeros_like(inputs[:, 0:1]) # A hacky way to tile.\n x = tf.concat([cls, inputs], axis=1)\n return x\n\n\nclass Encoder(tf.keras.layers.Layer):\n \"\"\"Transformer Encoder.\"\"\"\n\n def __init__(self,\n num_layers,\n mlp_dim,\n num_heads,\n dropout_rate=0.1,\n attention_dropout_rate=0.1,\n kernel_regularizer=None,\n inputs_positions=None,\n init_stochastic_depth_rate=0.0,\n kernel_initializer='glorot_uniform',\n add_pos_embed=True,\n **kwargs):\n super().__init__(**kwargs)\n self._num_layers = num_layers\n self._mlp_dim = mlp_dim\n self._num_heads = num_heads\n self._dropout_rate = dropout_rate\n self._attention_dropout_rate = attention_dropout_rate\n self._kernel_regularizer = kernel_regularizer\n self._inputs_positions = inputs_positions\n self._init_stochastic_depth_rate = init_stochastic_depth_rate\n self._kernel_initializer = kernel_initializer\n self._add_pos_embed = add_pos_embed\n\n def build(self, input_shape):\n if self._add_pos_embed:\n self._pos_embed = AddPositionEmbs(\n posemb_init=tf.keras.initializers.RandomNormal(stddev=0.02),\n name='posembed_input')\n self._dropout = layers.Dropout(rate=self._dropout_rate)\n\n self._encoder_layers = []\n # Set layer norm epsilons to 1e-6 to be consistent with JAX implementation.\n # https://flax.readthedocs.io/en/latest/_autosummary/flax.deprecated.nn.LayerNorm.html\n for i in range(self._num_layers):\n encoder_layer = nn_blocks.TransformerEncoderBlock(\n inner_activation=activations.gelu,\n num_attention_heads=self._num_heads,\n inner_dim=self._mlp_dim,\n output_dropout=self._dropout_rate,\n attention_dropout=self._attention_dropout_rate,\n kernel_regularizer=self._kernel_regularizer,\n kernel_initializer=self._kernel_initializer,\n norm_first=True,\n stochastic_depth_drop_rate=nn_layers.get_stochastic_depth_rate(\n self._init_stochastic_depth_rate, i + 1, self._num_layers),\n norm_epsilon=1e-6)\n self._encoder_layers.append(encoder_layer)\n self._norm = layers.LayerNormalization(epsilon=1e-6)\n super().build(input_shape)\n\n def call(self, inputs, training=None):\n x = inputs\n if self._add_pos_embed:\n x = self._pos_embed(x, inputs_positions=self._inputs_positions)\n x = self._dropout(x, training=training)\n\n for encoder_layer in self._encoder_layers:\n x = encoder_layer(x, training=training)\n x = self._norm(x)\n return x\n\n def get_config(self):\n config = {\n 'num_layers': self._num_layers,\n 'mlp_dim': self._mlp_dim,\n 'num_heads': self._num_heads,\n 'dropout_rate': self._dropout_rate,\n 'attention_dropout_rate': self._attention_dropout_rate,\n 'kernel_regularizer': self._kernel_regularizer,\n 'inputs_positions': self._inputs_positions,\n 'init_stochastic_depth_rate': self._init_stochastic_depth_rate,\n 'kernel_initializer': self._kernel_initializer,\n 'add_pos_embed': self._add_pos_embed,\n }\n base_config = super().get_config()\n return base_config.update(config)\n\n\nclass VisionTransformer(tf.keras.Model):\n \"\"\"Class to build VisionTransformer family model.\"\"\"\n\n def __init__(self,\n mlp_dim=3072,\n num_heads=12,\n num_layers=12,\n attention_dropout_rate=0.0,\n dropout_rate=0.1,\n init_stochastic_depth_rate=0.0,\n input_specs=layers.InputSpec(shape=[None, None, None, 3]),\n patch_size=16,\n hidden_size=768,\n representation_size=0,\n classifier='token',\n kernel_regularizer=None,\n original_init=True):\n \"\"\"VisionTransformer initialization function.\"\"\"\n inputs = tf.keras.Input(shape=input_specs.shape[1:])\n\n x = layers.Conv2D(\n filters=hidden_size,\n kernel_size=patch_size,\n strides=patch_size,\n padding='valid',\n kernel_regularizer=kernel_regularizer,\n kernel_initializer='lecun_normal' if original_init else 'he_uniform')(\n inputs)\n if tf.keras.backend.image_data_format() == 'channels_last':\n rows_axis, cols_axis = (1, 2)\n else:\n rows_axis, cols_axis = (2, 3)\n # The reshape below assumes the data_format is 'channels_last,' so\n # transpose to that. Once the data is flattened by the reshape, the\n # data_format is irrelevant, so no need to update\n # tf.keras.backend.image_data_format.\n x = tf.transpose(x, perm=[0, 2, 3, 1])\n seq_len = (input_specs.shape[rows_axis] // patch_size) * (\n input_specs.shape[cols_axis] // patch_size)\n x = tf.reshape(x, [-1, seq_len, hidden_size])\n\n # If we want to add a class token, add it here.\n if classifier == 'token':\n x = TokenLayer(name='cls')(x)\n\n x = Encoder(\n num_layers=num_layers,\n mlp_dim=mlp_dim,\n num_heads=num_heads,\n dropout_rate=dropout_rate,\n attention_dropout_rate=attention_dropout_rate,\n kernel_regularizer=kernel_regularizer,\n kernel_initializer='glorot_uniform' if original_init else dict(\n class_name='TruncatedNormal', config=dict(stddev=.02)),\n init_stochastic_depth_rate=init_stochastic_depth_rate)(\n x)\n\n if classifier == 'token':\n x = x[:, 0]\n elif classifier == 'gap':\n x = tf.reduce_mean(x, axis=1)\n\n if representation_size:\n x = tf.keras.layers.Dense(\n representation_size,\n kernel_regularizer=kernel_regularizer,\n name='pre_logits',\n kernel_initializer='lecun_normal' if original_init else 'he_uniform')(\n x)\n x = tf.nn.tanh(x)\n else:\n x = tf.identity(x, name='pre_logits')\n endpoints = {\n 'pre_logits':\n tf.reshape(x, [-1, 1, 1, representation_size or hidden_size])\n }\n\n super(VisionTransformer, self).__init__(inputs=inputs, outputs=endpoints)\n\n\[email protected]_backbone_builder('vit')\ndef build_vit(input_specs,\n backbone_config,\n norm_activation_config,\n l2_regularizer=None):\n \"\"\"Build ViT model.\"\"\"\n del norm_activation_config\n backbone_type = backbone_config.type\n backbone_cfg = backbone_config.get()\n assert backbone_type == 'vit', (f'Inconsistent backbone type '\n f'{backbone_type}')\n backbone_cfg.override(VIT_SPECS[backbone_cfg.model_name])\n\n return VisionTransformer(\n mlp_dim=backbone_cfg.transformer.mlp_dim,\n num_heads=backbone_cfg.transformer.num_heads,\n num_layers=backbone_cfg.transformer.num_layers,\n attention_dropout_rate=backbone_cfg.transformer.attention_dropout_rate,\n dropout_rate=backbone_cfg.transformer.dropout_rate,\n init_stochastic_depth_rate=backbone_cfg.init_stochastic_depth_rate,\n input_specs=input_specs,\n patch_size=backbone_cfg.patch_size,\n hidden_size=backbone_cfg.hidden_size,\n representation_size=backbone_cfg.representation_size,\n classifier=backbone_cfg.classifier,\n kernel_regularizer=l2_regularizer,\n original_init=backbone_cfg.original_init)\n",
"# Copyright 2022 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\"\"\"Test for image detection export lib.\"\"\"\n\nimport io\nimport os\n\nfrom absl.testing import parameterized\nimport numpy as np\nfrom PIL import Image\nimport tensorflow as tf\n\nfrom official.core import exp_factory\nfrom official.vision import registry_imports # pylint: disable=unused-import\nfrom official.vision.serving import detection\n\n\nclass DetectionExportTest(tf.test.TestCase, parameterized.TestCase):\n\n def _get_detection_module(self, experiment_name, input_type):\n params = exp_factory.get_exp_config(experiment_name)\n params.task.model.backbone.resnet.model_id = 18\n params.task.model.detection_generator.nms_version = 'batched'\n detection_module = detection.DetectionModule(\n params,\n batch_size=1,\n input_image_size=[640, 640],\n input_type=input_type)\n return detection_module\n\n def _export_from_module(self, module, input_type, save_directory):\n signatures = module.get_inference_signatures(\n {input_type: 'serving_default'})\n tf.saved_model.save(module, save_directory, signatures=signatures)\n\n def _get_dummy_input(self, input_type, batch_size, image_size):\n \"\"\"Get dummy input for the given input type.\"\"\"\n h, w = image_size\n\n if input_type == 'image_tensor':\n return tf.zeros((batch_size, h, w, 3), dtype=np.uint8)\n elif input_type == 'image_bytes':\n image = Image.fromarray(np.zeros((h, w, 3), dtype=np.uint8))\n byte_io = io.BytesIO()\n image.save(byte_io, 'PNG')\n return [byte_io.getvalue() for b in range(batch_size)]\n elif input_type == 'tf_example':\n image_tensor = tf.zeros((h, w, 3), dtype=tf.uint8)\n encoded_jpeg = tf.image.encode_jpeg(tf.constant(image_tensor)).numpy()\n example = tf.train.Example(\n features=tf.train.Features(\n feature={\n 'image/encoded':\n tf.train.Feature(\n bytes_list=tf.train.BytesList(value=[encoded_jpeg])),\n })).SerializeToString()\n return [example for b in range(batch_size)]\n elif input_type == 'tflite':\n return tf.zeros((batch_size, h, w, 3), dtype=np.float32)\n\n @parameterized.parameters(\n ('image_tensor', 'fasterrcnn_resnetfpn_coco', [384, 384]),\n ('image_bytes', 'fasterrcnn_resnetfpn_coco', [640, 640]),\n ('tf_example', 'fasterrcnn_resnetfpn_coco', [640, 640]),\n ('tflite', 'fasterrcnn_resnetfpn_coco', [640, 640]),\n ('image_tensor', 'maskrcnn_resnetfpn_coco', [640, 640]),\n ('image_bytes', 'maskrcnn_resnetfpn_coco', [640, 384]),\n ('tf_example', 'maskrcnn_resnetfpn_coco', [640, 640]),\n ('tflite', 'maskrcnn_resnetfpn_coco', [640, 640]),\n ('image_tensor', 'retinanet_resnetfpn_coco', [640, 640]),\n ('image_bytes', 'retinanet_resnetfpn_coco', [640, 640]),\n ('tf_example', 'retinanet_resnetfpn_coco', [384, 640]),\n ('tflite', 'retinanet_resnetfpn_coco', [640, 640]),\n ('image_tensor', 'retinanet_resnetfpn_coco', [384, 384]),\n ('image_bytes', 'retinanet_spinenet_coco', [640, 640]),\n ('tf_example', 'retinanet_spinenet_coco', [640, 384]),\n ('tflite', 'retinanet_spinenet_coco', [640, 640]),\n )\n def test_export(self, input_type, experiment_name, image_size):\n tmp_dir = self.get_temp_dir()\n module = self._get_detection_module(experiment_name, input_type)\n\n self._export_from_module(module, input_type, tmp_dir)\n\n self.assertTrue(os.path.exists(os.path.join(tmp_dir, 'saved_model.pb')))\n self.assertTrue(\n os.path.exists(os.path.join(tmp_dir, 'variables', 'variables.index')))\n self.assertTrue(\n os.path.exists(\n os.path.join(tmp_dir, 'variables',\n 'variables.data-00000-of-00001')))\n\n imported = tf.saved_model.load(tmp_dir)\n detection_fn = imported.signatures['serving_default']\n\n images = self._get_dummy_input(\n input_type, batch_size=1, image_size=image_size)\n\n if input_type == 'tflite':\n processed_images = tf.zeros(image_size + [3], dtype=tf.float32)\n anchor_boxes = module._build_anchor_boxes()\n image_info = tf.convert_to_tensor(\n [image_size, image_size, [1.0, 1.0], [0, 0]], dtype=tf.float32)\n else:\n processed_images, anchor_boxes, image_info = module._build_inputs(\n tf.zeros((224, 224, 3), dtype=tf.uint8))\n image_shape = image_info[1, :]\n image_shape = tf.expand_dims(image_shape, 0)\n processed_images = tf.expand_dims(processed_images, 0)\n for l, l_boxes in anchor_boxes.items():\n anchor_boxes[l] = tf.expand_dims(l_boxes, 0)\n\n expected_outputs = module.model(\n images=processed_images,\n image_shape=image_shape,\n anchor_boxes=anchor_boxes,\n training=False)\n outputs = detection_fn(tf.constant(images))\n\n self.assertAllClose(outputs['num_detections'].numpy(),\n expected_outputs['num_detections'].numpy())\n\n def test_build_model_fail_with_none_batch_size(self):\n params = exp_factory.get_exp_config('retinanet_resnetfpn_coco')\n with self.assertRaisesRegex(\n ValueError, 'batch_size cannot be None for detection models.'):\n detection.DetectionModule(\n params, batch_size=None, input_image_size=[640, 640])\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2022 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\"\"\"Test for centernet detection model.\"\"\"\n\nfrom absl.testing import parameterized\nimport tensorflow as tf\n\nfrom official.vision.beta.projects.centernet.configs import backbones\nfrom official.vision.beta.projects.centernet.modeling import centernet_model\nfrom official.vision.beta.projects.centernet.modeling.backbones import hourglass\nfrom official.vision.beta.projects.centernet.modeling.heads import centernet_head\nfrom official.vision.beta.projects.centernet.modeling.layers import detection_generator\nfrom official.vision.configs import common\n\n\nclass CenterNetTest(parameterized.TestCase, tf.test.TestCase):\n\n def testBuildCenterNet(self):\n backbone = hourglass.build_hourglass(\n input_specs=tf.keras.layers.InputSpec(shape=[None, 512, 512, 3]),\n backbone_config=backbones.Backbone(type='hourglass'),\n norm_activation_config=common.NormActivation(use_sync_bn=True)\n )\n\n task_config = {\n 'ct_heatmaps': 90,\n 'ct_offset': 2,\n 'ct_size': 2,\n }\n\n input_levels = ['2_0', '2']\n\n head = centernet_head.CenterNetHead(\n task_outputs=task_config,\n input_specs=backbone.output_specs,\n input_levels=input_levels)\n\n detection_ge = detection_generator.CenterNetDetectionGenerator()\n\n model = centernet_model.CenterNetModel(\n backbone=backbone,\n head=head,\n detection_generator=detection_ge\n )\n\n outputs = model(tf.zeros((5, 512, 512, 3)))\n self.assertLen(outputs['raw_output'], 3)\n self.assertLen(outputs['raw_output']['ct_heatmaps'], 2)\n self.assertLen(outputs['raw_output']['ct_offset'], 2)\n self.assertLen(outputs['raw_output']['ct_size'], 2)\n self.assertEqual(outputs['raw_output']['ct_heatmaps'][0].shape,\n (5, 128, 128, 90))\n self.assertEqual(outputs['raw_output']['ct_offset'][0].shape,\n (5, 128, 128, 2))\n self.assertEqual(outputs['raw_output']['ct_size'][0].shape,\n (5, 128, 128, 2))\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2022 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for semantic segmentation task.\"\"\"\n\n# pylint: disable=unused-import\nimport functools\nimport os\n\nfrom absl.testing import parameterized\nimport orbit\nimport tensorflow as tf\n\nfrom official.common import registry_imports # pylint: disable=unused-import\nfrom official.core import exp_factory\nfrom official.modeling import optimization\nfrom official.projects.volumetric_models.evaluation import segmentation_metrics\nfrom official.projects.volumetric_models.modeling import backbones\nfrom official.projects.volumetric_models.modeling import decoders\nfrom official.projects.volumetric_models.tasks import semantic_segmentation_3d as img_seg_task\nfrom official.vision.dataloaders import tfexample_utils\n\n\nclass SemanticSegmentationTaskTest(tf.test.TestCase, parameterized.TestCase):\n\n def setUp(self):\n super().setUp()\n data_dir = os.path.join(self.get_temp_dir(), 'data')\n tf.io.gfile.makedirs(data_dir)\n self._data_path = os.path.join(data_dir, 'data.tfrecord')\n # pylint: disable=g-complex-comprehension\n examples = [\n tfexample_utils.create_3d_image_test_example(\n image_height=32, image_width=32, image_volume=32, image_channel=2)\n for _ in range(20)\n ]\n # pylint: enable=g-complex-comprehension\n tfexample_utils.dump_to_tfrecord(self._data_path, tf_examples=examples)\n\n @parameterized.parameters(('seg_unet3d_test',))\n def test_task(self, config_name):\n config = exp_factory.get_exp_config(config_name)\n config.task.train_data.input_path = self._data_path\n config.task.train_data.global_batch_size = 4\n config.task.train_data.shuffle_buffer_size = 4\n config.task.validation_data.input_path = self._data_path\n config.task.validation_data.shuffle_buffer_size = 4\n config.task.evaluation.report_per_class_metric = True\n\n task = img_seg_task.SemanticSegmentation3DTask(config.task)\n model = task.build_model()\n metrics = task.build_metrics()\n strategy = tf.distribute.get_strategy()\n\n dataset = orbit.utils.make_distributed_dataset(strategy, task.build_inputs,\n config.task.train_data)\n\n iterator = iter(dataset)\n opt_factory = optimization.OptimizerFactory(config.trainer.optimizer_config)\n optimizer = opt_factory.build_optimizer(opt_factory.build_learning_rate())\n logs = task.train_step(next(iterator), model, optimizer, metrics=metrics)\n # Check if training loss is produced.\n self.assertIn('loss', logs)\n\n # Obtain distributed outputs.\n distributed_outputs = strategy.run(\n functools.partial(\n task.validation_step,\n model=model,\n metrics=task.build_metrics(training=False)),\n args=(next(iterator),))\n outputs = tf.nest.map_structure(strategy.experimental_local_results,\n distributed_outputs)\n\n # Check if validation loss is produced.\n self.assertIn('loss', outputs)\n\n # Check if state is updated.\n state = task.aggregate_logs(state=None, step_outputs=outputs)\n self.assertLen(state, 1)\n self.assertIsInstance(state[0], segmentation_metrics.DiceScore)\n\n # Check if all metrics are produced.\n result = task.reduce_aggregated_logs(aggregated_logs={}, global_step=1)\n self.assertIn('val_generalized_dice', result)\n self.assertIn('val_generalized_dice/class_0', result)\n self.assertIn('val_generalized_dice/class_1', result)\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2022 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for maskrcnn_model.py.\"\"\"\n\n# Import libraries\n\nfrom absl.testing import parameterized\nimport numpy as np\nimport tensorflow as tf\n\nfrom official.projects.deepmac_maskrcnn.modeling import maskrcnn_model\nfrom official.projects.deepmac_maskrcnn.modeling.heads import instance_heads as deep_instance_heads\nfrom official.vision.modeling.backbones import resnet\nfrom official.vision.modeling.decoders import fpn\nfrom official.vision.modeling.heads import dense_prediction_heads\nfrom official.vision.modeling.heads import instance_heads\nfrom official.vision.modeling.layers import detection_generator\nfrom official.vision.modeling.layers import mask_sampler\nfrom official.vision.modeling.layers import roi_aligner\nfrom official.vision.modeling.layers import roi_generator\nfrom official.vision.modeling.layers import roi_sampler\nfrom official.vision.ops import anchor\n\n\ndef construct_model_and_anchors(image_size, use_gt_boxes_for_masks):\n num_classes = 3\n min_level = 3\n max_level = 4\n num_scales = 3\n aspect_ratios = [1.0]\n\n anchor_boxes = anchor.Anchor(\n min_level=min_level,\n max_level=max_level,\n num_scales=num_scales,\n aspect_ratios=aspect_ratios,\n anchor_size=3,\n image_size=image_size).multilevel_boxes\n num_anchors_per_location = len(aspect_ratios) * num_scales\n\n input_specs = tf.keras.layers.InputSpec(shape=[None, None, None, 3])\n backbone = resnet.ResNet(model_id=50, input_specs=input_specs)\n decoder = fpn.FPN(\n min_level=min_level,\n max_level=max_level,\n input_specs=backbone.output_specs)\n rpn_head = dense_prediction_heads.RPNHead(\n min_level=min_level,\n max_level=max_level,\n num_anchors_per_location=num_anchors_per_location)\n detection_head = instance_heads.DetectionHead(\n num_classes=num_classes)\n roi_generator_obj = roi_generator.MultilevelROIGenerator()\n roi_sampler_obj = roi_sampler.ROISampler()\n roi_aligner_obj = roi_aligner.MultilevelROIAligner()\n detection_generator_obj = detection_generator.DetectionGenerator()\n mask_head = deep_instance_heads.DeepMaskHead(\n num_classes=num_classes, upsample_factor=2)\n mask_sampler_obj = mask_sampler.MaskSampler(\n mask_target_size=28, num_sampled_masks=1)\n mask_roi_aligner_obj = roi_aligner.MultilevelROIAligner(crop_size=14)\n\n model = maskrcnn_model.DeepMaskRCNNModel(\n backbone,\n decoder,\n rpn_head,\n detection_head,\n roi_generator_obj,\n roi_sampler_obj,\n roi_aligner_obj,\n detection_generator_obj,\n mask_head,\n mask_sampler_obj,\n mask_roi_aligner_obj,\n use_gt_boxes_for_masks=use_gt_boxes_for_masks)\n\n return model, anchor_boxes\n\n\nclass MaskRCNNModelTest(parameterized.TestCase, tf.test.TestCase):\n\n @parameterized.parameters(\n (False, False,),\n (False, True,),\n (True, False,),\n (True, True,),\n )\n def test_forward(self, use_gt_boxes_for_masks, training):\n image_size = (256, 256)\n images = np.random.rand(2, image_size[0], image_size[1], 3)\n image_shape = np.array([[224, 100], [100, 224]])\n model, anchor_boxes = construct_model_and_anchors(\n image_size, use_gt_boxes_for_masks)\n\n gt_boxes = tf.zeros((2, 16, 4), dtype=tf.float32)\n gt_masks = tf.zeros((2, 16, 32, 32))\n gt_classes = tf.zeros((2, 16), dtype=tf.int32)\n results = model(images.astype(np.uint8),\n image_shape,\n anchor_boxes,\n gt_boxes,\n gt_classes,\n gt_masks,\n training=training)\n\n self.assertIn('rpn_boxes', results)\n self.assertIn('rpn_scores', results)\n if training:\n self.assertIn('class_targets', results)\n self.assertIn('box_targets', results)\n self.assertIn('class_outputs', results)\n self.assertIn('box_outputs', results)\n self.assertIn('mask_outputs', results)\n self.assertEqual(results['mask_targets'].shape,\n results['mask_outputs'].shape)\n else:\n self.assertIn('detection_boxes', results)\n self.assertIn('detection_scores', results)\n self.assertIn('detection_classes', results)\n self.assertIn('num_detections', results)\n self.assertIn('detection_masks', results)\n\n @parameterized.parameters(\n [(1, 5), (1, 10), (1, 15), (2, 5), (2, 10), (2, 15)]\n )\n def test_image_and_boxes(self, batch_size, num_boxes):\n image_size = (640, 640)\n images = np.random.rand(1, image_size[0], image_size[1], 3).astype(\n np.float32)\n model, _ = construct_model_and_anchors(\n image_size, use_gt_boxes_for_masks=True)\n\n boxes = np.zeros((1, num_boxes, 4), dtype=np.float32)\n boxes[:, :, [2, 3]] = 1.0\n boxes = tf.constant(boxes)\n results = model.call_images_and_boxes(images, boxes)\n self.assertIn('detection_masks', results)\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
] |
[
[
"tensorflow.compat.v1.ones",
"tensorflow.compat.v1.random.uniform",
"tensorflow.compat.v1.test.main"
],
[
"tensorflow.test.main"
],
[
"tensorflow.concat",
"tensorflow.keras.Input",
"tensorflow.keras.backend.image_data_format",
"tensorflow.transpose",
"tensorflow.reduce_mean",
"tensorflow.keras.layers.Dense",
"tensorflow.reshape",
"tensorflow.cast",
"tensorflow.identity",
"tensorflow.nn.tanh",
"tensorflow.zeros_like",
"tensorflow.keras.initializers.RandomNormal"
],
[
"tensorflow.convert_to_tensor",
"tensorflow.constant",
"tensorflow.saved_model.load",
"tensorflow.zeros",
"tensorflow.expand_dims",
"tensorflow.test.main",
"tensorflow.saved_model.save",
"tensorflow.train.BytesList",
"numpy.zeros"
],
[
"tensorflow.keras.layers.InputSpec",
"tensorflow.test.main",
"tensorflow.zeros"
],
[
"tensorflow.distribute.get_strategy",
"tensorflow.io.gfile.makedirs",
"tensorflow.test.main",
"tensorflow.nest.map_structure"
],
[
"tensorflow.constant",
"tensorflow.zeros",
"tensorflow.test.main",
"numpy.random.rand",
"numpy.array",
"tensorflow.keras.layers.InputSpec",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"1.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
jbgh2/speech-denoising-wavenet
|
[
"386662527b8da69fb3314531a2a7cff087eac557"
] |
[
"util.py"
] |
[
"# A Wavenet For Speech Denoising - Dario Rethage - 19.05.2017\n# Util.py\n# Utility functions for dealing with audio signals and training a Denoising Wavenet\nimport os\nimport numpy as np\nimport json\nimport warnings\nimport scipy.signal\nimport scipy.stats\nimport soundfile as sf\nimport tensorflow.keras as keras\n\ndef l1_l2_loss(y_true, y_pred, l1_weight, l2_weight):\n\n loss = 0\n\n if l1_weight != 0:\n loss += l1_weight * keras.losses.mean_absolute_error(y_true, y_pred)\n\n if l2_weight != 0:\n loss += l2_weight * keras.losses.mean_squared_error(y_true, y_pred)\n\n return loss\n\n\ndef compute_receptive_field_length(stacks, dilations, filter_length, target_field_length):\n\n half_filter_length = (filter_length-1)/2\n length = 0\n for d in dilations:\n length += d*half_filter_length\n length = 2*length\n length = stacks * length\n length += target_field_length\n return int(length)\n\n\ndef snr_db(rms_amplitude_A, rms_amplitude_B):\n return 20.0*np.log10(rms_amplitude_A/rms_amplitude_B)\n\n\ndef wav_to_float(x):\n try:\n max_value = np.iinfo(x.dtype).max\n min_value = np.iinfo(x.dtype).min\n except:\n max_value = np.finfo(x.dtype).max\n min_value = np.finfo(x.dtype).min\n x = x.astype('float64', casting='safe')\n x -= min_value\n x /= ((max_value - min_value) / 2.)\n x -= 1.\n return x\n\n\ndef float_to_uint8(x):\n x += 1.\n x /= 2.\n uint8_max_value = np.iinfo('uint8').max\n x *= uint8_max_value\n x = x.astype('uint8')\n return x\n\n\ndef keras_float_to_uint8(x):\n x += 1.\n x /= 2.\n uint8_max_value = 255\n x *= uint8_max_value\n return x\n\n\ndef linear_to_ulaw(x, u=255):\n x = np.sign(x) * (np.log(1 + u * np.abs(x)) / np.log(1 + u))\n return x\n\n\ndef keras_linear_to_ulaw(x, u=255.0):\n x = keras.backend.sign(x) * (keras.backend.log(1 + u * keras.backend.abs(x)) / keras.backend.log(1 + u))\n return x\n\n\ndef uint8_to_float(x):\n max_value = np.iinfo('uint8').max\n min_value = np.iinfo('uint8').min\n x = x.astype('float32', casting='unsafe')\n x -= min_value\n x /= ((max_value - min_value) / 2.)\n x -= 1.\n return x\n\n\ndef keras_uint8_to_float(x):\n max_value = 255\n min_value = 0\n x -= min_value\n x /= ((max_value - min_value) / 2.)\n x -= 1.\n return x\n\n\ndef ulaw_to_linear(x, u=255.0):\n y = np.sign(x) * (1 / float(u)) * (((1 + float(u)) ** np.abs(x)) - 1)\n return y\n\n\ndef keras_ulaw_to_linear(x, u=255.0):\n y = keras.backend.sign(x) * (1 / u) * (((1 + u) ** keras.backend.abs(x)) - 1)\n return y\n\n\ndef one_hot_encode(x, num_values=256):\n if isinstance(x, int):\n x = np.array([x])\n if isinstance(x, list):\n x = np.array(x)\n return np.eye(num_values, dtype='uint8')[x.astype('uint8')]\n\n\ndef one_hot_decode(x):\n return np.argmax(x, axis=-1)\n\n\ndef preemphasis(signal, alpha=0.95):\n return np.append(signal[0], signal[1:] - alpha * signal[:-1])\n\n\ndef binary_encode(x, max_value):\n if isinstance(x, int):\n x = np.array([x])\n if isinstance(x, list):\n x = np.array(x)\n width = np.ceil(np.log2(max_value)).astype(int)\n return (((x[:, None] & (1 << np.arange(width)))) > 0).astype(int)\n\n\ndef get_condition_input_encode_func(representation):\n\n if representation == 'binary':\n return binary_encode\n else:\n return one_hot_encode\n\n\ndef ensure_keys_in_dict(keys, dictionary):\n\n if all (key in dictionary for key in keys):\n return True\n return False\n\n\ndef get_subdict_from_dict(keys, dictionary):\n\n return dict((k, dictionary[k]) for k in keys if k in dictionary)\n\ndef pretty_json_dump(values, file_path=None):\n\n if file_path is None:\n print(json.dumps(values, sort_keys=True, indent=4, separators=(',', ': ')))\n else:\n json.dump(values, open(file_path, 'w'), sort_keys=True, indent=4, separators=(',', ': '))\n\ndef read_wav(filename):\n # Reads in a wav audio file, takes the first channel, converts the signal to float64 representation\n\n audio_signal, sample_rate = sf.read(filename)\n\n if audio_signal.ndim > 1:\n audio_signal = audio_signal[:, 0]\n\n if audio_signal.dtype != 'float64':\n audio_signal = wav_to_float(audio_signal)\n\n return audio_signal, sample_rate\n\n\ndef load_wav(wav_path, desired_sample_rate):\n\n sequence, sample_rate = read_wav(wav_path)\n sequence = ensure_sample_rate(sequence, desired_sample_rate, sample_rate)\n return sequence\n\n\ndef write_wav(x, filename, sample_rate):\n\n if type(x) != np.ndarray:\n x = np.array(x)\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\")\n sf.write(filename, x, sample_rate)\n\n\ndef ensure_sample_rate(x, desired_sample_rate, file_sample_rate):\n if file_sample_rate != desired_sample_rate:\n return scipy.signal.resample_poly(x, desired_sample_rate, file_sample_rate)\n return x\n\n\ndef rms(x):\n return np.sqrt(np.mean(np.square(x), axis=-1))\n\n\ndef normalize(x):\n max_peak = np.max(np.abs(x))\n return x / max_peak\n\n\ndef get_subsequence_with_speech_indices(full_sequence):\n signal_magnitude = np.abs(full_sequence)\n\n chunk_length = 800\n\n chunks_energies = []\n for i in range(0, len(signal_magnitude), chunk_length):\n chunks_energies.append(np.mean(signal_magnitude[i:i + chunk_length]))\n\n threshold = np.max(chunks_energies) * .1\n\n onset_chunk_i = 0\n for i in range(0, len(chunks_energies)):\n if chunks_energies[i] >= threshold:\n onset_chunk_i = i\n break\n\n termination_chunk_i = len(chunks_energies)\n for i in range(len(chunks_energies) - 1, 0, -1):\n if chunks_energies[i] >= threshold:\n termination_chunk_i = i\n break\n\n num_pad_chunks = 4\n onset_chunk_i = np.max((0, onset_chunk_i - num_pad_chunks))\n termination_chunk_i = np.min((len(chunks_energies), termination_chunk_i + num_pad_chunks))\n\n return [onset_chunk_i*chunk_length, (termination_chunk_i+1)*chunk_length]\n\n\ndef extract_subsequence_with_speech(full_sequence):\n\n indices = get_subsequence_with_speech_indices(full_sequence)\n return full_sequence[indices[0]:indices[1]]\n\n\ndef dir_contains_files(path):\n for f in os.listdir(path):\n if not f.startswith('.'):\n return True\n return False\n"
] |
[
[
"tensorflow.keras.backend.sign",
"numpy.max",
"numpy.mean",
"numpy.iinfo",
"tensorflow.keras.backend.log",
"numpy.square",
"numpy.arange",
"numpy.eye",
"numpy.finfo",
"numpy.argmax",
"numpy.log",
"tensorflow.keras.backend.abs",
"numpy.append",
"numpy.log10",
"numpy.array",
"numpy.log2",
"numpy.abs",
"numpy.sign",
"tensorflow.keras.losses.mean_absolute_error",
"tensorflow.keras.losses.mean_squared_error"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
wkentaro/cupy
|
[
"1d072d0b3cb2780c0874201c0222d46fa8e7797d",
"1d072d0b3cb2780c0874201c0222d46fa8e7797d"
] |
[
"cupy/linalg/product.py",
"cupy/indexing/generate.py"
] |
[
"import collections\n\nimport numpy\nimport six\n\nimport cupy\nfrom cupy import core\nfrom cupy import internal\n\n\nmatmul = core.matmul\n\n\ndef dot(a, b, out=None):\n \"\"\"Returns a dot product of two arrays.\n\n For arrays with more than one axis, it computes the dot product along the\n last axis of ``a`` and the second-to-last axis of ``b``. This is just a\n matrix product if the both arrays are 2-D. For 1-D arrays, it uses their\n unique axis as an axis to take dot product over.\n\n Args:\n a (cupy.ndarray): The left argument.\n b (cupy.ndarray): The right argument.\n out (cupy.ndarray): Output array.\n\n Returns:\n cupy.ndarray: The dot product of ``a`` and ``b``.\n\n .. seealso:: :func:`numpy.dot`\n\n \"\"\"\n # TODO(okuta): check type\n return a.dot(b, out)\n\n\ndef vdot(a, b):\n \"\"\"Returns the dot product of two vectors.\n\n The input arrays are flattened into 1-D vectors and then it performs inner\n product of these vectors.\n\n Args:\n a (cupy.ndarray): The first argument.\n b (cupy.ndarray): The second argument.\n\n Returns:\n cupy.ndarray: Zero-dimensional array of the dot product result.\n\n .. seealso:: :func:`numpy.vdot`\n\n \"\"\"\n if a.size != b.size:\n raise ValueError('Axis dimension mismatch')\n if a.dtype.kind == 'c':\n a = a.conj()\n\n return core.tensordot_core(a, b, None, 1, 1, a.size, ())\n\n\ndef inner(a, b):\n \"\"\"Returns the inner product of two arrays.\n\n It uses the last axis of each argument to take sum product.\n\n Args:\n a (cupy.ndarray): The first argument.\n b (cupy.ndarray): The second argument.\n\n Returns:\n cupy.ndarray: The inner product of ``a`` and ``b``.\n\n .. seealso:: :func:`numpy.inner`\n\n \"\"\"\n a_ndim = a.ndim\n b_ndim = b.ndim\n if a_ndim == 0 or b_ndim == 0:\n return cupy.multiply(a, b)\n\n a_axis = a_ndim - 1\n b_axis = b_ndim - 1\n\n if a.shape[-1] != b.shape[-1]:\n raise ValueError('Axis dimension mismatch')\n\n if a_axis:\n a = cupy.rollaxis(a, a_axis, 0)\n if b_axis:\n b = cupy.rollaxis(b, b_axis, 0)\n\n ret_shape = a.shape[1:] + b.shape[1:]\n\n k = a.shape[0]\n n = a.size // k\n m = b.size // k\n\n return core.tensordot_core(a, b, None, n, m, k, ret_shape)\n\n\ndef outer(a, b, out=None):\n \"\"\"Returns the outer product of two vectors.\n\n The input arrays are flattened into 1-D vectors and then it performs outer\n product of these vectors.\n\n Args:\n a (cupy.ndarray): The first argument.\n b (cupy.ndarray): The second argument.\n out (cupy.ndarray): Output array.\n\n Returns:\n cupy.ndarray: 2-D array of the outer product of ``a`` and ``b``.\n\n .. seealso:: :func:`numpy.outer`\n\n \"\"\"\n n = a.size\n m = b.size\n ret_shape = (n, m)\n\n if out is None:\n return core.tensordot_core(a, b, None, n, m, 1, ret_shape)\n\n if out.size != n * m:\n raise ValueError('Output array has an invalid size')\n if out.flags.c_contiguous:\n return core.tensordot_core(a, b, out, n, m, 1, ret_shape)\n else:\n out[:] = core.tensordot_core(a, b, None, n, m, 1, ret_shape)\n return out\n\n\ndef tensordot(a, b, axes=2):\n \"\"\"Returns the tensor dot product of two arrays along specified axes.\n\n This is equivalent to compute dot product along the specified axes which\n are treated as one axis by reshaping.\n\n Args:\n a (cupy.ndarray): The first argument.\n b (cupy.ndarray): The second argument.\n axes:\n - If it is an integer, then ``axes`` axes at the last of ``a`` and\n the first of ``b`` are used.\n - If it is a pair of sequences of integers, then these two\n sequences specify the list of axes for ``a`` and ``b``. The\n corresponding axes are paired for sum-product.\n out (cupy.ndarray): Output array.\n\n Returns:\n cupy.ndarray: The tensor dot product of ``a`` and ``b`` along the\n axes specified by ``axes``.\n\n .. seealso:: :func:`numpy.tensordot`\n\n \"\"\"\n a_ndim = a.ndim\n b_ndim = b.ndim\n if a_ndim == 0 or b_ndim == 0:\n if axes != 0 and axes != ((), ()):\n raise ValueError('An input is zero-dim while axes has dimensions')\n return cupy.multiply(a, b)\n\n if isinstance(axes, collections.Sequence):\n if len(axes) != 2:\n raise ValueError('Axes must consist of two arrays.')\n a_axes, b_axes = axes\n if numpy.isscalar(a_axes):\n a_axes = a_axes,\n if numpy.isscalar(b_axes):\n b_axes = b_axes,\n else:\n a_axes = tuple(six.moves.range(a_ndim - axes, a_ndim))\n b_axes = tuple(six.moves.range(axes))\n\n sum_ndim = len(a_axes)\n if sum_ndim != len(b_axes):\n raise ValueError('Axes length mismatch')\n\n for a_axis, b_axis in zip(a_axes, b_axes):\n if a.shape[a_axis] != b.shape[b_axis]:\n raise ValueError('Axis dimension mismatch')\n\n # Make the axes non-negative\n a = _move_axes_to_head(a, [axis % a_ndim for axis in a_axes])\n b = _move_axes_to_head(b, [axis % b_ndim for axis in b_axes])\n\n ret_shape = a.shape[sum_ndim:] + b.shape[sum_ndim:]\n\n k = internal.prod(a.shape[:sum_ndim])\n n = a.size // k\n m = b.size // k\n\n return core.tensordot_core(a, b, None, n, m, k, ret_shape)\n\n\n# TODO(okuta): Implement matrix_power\n\n\ndef kron(a, b):\n \"\"\"Returns the kronecker product of two arrays.\n\n Args:\n a (~cupy.ndarray): The first argument.\n b (~cupy.ndarray): The second argument.\n\n Returns:\n ~cupy.ndarray: Output array.\n\n .. seealso:: :func:`numpy.kron`\n\n \"\"\"\n a_ndim = a.ndim\n b_ndim = b.ndim\n if a_ndim == 0 or b_ndim == 0:\n return cupy.multiply(a, b)\n\n ndim = b_ndim\n a_shape = a.shape\n b_shape = b.shape\n if a_ndim != b_ndim:\n if b_ndim > a_ndim:\n a_shape = (1,) * (b_ndim - a_ndim) + a_shape\n else:\n b_shape = (1,) * (a_ndim - b_ndim) + b_shape\n ndim = a_ndim\n\n axis = ndim - 1\n out = core.tensordot_core(a, b, None, a.size, b.size, 1, a_shape + b_shape)\n for _ in six.moves.range(ndim):\n out = core.concatenate_method(out, axis=axis)\n\n return out\n\n\ndef _move_axes_to_head(a, axes):\n # This function moves the axes of ``s`` to the head of the shape.\n for idx, axis in enumerate(axes):\n if idx != axis:\n break\n else:\n return a\n\n return a.transpose(\n axes + [i for i in six.moves.range(a.ndim) if i not in axes])\n",
"# flake8: NOQA\n# \"flake8: NOQA\" to suppress warning \"H104 File contains nothing but comments\"\n\n# class s_(object):\n\nimport numpy\nimport six\n\nimport cupy\nfrom cupy import core\nfrom cupy.creation import from_data\nfrom cupy.manipulation import join\n\n\nclass AxisConcatenator(object):\n \"\"\"Translates slice objects to concatenation along an axis.\n\n For detailed documentation on usage, see :func:`cupy.r_`.\n This implementation is partially borrowed from NumPy's one.\n\n \"\"\"\n\n def _output_obj(self, obj, ndim, ndmin, trans1d):\n k2 = ndmin - ndim\n if trans1d < 0:\n trans1d += k2 + 1\n defaxes = list(six.moves.range(ndmin))\n k1 = trans1d\n axes = defaxes[:k1] + defaxes[k2:] + \\\n defaxes[k1:k2]\n return obj.transpose(axes)\n\n def __init__(self, axis=0, matrix=False, ndmin=1, trans1d=-1):\n self.axis = axis\n self.trans1d = trans1d\n self.matrix = matrix\n self.ndmin = ndmin\n\n def __getitem__(self, key):\n trans1d = self.trans1d\n ndmin = self.ndmin\n objs = []\n scalars = []\n arraytypes = []\n scalartypes = []\n if isinstance(key, six.string_types):\n raise NotImplementedError\n if not isinstance(key, tuple):\n key = (key,)\n\n for i, k in enumerate(key):\n scalar = False\n if isinstance(k, slice):\n raise NotImplementedError\n elif isinstance(k, six.string_types):\n if i != 0:\n raise ValueError(\n 'special directives must be the first entry.')\n raise NotImplementedError\n elif type(k) in numpy.ScalarType:\n newobj = from_data.array(k, ndmin=ndmin)\n scalars.append(i)\n scalar = True\n scalartypes.append(newobj.dtype)\n else:\n newobj = from_data.array(k, copy=False, ndmin=ndmin)\n if ndmin > 1:\n ndim = from_data.array(k, copy=False).ndim\n if trans1d != -1 and ndim < ndmin:\n newobj = self._output_obj(newobj, ndim, ndmin, trans1d)\n\n objs.append(newobj)\n if not scalar and isinstance(newobj, core.ndarray):\n arraytypes.append(newobj.dtype)\n\n final_dtype = numpy.find_common_type(arraytypes, scalartypes)\n if final_dtype is not None:\n for k in scalars:\n objs[k] = objs[k].astype(final_dtype)\n\n return join.concatenate(tuple(objs), axis=self.axis)\n\n def __len__(self):\n return 0\n\n\nclass CClass(AxisConcatenator):\n\n def __init__(self):\n super(CClass, self).__init__(-1, ndmin=2, trans1d=0)\n\n\nc_ = CClass()\n\"\"\"Translates slice objects to concatenation along the second axis.\n\nThis is a CuPy object that corresponds to :func:`cupy.r_`, which is\nuseful because of its common occurrence. In particular, arrays will be\nstacked along their last axis after being upgraded to at least 2-D with\n1's post-pended to the shape (column vectors made out of 1-D arrays).\n\nFor detailed documentation, see :func:`r_`.\n\nThis implementation is partially borrowed from NumPy's one.\n\nArgs:\n Not a function, so takes no parameters\n\nReturns:\n cupy.ndarray: Joined array.\n\n.. seealso:: :func:`numpy.c_`\n\nExamples\n--------\n>>> a = cupy.array([[1, 2, 3]], dtype=np.int32)\n>>> b = cupy.array([[4, 5, 6]], dtype=np.int32)\n>>> cupy.c_[a, 0, 0, b]\narray([[1, 2, 3, 0, 0, 4, 5, 6]], dtype=int32)\n\n\"\"\"\n\n\nclass RClass(AxisConcatenator):\n\n def __init__(self):\n super(RClass, self).__init__()\n\n\nr_ = RClass()\n\"\"\"Translates slice objects to concatenation along the first axis.\n\nThis is a simple way to build up arrays quickly.\nIf the index expression contains comma separated arrays, then stack\nthem along their first axis.\n\nThis object can build up from normal CuPy arrays.\nTherefore, the other objects (e.g. writing strings like '2,3,4',\nor using imaginary numbers like [1,2,3j],\nor using string integers like '-1') are not implemented yet\ncompared with NumPy.\n\nThis implementation is partially borrowed from NumPy's one.\n\nArgs:\n Not a function, so takes no parameters\n\nReturns:\n cupy.ndarray: Joined array.\n\n.. seealso:: :func:`numpy.r_`\n\nExamples\n--------\n>>> a = cupy.array([1, 2, 3], dtype=np.int32)\n>>> b = cupy.array([4, 5, 6], dtype=np.int32)\n>>> cupy.r_[a, 0, 0, b]\narray([1, 2, 3, 0, 0, 4, 5, 6], dtype=int32)\n\n\"\"\"\n\n\ndef indices(dimensions, dtype=int):\n \"\"\"Returns an array representing the indices of a grid.\n\n Computes an array where the subarrays contain index values 0,1,...\n varying only along the corresponding axis.\n\n Args:\n dimensions: The shape of the grid.\n dtype: Data type specifier. It is int by default.\n\n Returns:\n ndarray:\n The array of grid indices,\n ``grid.shape = (len(dimensions),) + tuple(dimensions)``.\n\n Examples\n --------\n >>> grid = cupy.indices((2, 3))\n >>> grid.shape\n (2, 2, 3)\n >>> grid[0] # row indices\n array([[0, 0, 0],\n [1, 1, 1]])\n >>> grid[1] # column indices\n array([[0, 1, 2],\n [0, 1, 2]])\n\n .. seealso:: :func:`numpy.indices`\n\n \"\"\"\n dimensions = tuple(dimensions)\n N = len(dimensions)\n shape = (1,) * N\n res = cupy.empty((N,) + dimensions, dtype=dtype)\n for i, dim in enumerate(dimensions):\n res[i] = cupy.arange(dim, dtype=dtype).reshape(\n shape[:i] + (dim,) + shape[i + 1:]\n )\n return res\n\n\ndef ix_(*args):\n \"\"\"Construct an open mesh from multiple sequences.\n\n This function takes N 1-D sequences and returns N outputs with N\n dimensions each, such that the shape is 1 in all but one dimension\n and the dimension with the non-unit shape value cycles through all\n N dimensions.\n\n Using `ix_` one can quickly construct index arrays that will index\n the cross product. ``a[cupy.ix_([1,3],[2,5])]`` returns the array\n ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``.\n\n Args:\n *args: 1-D sequences\n\n Returns:\n tuple of ndarrays:\n N arrays with N dimensions each, with N the number of input sequences.\n Together these arrays form an open mesh.\n\n Examples\n --------\n >>> a = cupy.arange(10).reshape(2, 5)\n >>> a\n array([[0, 1, 2, 3, 4],\n [5, 6, 7, 8, 9]])\n >>> ixgrid = cupy.ix_([0,1], [2,4])\n >>> ixgrid\n (array([[0],\n [1]]), array([[2, 4]]))\n\n .. seealso:: :func:`numpy.ix_`\n\n \"\"\"\n out = []\n nd = len(args)\n for k, new in enumerate(args):\n new = from_data.asarray(new)\n if new.ndim != 1:\n raise ValueError('Cross index must be 1 dimensional')\n if new.size == 0:\n # Explicitly type empty arrays to avoid float default\n new = new.astype(numpy.intp)\n if cupy.issubdtype(new.dtype, cupy.bool_):\n new, = new.nonzero()\n new = new.reshape((1,) * k + (new.size,) + (1,) * (nd - k - 1))\n out.append(new)\n return tuple(out)\n\n# TODO(okuta): Implement ravel_multi_index\n\n\ndef unravel_index(indices, dims, order='C'):\n \"\"\"Converts a flat index or array of flat indices into a tuple of coordinate arrays.\n\n Args:\n indices (cupy.ndarray): An integer array whose elements are indices\n into the flattened version of an array of dimensions :obj:`dims`.\n dims (tuple of ints): The shape of the array to use for unraveling indices.\n order ('C' or 'F'): Determines whether the indices should be viewed as indexing\n in row-major (C-style) or column-major (Fortran-style) order.\n\n Returns: tuple of ndarrays:\n Each array in the tuple has the same shape as the indices array.\n\n Examples\n --------\n >>> cupy.unravel_index(cupy.array([22, 41, 37]), (7, 6))\n (array([3, 6, 6]), array([4, 5, 1]))\n >>> cupy.unravel_index(cupy.array([31, 41, 13]), (7, 6), order='F')\n (array([3, 6, 6]), array([4, 5, 1]))\n\n .. seealso:: :func:`numpy.unravel_index`\n\n \"\"\"\n if order is None:\n order = 'C'\n\n if order == 'C':\n dims = reversed(dims)\n elif order == 'F':\n pass\n else:\n raise TypeError('order not understood')\n\n if not cupy.can_cast(indices, cupy.int64, 'same_kind'):\n raise TypeError(\n 'Iterator operand 0 dtype could not be cast '\n 'from dtype(\\'{}\\') to dtype(\\'{}\\') '\n 'according to the rule \\'same_kind\\''.format(\n indices.dtype, cupy.int64().dtype))\n\n if (indices < 0).any():\n raise ValueError('invalid entry in index array')\n\n unraveled_coords = []\n for dim in dims:\n unraveled_coords.append(indices % dim)\n indices = indices // dim\n\n if (indices > 0).any():\n raise ValueError('invalid entry in index array')\n\n if order == 'C':\n unraveled_coords = reversed(unraveled_coords)\n return tuple(unraveled_coords)\n\n\n# TODO(okuta): Implement diag_indices\n\n\n# TODO(okuta): Implement diag_indices_from\n\n\n# TODO(okuta): Implement mask_indices\n\n\n# TODO(okuta): Implement tril_indices\n\n\n# TODO(okuta): Implement tril_indices_from\n\n\n# TODO(okuta): Implement triu_indices\n\n\n# TODO(okuta): Implement triu_indices_from\n"
] |
[
[
"numpy.isscalar"
],
[
"numpy.find_common_type"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kh296/InnerEye-DeepLearning
|
[
"917f8d0b30c4ecfa9198cf55b17b87f359fbbbe9"
] |
[
"InnerEye/ML/metrics_dict.py"
] |
[
"# ------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.\n# ------------------------------------------------------------------------------------------\nfrom __future__ import annotations\n\nimport logging\nfrom collections import OrderedDict\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\nfrom typing import Any, Dict, Generic, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union\n\nimport numpy as np\nimport pandas as pd\nfrom more_itertools import flatten\nfrom pandas._typing import FilePathOrBuffer\nfrom sklearn.metrics import auc, log_loss, precision_recall_curve, roc_auc_score, roc_curve\n\nfrom InnerEye.Azure.azure_util import DEFAULT_CROSS_VALIDATION_SPLIT_INDEX\nfrom InnerEye.Common.common_util import check_properties_are_not_none\nfrom InnerEye.Common.metrics_constants import INTERNAL_TO_LOGGING_COLUMN_NAMES, LoggingColumns, MetricType, \\\n MetricTypeOrStr, SEQUENCE_POSITION_HUE_NAME_PREFIX\nfrom InnerEye.ML.common import ModelExecutionMode\nfrom InnerEye.ML.utils.metrics_util import binary_classification_accuracy, mean_absolute_error, \\\n mean_squared_error, r2_score\n\nFloatOrInt = Union[float, int]\nT = TypeVar('T', np.ndarray, float)\n\n\ndef average_metric_values(values: List[float], skip_nan_when_averaging: bool) -> float:\n \"\"\"\n Returns the average (arithmetic mean) of the values provided. If skip_nan_when_averaging is True, the mean\n will be computed without any possible NaN values in the list.\n :param values: The individual values that should be averaged.\n :param skip_nan_when_averaging: If True, compute mean with any NaN values. If False, any NaN value present\n in the argument will make the function return NaN.\n :return: The average of the provided values. If the argument is an empty list, NaN will be returned.\n \"\"\"\n if skip_nan_when_averaging:\n return np.nanmean(values).item()\n else:\n return np.mean(values).item()\n\n\n@dataclass(frozen=True)\nclass PredictionEntry(Generic[T]):\n subject_id: str\n predictions: T\n labels: T\n\n def __post_init__(self) -> None:\n check_properties_are_not_none(self)\n\n\ndef get_column_name_for_logging(metric_name: Union[str, MetricType],\n hue_name: Optional[str] = None) -> str:\n \"\"\"\n Computes the column name that should be used when logging a metric to disk.\n Raises a value error when no column name has yet been defined.\n :param metric_name: The name of the metric.\n :param hue_name: If provided will be used as a prefix hue_name/column_name\n \"\"\"\n metric_str = metric_name if isinstance(metric_name, str) else metric_name.value\n if metric_str in INTERNAL_TO_LOGGING_COLUMN_NAMES:\n return get_metric_name_with_hue_prefix(INTERNAL_TO_LOGGING_COLUMN_NAMES[metric_str].value, hue_name)\n raise ValueError(f\"No column name mapping defined for metric '{metric_str}'\")\n\n\ndef get_metric_name_with_hue_prefix(metric_name: str, hue_name: Optional[str] = None) -> str:\n \"\"\"\n If hue_name is provided and is not equal to the default hue then it will be\n used as a prefix hue_name/column_name, otherwise metric_name will be returned.\n \"\"\"\n prefix = f\"{hue_name}/\" if hue_name and hue_name is not MetricsDict.DEFAULT_HUE_KEY else ''\n return f\"{prefix}{metric_name}\"\n\n\n@dataclass\nclass Hue:\n \"\"\"\n Dataclass to encapsulate hue specific data related for metrics computation.\n \"\"\"\n name: str\n values: Dict[str, List[FloatOrInt]] = field(default_factory=dict)\n predictions: List[np.ndarray] = field(default_factory=list)\n labels: List[np.ndarray] = field(default_factory=list)\n subject_ids: List[str] = field(default_factory=list)\n\n @property\n def has_prediction_entries(self) -> bool:\n \"\"\"\n Returns True if the present object stores any entries for computing the Area Under Roc Curve metric.\n \"\"\"\n _labels = self.labels\n return len(_labels) > 0 if _labels else False\n\n def add_predictions(self,\n subject_ids: Sequence[str],\n predictions: np.ndarray,\n labels: np.ndarray) -> None:\n \"\"\"\n Adds predictions and labels for later computing the area under the ROC curve.\n :param subject_ids: Subject ids associated with the predictions and labels.\n :param predictions: A numpy array with model predictions, of size [N x C] for N samples in C classes, or size\n [N x 1] or size [N] for binary.\n :param labels: A numpy array with labels, of size [N x C] for N samples in C classes, or size\n [N x 1] or size [N] for binary.\n \"\"\"\n if predictions.ndim == 1:\n predictions = np.expand_dims(predictions, axis=1)\n if labels.ndim == 1:\n labels = np.expand_dims(labels, axis=1)\n if not (len(predictions) == len(labels) == len(subject_ids)):\n raise ValueError(\"predictions, labels and subject_ids must have the same length in dimension 0 \"\n f\"found predictions={len(predictions)}, labels={len(labels)}, \"\n f\"and subject_ids={len(subject_ids)}\")\n self.subject_ids += subject_ids\n self.predictions.append(predictions)\n self.labels.append(labels)\n\n def get_predictions(self) -> np.ndarray:\n \"\"\"\n Return a concatenated copy of the roc predictions stored internally.\n \"\"\"\n\n return Hue._concat_if_needed(self.predictions)\n\n def get_labels(self) -> np.ndarray:\n \"\"\"\n Return a concatenated copy of the roc labels stored internally.\n \"\"\"\n return Hue._concat_if_needed(self.labels)\n\n def get_predictions_and_labels_per_subject(self) -> List[PredictionEntry[float]]:\n \"\"\"\n Gets the per-subject predictions that are stored in the present object.\n \"\"\"\n predictions = self.get_predictions()\n labels = self.get_labels()\n if not (len(self.subject_ids) == len(labels) == len(predictions)):\n raise ValueError(f\"Inconsistent number of predictions stored: \"\n f\"{len(self.subject_ids)} subjects, \"\n f\"{len(labels)} labels, \"\n f\"{len(predictions)} predictions.\")\n return [PredictionEntry(subject_id=x,\n predictions=predictions[i][0],\n labels=labels[i][0])\n for i, x in enumerate(self.subject_ids)]\n\n @staticmethod\n def _concat_if_needed(arrays: List[np.ndarray]) -> np.ndarray:\n \"\"\"\n Joins a list of arrays into a single array, taking empty lists into account correctly.\n :param arrays: Array list to be concatenated.\n \"\"\"\n if arrays:\n return np.concatenate(arrays, axis=0)\n return np.array([])\n\n def enumerate_single_values(self) -> Iterable[Tuple[str, float]]:\n \"\"\"\n Returns an iterator that contains all (metric name, metric value) tuples that are stored in the\n present object. The method assumes that there is exactly 1 metric value stored per name, and throws a\n ValueError if that is not the case.\n :return: An iterator with (metric name, metric value) pairs.\n \"\"\"\n for metric_name, metric_value in self.values.items():\n if len(metric_value) == 1:\n yield metric_name, metric_value[0]\n else:\n raise ValueError(f\"Expected that all metrics lists only hold 1 item, \"\n f\"but got this list for Hue {self.name} : metric \"\n f\"'{metric_name}': {metric_value}\")\n\n\nclass MetricsDict:\n \"\"\"\n This class helps aggregate an arbitrary number of metrics across multiple batches or multiple samples. Metrics are\n identified by a string name. Metrics can have further hues which are isolated metrics records, and can be used\n for cases such as different anatomical structures, where we might want to maintain separate metrics for each\n structure, to perform independent aggregations.\n \"\"\"\n\n DEFAULT_HUE_KEY = \"Default\"\n # the columns used when metrics dict is converted to a data frame/string representation\n DATAFRAME_COLUMNS = [LoggingColumns.Hue.value, \"metrics\"]\n\n def __init__(self, hues: Optional[List[str]] = None, is_classification_metrics: bool = True) -> None:\n \"\"\"\n :param hues: Supported hues for this metrics dict, otherwise all records will belong to the\n default hue.\n :param is_classification_metrics: If this is a classification metrics dict\n \"\"\"\n\n _hues = hues.copy() if hues else None\n if _hues and MetricsDict.DEFAULT_HUE_KEY in _hues:\n _hues.remove(MetricsDict.DEFAULT_HUE_KEY)\n self.hues_without_default = _hues or []\n _hue_keys = self.hues_without_default + [MetricsDict.DEFAULT_HUE_KEY]\n self.hues: OrderedDict[str, Hue] = OrderedDict([(x, Hue(name=x)) for x in _hue_keys])\n self.skip_nan_when_averaging: Dict[str, bool] = dict()\n self.row_labels: List[str] = list()\n self.is_classification_metrics = is_classification_metrics\n self.diagnostics: Dict[str, List[Any]] = dict()\n\n def subject_ids(self, hue: str = DEFAULT_HUE_KEY) -> List[str]:\n \"\"\"\n Return the subject ids that have metrics associated with them in this dictionary.\n :param hue: If provided then subject ids belonging to this hue only will be returned.\n Otherwise subject ids for the default hue will be returned.\n \"\"\"\n return self._get_hue(hue=hue).subject_ids\n\n def get_hue_names(self, include_default: bool = True) -> List[str]:\n \"\"\"\n Returns all of the hues supported by this metrics dict\n :param include_default: Include the default hue if True, otherwise exclude the default hue.\n \"\"\"\n _hue_names = list(self.hues.keys())\n if not include_default:\n _hue_names.remove(MetricsDict.DEFAULT_HUE_KEY)\n return _hue_names\n\n def delete_hue(self, hue: str) -> None:\n \"\"\"\n Removes all data stored for the given hue from the present object.\n :param hue: The hue to remove.\n \"\"\"\n del self.hues[hue]\n\n def get_single_metric(self, metric_name: MetricTypeOrStr, hue: str = DEFAULT_HUE_KEY) -> FloatOrInt:\n \"\"\"\n Gets the value stored for the given metric. The method assumes that there is a single value stored for the\n metric, and raises a ValueError if that is not the case.\n :param metric_name: The name of the metric to retrieve.\n :param hue: The hue to retrieve the metric from.\n :return:\n \"\"\"\n name = MetricsDict._metric_name(metric_name)\n values = self.values(hue)[name]\n if len(values) == 1:\n return values[0]\n raise ValueError(f\"Expected a single entry for metric '{name}', but got {len(values)}\")\n\n def has_prediction_entries(self, hue: str = DEFAULT_HUE_KEY) -> bool:\n \"\"\"\n Returns True if the present object stores any entries for computing the Area Under Roc Curve metric.\n :param hue: will be used to check a particular hue otherwise default hue will be used.\n :return: True if entries exist. False otherwise.\n \"\"\"\n return self._get_hue(hue).has_prediction_entries\n\n def values(self, hue: str = DEFAULT_HUE_KEY) -> Dict[str, Any]:\n \"\"\"\n Returns values held currently in the dict\n :param hue: will be used to restrict values for the provided hue otherwise values in the default\n hue will be returned.\n :return: Dictionary of values for this object.\n \"\"\"\n return self._get_hue(hue).values\n\n def add_diagnostics(self, name: str, value: Any) -> None:\n \"\"\"\n Adds a diagnostic value to the present object. Multiple diagnostics can be stored per unique value of name,\n the values get concatenated.\n :param name: The name of the diagnostic value to store.\n :param value: The value to store.\n \"\"\"\n if name in self.diagnostics:\n # There is already an entry, append to the end of the list\n self.diagnostics[name].append(value)\n else:\n self.diagnostics[name] = [value]\n\n @staticmethod\n def _metric_name(metric_name: MetricTypeOrStr) -> str:\n \"\"\"\n Converts a metric name, given either as an enum or a string, to a string.\n \"\"\"\n if isinstance(metric_name, MetricType):\n return metric_name.value\n return str(metric_name)\n\n def add_metric(self,\n metric_name: Union[str, MetricType],\n metric_value: FloatOrInt,\n skip_nan_when_averaging: bool = False,\n hue: str = DEFAULT_HUE_KEY) -> None:\n \"\"\"\n Adds values for a single metric to the present object, when the metric value is a scalar.\n :param metric_name: The name of the metric to add. This can be a string or a value in the MetricType enum.\n :param metric_value: The values of the metric, as a float or integer.\n :param skip_nan_when_averaging: If True, averaging this metric will skip any NaN (not a number) values.\n If False, NaN will propagate through the mean computation.\n :param hue: The hue for which this record belongs to, default hue will be used if None provided.\n \"\"\"\n _metric_name = MetricsDict._metric_name(metric_name)\n if isinstance(metric_value, (float, int)):\n _values = self._get_hue(hue).values\n if _metric_name in _values:\n # There is already an entry for this metric, append to the end of the list\n _values[_metric_name].append(metric_value)\n else:\n _values[_metric_name] = [metric_value]\n else:\n raise ValueError(f\"Expected the metric to be a scalar (float or int), but got: {type(metric_value)}\")\n self.skip_nan_when_averaging[_metric_name] = skip_nan_when_averaging\n\n def delete_metric(self,\n metric_name: Union[str, MetricType],\n hue: str = DEFAULT_HUE_KEY) -> None:\n \"\"\"\n Deletes all values that are stored for a given metric from the present object.\n :param metric_name: The name of the metric to add. This can be a string or a value in the MetricType enum.\n :param hue: The hue for which this record belongs to, default hue will be used if None provided.\n \"\"\"\n _metric_name = MetricsDict._metric_name(metric_name)\n del self._get_hue(hue).values[_metric_name]\n\n def add_predictions(self, subject_ids: Sequence[str],\n predictions: np.ndarray,\n labels: np.ndarray,\n hue: str = DEFAULT_HUE_KEY) -> None:\n \"\"\"\n Adds predictions and labels for later computing the area under the ROC curve.\n :param subject_ids: Subject ids associated with the predictions and labels.\n :param predictions: A numpy array with model predictions, of size [N x C] for N samples in C classes, or size\n [N x 1] or size [N] for binary.\n :param labels: A numpy array with labels, of size [N x C] for N samples in C classes, or size\n [N x 1] or size [N] for binary.\n :param hue: The hue this prediction belongs to, default hue will be used if None provided.\n \"\"\"\n self._get_hue(hue).add_predictions(subject_ids=subject_ids,\n labels=labels,\n predictions=predictions)\n\n def num_entries(self, hue: str = DEFAULT_HUE_KEY) -> Dict[str, int]:\n \"\"\"\n Gets the number of values that are stored for each individual metric.\n :param hue: The hue to count entries for, otherwise all entries will be counted.\n :return: A dictionary mapping from metric name to number of values stored.\n \"\"\"\n _values = self._get_hue(hue).values\n return {m: len(v) for m, v in _values.items()}\n\n def average(self,\n add_metrics_from_entries: bool = False,\n across_hues: bool = True) -> MetricsDict:\n \"\"\"\n Returns a MetricsDict object that only contains the per-metric averages (arithmetic mean) from the present\n object.\n Computing the average will respect the skip_nan_when_averaging value that has been provided when adding\n the metric.\n :param add_metrics_from_entries: average existing metrics in the dict.\n :param across_hues: If True then same metric types will be averaged regardless of hues, otherwise\n separate averages for each metric type for each hue will be computed, Default is True.\n :return: A MetricsDict object with a single-item list for each of the metrics.\n \"\"\"\n\n def _get_all_metrics() -> List[Tuple[str, str, Any]]:\n _all_values = {}\n for _hue in self.get_hue_names():\n _values = self.values(_hue)\n if self.has_prediction_entries(_hue):\n if self.is_classification_metrics:\n _values[MetricType.AREA_UNDER_ROC_CURVE.value] = [self.get_roc_auc(_hue)]\n _values[MetricType.AREA_UNDER_PR_CURVE.value] = [self.get_pr_auc(_hue)]\n # Add metrics at optimal cut-off\n optimal_threshold, fpr, fnr, accuracy = self.get_metrics_at_optimal_cutoff(_hue)\n _values[MetricType.ACCURACY_AT_OPTIMAL_THRESHOLD.value] = [accuracy]\n _values[MetricType.FALSE_POSITIVE_RATE_AT_OPTIMAL_THRESHOLD.value] = [fpr]\n _values[MetricType.FALSE_NEGATIVE_RATE_AT_OPTIMAL_THRESHOLD.value] = [fnr]\n _values[MetricType.OPTIMAL_THRESHOLD.value] = [optimal_threshold]\n\n if add_metrics_from_entries:\n if MetricType.CROSS_ENTROPY.value in _values:\n raise ValueError(\n \"Unable to add cross entropy because this metric is already present in the dict.\")\n else:\n _values[MetricType.CROSS_ENTROPY.value] = [self.get_cross_entropy(_hue)]\n _values[MetricType.ACCURACY_AT_THRESHOLD_05.value] = [self.get_accuracy_at05(_hue)]\n else:\n if add_metrics_from_entries:\n _values[MetricType.MEAN_ABSOLUTE_ERROR.value] = [self.get_mean_absolute_error(_hue)]\n _values[MetricType.MEAN_SQUARED_ERROR.value] = [self.get_mean_squared_error(_hue)]\n _values[MetricType.EXPLAINED_VAR.value] = [self.get_r2_score(_hue)]\n\n _values[MetricType.SUBJECT_COUNT.value] = [len(self.get_predictions(_hue))]\n _all_values[_hue] = _values\n # noinspection PyTypeChecker\n return list(\n flatten([list(map(lambda x: (k, *x), v.items())) for k, v in _all_values.items()])) # type: ignore\n\n def _fill_new_metrics_dict(m: MetricsDict, average: bool = False) -> MetricsDict:\n for _m_hue, _m_metric_name, _m_value in _get_all_metrics():\n skip_nan = self.skip_nan_when_averaging.get(_m_metric_name, False) # type: ignore\n if average:\n m.add_metric(_m_metric_name,\n average_metric_values(_m_value, skip_nan_when_averaging=skip_nan),\n hue=_m_hue)\n else:\n for _v in _m_value:\n m.add_metric(_m_metric_name, _v, skip_nan_when_averaging=skip_nan)\n return m\n\n if across_hues:\n return _fill_new_metrics_dict(MetricsDict()).average(across_hues=False)\n else:\n return _fill_new_metrics_dict(MetricsDict(hues=self.get_hue_names(include_default=False)), average=True)\n\n def get_accuracy_at05(self, hue: str = DEFAULT_HUE_KEY) -> float:\n \"\"\"\n Returns the binary classification accuracy at threshold 0.5\n \"\"\"\n return binary_classification_accuracy(model_output=self.get_predictions(hue=hue),\n label=self.get_labels(hue=hue))\n\n @classmethod\n def get_optimal_idx(cls, fpr: np.ndarray, tpr: np.ndarray) -> np.ndarray:\n \"\"\"\n Given a list of FPR and TPR values corresponding to different thresholds, compute the index which corresponds\n to the optimal threshold.\n \"\"\"\n optimal_idx = np.argmax(tpr - fpr)\n return optimal_idx\n\n def get_metrics_at_optimal_cutoff(self, hue: str = DEFAULT_HUE_KEY) -> Tuple:\n \"\"\"\n Computes the ROC to find the optimal cut-off i.e. the probability threshold for which the\n difference between true positive rate and false positive rate is smallest. Then, computes\n the false positive rate, false negative rate and accuracy at this threshold (i.e. when the\n predicted probability is higher than the threshold the predicted label is 1 otherwise 0).\n :param hue: The hue to restrict the values used for computation, otherwise all values will be used.\n :returns: Tuple(optimal_threshold, false positive rate, false negative rate, accuracy)\n \"\"\"\n fpr, tpr, thresholds = roc_curve(self.get_labels(hue=hue), self.get_predictions(hue=hue))\n optimal_idx = MetricsDict.get_optimal_idx(fpr=fpr, tpr=tpr)\n optimal_threshold = float(thresholds[optimal_idx])\n accuracy = binary_classification_accuracy(model_output=self.get_predictions(hue=hue),\n label=self.get_labels(hue=hue),\n threshold=optimal_threshold)\n false_negative_optimal = 1 - tpr[optimal_idx]\n false_positive_optimal = fpr[optimal_idx]\n return optimal_threshold, false_positive_optimal, false_negative_optimal, accuracy\n\n def get_roc_auc(self, hue: str = DEFAULT_HUE_KEY) -> float:\n \"\"\"\n Computes the Area Under the ROC curve, from the entries that were supplied in the add_roc_entries method.\n :param hue: The hue to restrict the values used for computation, otherwise all values will be used.\n :return: The AUC score, or np.nan if no entries are available in the present object.\n \"\"\"\n if not self.has_prediction_entries(hue):\n return np.nan\n predictions = self.get_predictions(hue)\n labels = self.get_labels(hue)\n if predictions.shape[1] == 1 and labels.shape[1] == 1 and len(np.unique(labels)) == 1:\n # We are dealing with a binary classification problem, but there is only a single class present\n # in the data: This happens occasionaly in test data. Return 1.0 because in such cases we could\n # always get a classifier threshold that correctly classifies everything.\n return 1.0\n else:\n return roc_auc_score(labels, predictions)\n\n def get_pr_auc(self, hue: str = DEFAULT_HUE_KEY) -> float:\n \"\"\"\n Computes the Area Under the Precision Recall Curve, from the entries that were supplied in the\n add_roc_entries method.\n :param hue: The hue to restrict the values used for computation, otherwise all values will be used.\n :return: The PR AUC score, or np.nan if no entries are available in the present object.\n \"\"\"\n if not self.has_prediction_entries(hue):\n return np.nan\n predictions = self.get_predictions(hue)\n labels = self.get_labels(hue)\n if predictions.shape[1] == 1 and labels.shape[1] == 1 and len(np.unique(labels)) == 1:\n # We are dealing with a binary classification problem, but there is only a single class present\n # in the data: This happens occasionaly in test data. Return 1.0 because in such cases we could\n # always get a classifier threshold that correctly classifies everything.\n return 1.0\n precision, recall, _ = precision_recall_curve(labels, predictions)\n return auc(recall, precision)\n\n def get_cross_entropy(self, hue: str = DEFAULT_HUE_KEY) -> float:\n \"\"\"\n Computes the binary cross entropy from the entries that were supplied in the\n add_roc_entries method.\n :param hue: The hue to restrict the values used for computation, otherwise all values will be used.\n :return: The cross entropy score.\n \"\"\"\n predictions = self.get_predictions(hue)\n labels = self.get_labels(hue)\n return log_loss(labels, predictions)\n\n def get_mean_absolute_error(self, hue: str = DEFAULT_HUE_KEY) -> float:\n \"\"\"\n Get the mean absolute error.\n :param hue: The hue to restrict the values used for computation, otherwise all values will be used.\n :return: Mean absolute error.\n \"\"\"\n return mean_absolute_error(model_output=self.get_predictions(hue), label=self.get_labels(hue))\n\n def get_mean_squared_error(self, hue: str = DEFAULT_HUE_KEY) -> float:\n \"\"\"\n Get the mean squared error.\n :param hue: The hue to restrict the values used for computation, otherwise all values will be used.\n :return: Mean squared error\n \"\"\"\n return mean_squared_error(model_output=self.get_predictions(hue), label=self.get_labels(hue))\n\n def get_r2_score(self, hue: str = DEFAULT_HUE_KEY) -> float:\n \"\"\"\n Get the R2 score.\n :param hue: The hue to restrict the values used for computation, otherwise all values will be used.\n :return: R2 score\n \"\"\"\n return r2_score(model_output=self.get_predictions(hue), label=self.get_labels(hue))\n\n def enumerate_single_values(self, hue: Optional[str] = None) -> Iterable[Tuple[str, str, float]]:\n \"\"\"\n Returns an iterator that contains all (hue name, metric name, metric values) tuples that are stored in the\n present object. This method assumes that for each hue/metric combination there is exactly 1 value, and it\n throws an exception if that is more than 1 value.\n :param hue: The hue to restrict the values, otherwise all values will be used if set to None.\n :return: An iterator with (hue name, metric name, metric values) pairs.\n \"\"\"\n for _hue, metric_name, values in self._enumerate_values(hue=hue, ensure_singleton_values_only=True):\n yield _hue, metric_name, values[0]\n\n def _enumerate_values(self, hue: Optional[str] = None,\n ensure_singleton_values_only: bool = False) \\\n -> Iterable[Tuple[str, str, List[float]]]:\n \"\"\"\n Returns an iterator that contains all (hue name, metric name, metric values) tuples that are stored in the\n present object.\n :param hue: The hue to restrict the values, otherwise all values will be used if set to None.\n :param ensure_singleton_values_only: Ensure that each of the values return is a singleton.\n :return: An iterator with (hue name, metric name, metric values) pairs.\n \"\"\"\n _hues_to_iterate = [hue] if hue is not None else self.get_hue_names()\n for _hue in _hues_to_iterate:\n _values = self._get_hue(_hue).values\n for metric_name, metric_value in _values.items():\n if ensure_singleton_values_only and len(metric_value) != 1:\n raise ValueError(f\"Expected that all metrics lists only hold 1 item, \"\n f\"but got this list for Hue {_hue} : metric \"\n f\"'{metric_name}': {metric_value}\")\n\n yield _hue, metric_name, metric_value\n\n def enumerate_single_values_groupwise(self) -> Iterable[Tuple[str, Iterable[Tuple[str, float]]]]:\n \"\"\"\n Returns an iterator that contains (hue name, metric_name_and_value) tuples that are stored in the\n present object. The second tuple element is again an iterator that returns all metric name and value tuples\n that are stored for that specific hue. This method assumes that for each hue/metric combination there is\n exactly 1 value, and it throws an exception if that is more than 1 value.\n :return: An iterator with (hue name, metric_name_and_value) pairs.\n \"\"\"\n _hues_to_iterate = [MetricsDict.DEFAULT_HUE_KEY] + self.get_hue_names(include_default=False)\n for _hue in _hues_to_iterate:\n yield _hue, self._get_hue(_hue).enumerate_single_values()\n\n def get_predictions(self, hue: str = DEFAULT_HUE_KEY) -> np.ndarray:\n \"\"\"\n Return a concatenated copy of the roc predictions stored internally.\n :param hue: The hue to restrict the values, otherwise all values will be used.\n :return: concatenated roc predictions as np array\n \"\"\"\n return self._get_hue(hue).get_predictions()\n\n def get_labels(self, hue: str = DEFAULT_HUE_KEY) -> np.ndarray:\n \"\"\"\n Return a concatenated copy of the roc labels stored internally.\n :param hue: The hue to restrict the values, otherwise all values will be used.\n :return: roc labels as np array\n \"\"\"\n return self._get_hue(hue).get_labels()\n\n def get_predictions_and_labels_per_subject(self, hue: str = DEFAULT_HUE_KEY) \\\n -> List[PredictionEntry[float]]:\n \"\"\"\n Gets the per-subject labels and predictions that are stored in the present object.\n :param hue: The hue to restrict the values, otherwise the default hue will be used.\n :return: List of per-subject labels and predictions\n \"\"\"\n return self._get_hue(hue).get_predictions_and_labels_per_subject()\n\n def to_string(self, tabulate: bool = True) -> str:\n \"\"\"\n Creates a multi-line human readable string from the given metrics.\n :param tabulate: If True then create a pretty printable table string.\n :return: Formatted metrics string\n \"\"\"\n from InnerEye.ML.utils.io_util import tabulate_dataframe\n df = self.to_data_frame()\n return tabulate_dataframe(df) if tabulate else df.to_string(index=False)\n\n def to_data_frame(self) -> pd.DataFrame:\n \"\"\"\n Creates a data frame representation of the metrics dict in the format with the\n Hue name as a column and a string representation of all metrics for that hue as a second column.\n \"\"\"\n\n def _format_metric_values(x: Union[List[float], float]) -> str:\n x = [x] if isinstance(x, float) else x\n _x = [f\"{y:0.4f}\" for y in x]\n return str(_x[0] if len(_x) == 1 else _x)\n\n info_df = pd.DataFrame(columns=MetricsDict.DATAFRAME_COLUMNS)\n for hue in self.get_hue_names():\n info_list = [f\"{metric_name}: {_format_metric_values(metric_values)}\"\n for _, metric_name, metric_values in self._enumerate_values(hue=hue)]\n if info_list:\n info_list_str = \", \".join(info_list)\n info_df = info_df.append({MetricsDict.DATAFRAME_COLUMNS[0]: hue,\n MetricsDict.DATAFRAME_COLUMNS[1]: info_list_str}, ignore_index=True)\n return info_df\n\n def _get_hue(self, hue: str = DEFAULT_HUE_KEY) -> Hue:\n \"\"\"\n Get the hue record for the provided key.\n Raises a KeyError if the provided hue key does not exist.\n :param hue: The hue to retrieve record for\n \"\"\"\n if hue not in self.hues:\n raise KeyError(f\"Unknown hue '{hue}' provided, key value must be one of {self.hues.keys()}\")\n else:\n return self.hues[hue]\n\n\nclass ScalarMetricsDict(MetricsDict):\n \"\"\"\n Specialization of the MetricsDict with Classification related functions.\n \"\"\"\n\n def __init__(self, hues: Optional[List[str]] = None, is_classification_metrics: bool = True) -> None:\n super().__init__(hues, is_classification_metrics=is_classification_metrics)\n\n def binary_classification_accuracy(self, hue: str = MetricsDict.DEFAULT_HUE_KEY) -> float:\n \"\"\"\n :param hue: The hue to restrict the values, otherwise all values will be used.\n :return: binary classification accuracy\n \"\"\"\n return binary_classification_accuracy(model_output=self.get_predictions(hue=hue),\n label=self.get_labels(hue=hue))\n\n def store_metrics_per_subject(self,\n df_logger: DataframeLogger,\n mode: ModelExecutionMode,\n cross_validation_split_index: int = DEFAULT_CROSS_VALIDATION_SPLIT_INDEX) -> None:\n \"\"\"\n Store metrics using the provided df_logger at subject level for classification models.\n :param df_logger: A data frame logger to use to write the metrics to disk.\n :param mode: Model execution mode these metrics belong to.\n :param cross_validation_split_index: cross validation split index for the epoch if performing cross val\n :return:\n \"\"\"\n for hue in self.get_hue_names():\n for prediction_entry in self.get_predictions_and_labels_per_subject(hue=hue):\n df_logger.add_record({\n LoggingColumns.Hue.value: hue,\n LoggingColumns.Patient.value: prediction_entry.subject_id,\n LoggingColumns.ModelOutput.value: prediction_entry.predictions,\n LoggingColumns.Label.value: prediction_entry.labels,\n LoggingColumns.CrossValidationSplitIndex.value: cross_validation_split_index,\n LoggingColumns.DataSplit.value: mode.value\n })\n\n @staticmethod\n def load_execution_mode_metrics_from_df(df: pd.DataFrame,\n is_classification_metrics: bool) -> Dict[ModelExecutionMode,\n Dict[int, ScalarMetricsDict]]:\n \"\"\"\n Helper function to create BinaryClassificationMetricsDict grouped by ModelExecutionMode and epoch\n from a given dataframe. The following columns must exist in the provided data frame:\n >>> LoggingColumns.DataSplit\n >>> LoggingColumns.Epoch\n\n :param df: DataFrame to use for creating the metrics dict.\n :param is_classification_metrics: If the current metrics are for classification or not.\n \"\"\"\n has_hue_column = LoggingColumns.Hue.value in df\n group_columns = [LoggingColumns.DataSplit.value, LoggingColumns.Epoch.value]\n if has_hue_column:\n group_columns.append(LoggingColumns.Hue.value)\n grouped = df.groupby(group_columns)\n result: Dict[ModelExecutionMode, Dict[int, ScalarMetricsDict]] = dict()\n hues = []\n if has_hue_column:\n hues = [h for h in df[LoggingColumns.Hue.value].unique() if h]\n for name, group in grouped:\n if has_hue_column:\n mode_str, epoch, hue = name\n else:\n mode_str, epoch = name\n hue = MetricsDict.DEFAULT_HUE_KEY\n mode = ModelExecutionMode(mode_str)\n if mode not in result:\n result[mode] = dict()\n if epoch not in result[mode]:\n result[mode][epoch] = ScalarMetricsDict(is_classification_metrics=is_classification_metrics,\n hues=hues)\n subjects = list(group[LoggingColumns.Patient.value].values)\n predictions = group[LoggingColumns.ModelOutput.value].to_numpy(dtype=np.float)\n labels = group[LoggingColumns.Label.value].to_numpy(dtype=np.float)\n result[mode][epoch].add_predictions(subjects, predictions, labels, hue=hue)\n\n return result\n\n @staticmethod\n def aggregate_and_save_execution_mode_metrics(metrics: Dict[ModelExecutionMode, Dict[int, ScalarMetricsDict]],\n data_frame_logger: DataframeLogger,\n log_info: bool = True) -> None:\n \"\"\"\n Given metrics dicts for execution modes and epochs, compute the aggregate metrics that are computed\n from the per-subject predictions. The metrics are written to the dataframe logger with the string labels\n (column names) taken from the `MetricType` enum.\n :param metrics: Mapping between epoch and subject level metrics\n :param data_frame_logger: DataFrame logger to write to and flush\n :param log_info: If True then log results as an INFO string to the default logger also.\n :return:\n \"\"\"\n for mode, epoch_metrics in metrics.items():\n for epoch, metrics_dict in epoch_metrics.items():\n # Compute the aggregate metrics using the .average method of the dictionary,\n # to ensure that we are averaging over the same metrics that would be written in training.\n averaged = metrics_dict.average(add_metrics_from_entries=True, across_hues=False)\n for hue, values_within_hue in averaged.enumerate_single_values_groupwise():\n record: Dict[str, Any] = {\n LoggingColumns.Hue.value: hue,\n }\n has_any_values = False\n for key, value in values_within_hue:\n has_any_values = True\n value_str = str(value) if isinstance(value, int) else f\"{value:0.5f}\"\n metric_name = get_column_name_for_logging(key)\n record[metric_name] = value_str\n # Do not create a row at all if there are no metrics in a particular hue. This could happen\n # for example when using multi-step RNN, where no data is in the default hue.\n if has_any_values:\n # Add epoch last to more easily navigate visually\n record[LoggingColumns.DataSplit.value] = mode.value\n record[LoggingColumns.Epoch.value] = epoch\n data_frame_logger.add_record(record)\n\n # save results to disk\n data_frame_logger.flush(log_info=log_info)\n\n\nclass SequenceMetricsDict(ScalarMetricsDict):\n \"\"\"\n Specialization of the MetricsDict with Sequence related functions.\n \"\"\"\n\n def __init__(self, hues: Optional[List[str]] = None, is_classification_metrics: bool = True) -> None:\n super().__init__(hues, is_classification_metrics=is_classification_metrics)\n\n @staticmethod\n def create(is_classification_model: bool, sequence_target_positions: List[int]) -> SequenceMetricsDict:\n # Create labels for the different prediction target positions that give numerically increasing positions\n # when using string sorting\n hues = [SequenceMetricsDict.get_hue_name_from_target_index(p)\n for p in sequence_target_positions]\n return SequenceMetricsDict(hues=hues, is_classification_metrics=is_classification_model)\n\n @staticmethod\n def get_hue_name_from_target_index(target_index: int) -> str:\n \"\"\"\n Creates a metrics hue name for sequence models, from a target index. For a sequence model that predicts\n at index 7, the hue name would be \"Seq_pos 07\"\n \"\"\"\n return f\"{SEQUENCE_POSITION_HUE_NAME_PREFIX} {target_index:02}\"\n\n @staticmethod\n def get_target_index_from_hue_name(hue_name: str) -> int:\n \"\"\"\n Extracts a sequence target index from a metrics hue name. For example, from metrics hue \"Seq_pos 07\",\n it would return 7.\n :param hue_name: hue name containing sequence target index\n \"\"\"\n if hue_name.startswith(SEQUENCE_POSITION_HUE_NAME_PREFIX):\n try:\n return int(hue_name[len(SEQUENCE_POSITION_HUE_NAME_PREFIX):])\n except:\n pass\n raise ValueError(f\"Unable to extract target index from this string: {hue_name}\")\n\n\nclass DataframeLogger:\n \"\"\"\n Single DataFrame logger for logging to CSV file\n \"\"\"\n\n def __init__(self, csv_path: FilePathOrBuffer, fixed_columns: Optional[Dict[str, Any]] = None):\n self.csv_path = csv_path\n self.fixed_columns = fixed_columns or {}\n self.records: List[Dict[str, Any]] = []\n\n def add_record(self, record: Dict[str, Any]) -> None:\n self.records.append({**record, **self.fixed_columns})\n\n def flush(self, log_info: bool = False) -> None:\n \"\"\"\n Save the internal records to a csv file.\n :param log_info: If true, write the final dataframe also to logging.info.\n \"\"\"\n import pandas as pd\n if isinstance(self.csv_path, Path):\n self.csv_path.parent.mkdir(parents=True, exist_ok=True)\n # Specifying columns such that the order in which columns appear matches the order in which\n # columns were added in the code.\n columns = self.records[0].keys() if len(self.records) > 0 else None\n df = pd.DataFrame.from_records(self.records, columns=columns)\n special_formatting = {\n MetricType.LEARNING_RATE.value: \".6e\",\n MetricType.SECONDS_PER_EPOCH.value: \".2f\",\n MetricType.SECONDS_PER_BATCH.value: \".2f\",\n }\n for column, column_format in special_formatting.items():\n if column in df:\n column_format = \"{0:\" + column_format + \"}\"\n df[column] = df[column].map(lambda x: column_format.format(x))\n df.to_csv(self.csv_path, sep=',', mode='w', index=False, float_format=\"%.6f\")\n if log_info:\n s = df.to_string(index=False, float_format=\"%.6f\")\n logging.info(f\"\\n{s}\")\n"
] |
[
[
"sklearn.metrics.roc_auc_score",
"numpy.expand_dims",
"numpy.unique",
"sklearn.metrics.precision_recall_curve",
"pandas.DataFrame",
"numpy.concatenate",
"sklearn.metrics.log_loss",
"numpy.argmax",
"numpy.mean",
"numpy.nanmean",
"pandas.DataFrame.from_records",
"sklearn.metrics.auc",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
bradyneal/rl-width
|
[
"9720ccd8bfc9fa29ffa14b9afa6b70d34199292c",
"9720ccd8bfc9fa29ffa14b9afa6b70d34199292c"
] |
[
"SAC/main.py",
"DDPG/main.py"
] |
[
"import argparse\nimport os\nimport random\nimport time\n\nimport gym\nimport imageio\nimport numpy as np\nimport torch\n\nimport SAC\nimport utils\n\nfrom utils import Logger\nfrom utils import create_folder\n\n\n# Runs policy for X episodes and returns average reward\ndef evaluate_policy(policy,\n total_timesteps,\n eval_episodes=10,\n render=False,\n skip_frame=10):\n avg_reward = 0.\n for i in range(eval_episodes):\n obs = env.reset()\n\n if render and i == 0:\n frames = [env.render(mode='rgb_array').copy()]\n\n done = False\n t = 0\n while not done:\n t += 1\n action = policy.select_action(np.array(obs))\n obs, reward, done, _ = env.step(action)\n avg_reward += reward\n if render and i == 0 and t % skip_frame == 0:\n frames.append(env.render(mode='rgb_array').copy())\n\n avg_reward /= eval_episodes\n\n\n print(\"---------------------------------------\")\n print(\"Evaluation over %d episodes: %f\" % (eval_episodes, avg_reward))\n print(\"---------------------------------------\")\n return avg_reward\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--env_name\", default=\"HalfCheetah-v1\") # OpenAI gym environment name\n parser.add_argument(\n \"--seed\", default=0, type=int) # Sets Gym, PyTorch and Numpy seeds\n parser.add_argument(\n \"--start_timesteps\", default=1e4,\n type=int) # How many time steps purely random policy is run for\n parser.add_argument(\n \"--eval_freq\", default=5e3,\n type=float) # How often (time steps) we evaluate\n parser.add_argument(\n \"--max_timesteps\", default=1e6,\n type=float) # Max time steps to run environment for\n parser.add_argument(\n \"--save_models\",\n action=\"store_true\") # Whether or not models are saved\n parser.add_argument(\n \"--save_videos\",\n action=\"store_true\") # Whether or not evaluation vides are saved\n parser.add_argument(\n \"--print_fps\", action=\"store_true\") # Whether or not print fps\n parser.add_argument(\n \"--batch_size\", default=100,\n type=int) # Batch size for both actor and critic\n parser.add_argument(\n \"--discount\", default=0.99, type=float) # Discount factor\n parser.add_argument(\n \"--tau\", default=0.005, type=float) # Target network update rate\n parser.add_argument(\n \"--initial_temperature\", default=0.2, type=float) # SAC temperature\n parser.add_argument(\n \"--learn_temperature\",\n action=\"store_true\") # Whether or not learn the temperature\n parser.add_argument(\n \"--policy_freq\", default=2,\n type=int) # Frequency of delayed policy updates\n parser.add_argument(\n \"--normalize_returns\", action=\"store_true\") # Normalize returns\n parser.add_argument(\"--linear_lr_decay\", action=\"store_true\") # Decay lr\n\n parser.add_argument(\"--policy_name\", default=\"SAC\", help = \"SAC\")\n parser.add_argument(\"--folder\", type=str, default='./results/') \n parser.add_argument(\"--use_logger\", action=\"store_true\", default=False, help='whether to use logging or not')\n \n\n parser.add_argument(\"--width\", default=256, type=int) ## only one width hparam - same width across layers \n\n args = parser.parse_args()\n\n if args.normalize_returns and args.initial_temperature != 0.01:\n print(\"Please use temperature of 0.01 for normalized returns\")\n\n if args.use_logger:\n file_name = \"%s_%s_%s\" % (args.policy_name, args.env_name, str(args.seed))\n logger = Logger(experiment_name = args.policy_name, environment_name = args.env_name, width_net=str(args.width), folder = args.folder)\n logger.save_args(args)\n\n print ('Saving to', logger.save_folder)\n\n env = gym.make(args.env_name)\n\n # Set seeds\n seed = np.random.randint(20)\n env.seed(seed)\n torch.manual_seed(seed)\n np.random.seed(seed)\n\n\n # Set seeds\n torch.manual_seed(seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(seed)\n np.random.seed(seed)\n random.seed(seed)\n env.seed(seed)\n\n\n if args.use_logger: \n print (\"---------------------------------------\")\n print (\"Settings: %s\" % (file_name))\n print (\"Seed : %s\" % (seed))\n print (\"---------------------------------------\")\n\n\n\n if torch.cuda.is_available():\n torch.set_num_threads(1)\n\n state_dim = env.observation_space.shape[0]\n action_dim = env.action_space.shape[0]\n max_action = float(env.action_space.high[0])\n\n # Initialize policy\n if args.policy_name == \"SAC\":\n policy = SAC.SAC(state_dim, action_dim, max_action, args.initial_temperature, args.width)\n\n\n\n replay_buffer = utils.ReplayBuffer(norm_ret=args.normalize_returns)\n\n # Evaluate untrained policy\n evaluations = [evaluate_policy(policy, 0, render=args.save_videos)]\n\n total_timesteps = 0\n timesteps_since_eval = 0\n episode_num = 0\n done = True\n\n if args.print_fps:\n if torch.cuda.is_available():\n torch.cuda.synchronize()\n prev_time = time.time()\n prev_eval_timesteps = 0\n\n while total_timesteps < args.max_timesteps:\n\n if args.linear_lr_decay:\n policy.set_lr(1e-3 * (1 - float(total_timesteps) / args.max_timesteps))\n\n if done:\n if total_timesteps != 0:\n if args.print_fps:\n if torch.cuda.is_available():\n torch.cuda.synchronize()\n fps = (total_timesteps - prev_eval_timesteps) / (\n time.time() - prev_time)\n print((\n \"Total T: %d FPS %d Episode Num: %d Episode T: %d Reward: %f\"\n ) % (total_timesteps, fps, episode_num, episode_timesteps,\n episode_reward))\n else:\n print(\n (\"Total T: %d Episode Num: %d Episode T: %d Reward: %f\"\n ) % (total_timesteps, episode_num, episode_timesteps,\n episode_reward))\n\n # Evaluate episode\n if timesteps_since_eval >= args.eval_freq:\n timesteps_since_eval %= args.eval_freq\n evaluations.append(evaluate_policy(policy, total_timesteps, render=args.save_videos))\n\n if args.use_logger:\n logger.record_reward(evaluations)\n logger.save()\n # np.save(\"./results/%s\" % (file_name), evaluations)\n\n if args.print_fps:\n if torch.cuda.is_available():\n torch.cuda.synchronize()\n prev_time = time.time()\n prev_eval_timesteps = total_timesteps\n\n # Reset environment\n obs = env.reset()\n done = False\n episode_reward = 0\n episode_timesteps = 0\n episode_num += 1\n\n # Select action randomly or according to policy\n if total_timesteps < args.start_timesteps:\n action = env.action_space.sample()\n else:\n action = policy.sample_action(np.array(obs))\n\n\n if total_timesteps > 1e3:\n policy.train(replay_buffer, total_timesteps, args.batch_size,\n args.discount, args.tau, args.policy_freq,\n -action_dim if args.learn_temperature else None)\n\n # Perform action\n new_obs, reward, done, _ = env.step(action)\n done_bool = 0 if episode_timesteps + 1 == env._max_episode_steps else float(done)\n\n episode_reward += reward\n\n # Store data in replay buffer\n replay_buffer.add((obs, new_obs, action, reward, done_bool))\n\n obs = new_obs\n\n episode_timesteps += 1\n total_timesteps += 1\n timesteps_since_eval += 1\n\n\n # Final evaluation\n evaluations.append(evaluate_policy(policy, total_timesteps, render=args.save_videos))\n if args.use_logger:\n logger.record_reward(evaluations)\n logger.save()\n\n",
"import numpy as np\nimport torch\nimport gym\nimport argparse\nimport os\n\nimport utils\nimport TD3\nimport DDPG\nfrom utils import Logger\nfrom utils import create_folder\n\n\n# Runs policy for X episodes and returns average reward\ndef evaluate_policy(policy, eval_episodes=10):\n\tavg_reward = 0.\n\tfor _ in range(eval_episodes):\n\t\tobs = env.reset()\n\t\tdone = False\n\t\twhile not done:\n\t\t\taction = policy.select_action(np.array(obs))\n\t\t\tobs, reward, done, _ = env.step(action)\n\t\t\tavg_reward += reward\n\n\tavg_reward /= eval_episodes\n\n\tprint (\"---------------------------------------\")\n\tprint (\"Evaluation over %d episodes: %f\" % (eval_episodes, avg_reward))\n\tprint (\"---------------------------------------\")\n\treturn avg_reward\n\n\nif __name__ == \"__main__\":\n\t\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"--policy_name\", default=\"DDPG\", help=\"DDPG\")\t\t\t\t\t# Policy name\n\tparser.add_argument(\"--env_name\", default=\"HalfCheetah-v1\")\t\t\t# OpenAI gym environment name\n\tparser.add_argument(\"--seed\", default=0, type=int)\t\t\t\t\t# Sets Gym, PyTorch and Numpy seeds\n\tparser.add_argument(\"--start_timesteps\", default=1e4, type=int)\t\t# How many time steps purely random policy is run for\n\tparser.add_argument(\"--eval_freq\", default=5e3, type=float)\t\t\t# How often (time steps) we evaluate\n\tparser.add_argument(\"--max_timesteps\", default=1e6, type=float)\t\t# Max time steps to run environment for\n\tparser.add_argument(\"--save_models\", default=True)\t\t\t# Whether or not models are saved\n\tparser.add_argument(\"--expl_noise\", default=0.1, type=float)\t\t# Std of Gaussian exploration noise\n\tparser.add_argument(\"--batch_size\", default=100, type=int)\t\t\t# Batch size for both actor and critic\n\tparser.add_argument(\"--discount\", default=0.99, type=float)\t\t\t# Discount factor\n\tparser.add_argument(\"--tau\", default=0.005, type=float)\t\t\t\t# Target network update rate\n\tparser.add_argument(\"--policy_noise\", default=0.2, type=float)\t\t# Noise added to target policy during critic update\n\tparser.add_argument(\"--noise_clip\", default=0.5, type=float)\t\t# Range to clip target policy noise\n\tparser.add_argument(\"--policy_freq\", default=2, type=int)\t\t\t# Frequency of delayed policy updates\n\tparser.add_argument(\"--ent_weight\", default=0.01, type=float)\t\t# Range to clip target policy noise\n\tparser.add_argument(\"--folder\", type=str, default='./results/')\t\n\tparser.add_argument(\"--use_logger\", action=\"store_true\", default=False, help='whether to use logging or not')\n\n\n\tparser.add_argument(\"--width_l1\", default=400, type=int)\n\tparser.add_argument(\"--width_l2\", default=300, type=int)\t\n\n\n\targs = parser.parse_args()\n\n\tif args.use_logger:\n\t\tfile_name = \"%s_%s_%s\" % (args.policy_name, args.env_name, str(args.seed))\n\n\t\tlogger = Logger(experiment_name = args.policy_name, environment_name = args.env_name, width_net1=\"width_l1_\" + str(args.width_l1), width_net2=\"width_l2_\" + str(args.width_l2), folder = args.folder)\n\t\tlogger.save_args(args)\n\n\t\tprint ('Saving to', logger.save_folder)\n\n\tif not os.path.exists(\"./results\"):\n\t\tos.makedirs(\"./results\")\n\tif args.save_models and not os.path.exists(\"./pytorch_models\"):\n\t\tos.makedirs(\"./pytorch_models\")\n\n\tenv = gym.make(args.env_name)\n\n\t# Set seeds\n\tseed = np.random.randint(10)\n\tenv.seed(seed)\n\ttorch.manual_seed(seed)\n\tnp.random.seed(seed)\n\n\tif args.use_logger:\t\n\t\tprint (\"---------------------------------------\")\n\t\tprint (\"Settings: %s\" % (file_name))\n\t\tprint (\"Seed : %s\" % (seed))\n\t\tprint (\"---------------------------------------\")\n\n\tstate_dim = env.observation_space.shape[0]\n\taction_dim = env.action_space.shape[0] \n\tmax_action = float(env.action_space.high[0])\n\n\t# Initialize policy\n\tif args.policy_name == \"DDPG\": policy = DDPG.DDPG(state_dim, action_dim, max_action, args.width_l1, args.width_l2)\n\n\treplay_buffer = utils.ReplayBuffer()\n\n\t# Evaluate untrained policy\n\tevaluations = [evaluate_policy(policy)] \n\tepisode_reward = 0 \n\ttraining_evaluations = [episode_reward]\n\n\ttotal_timesteps = 0\n\ttimesteps_since_eval = 0\n\tepisode_num = 0\n\tdone = True \n\n\n\twhile total_timesteps < args.max_timesteps:\n\t\t\n\t\tif done: \n\t\t\tif total_timesteps != 0: \n\t\t\t\tprint((\"Total T: %d Episode Num: %d Episode T: %d Reward: %f\") % (total_timesteps, episode_num, episode_timesteps, episode_reward))\n\n\t\t\t\tpolicy.train(replay_buffer, episode_timesteps, args.batch_size, args.discount, args.tau)\n\t\t\t\n\t\t\t# Evaluate episode\n\t\t\tif timesteps_since_eval >= args.eval_freq:\n\t\t\t\ttimesteps_since_eval %= args.eval_freq\n\t\t\t\tevaluations.append(evaluate_policy(policy))\n\t\t\t\tif args.use_logger:\n\t\t\t\t\tlogger.record_reward(evaluations)\n\t\t\t\t\tlogger.save()\t\t\t\n\t\t\t\t\tif args.save_models: policy.save(file_name, directory=\"./pytorch_models\")\n\t\t\t\t\tnp.save(\"./results/%s\" % (file_name), evaluations) \n\t\t\t\n\t\t\t# Reset environment\n\t\t\tobs = env.reset()\n\t\t\tdone = False\n\t\t\ttraining_evaluations.append(episode_reward)\n\n\t\t\tif args.use_logger:\n\t\t\t\tlogger.training_record_reward(training_evaluations)\n\t\t\t\tlogger.save_2()\n\t\t\t\t\n\t\t\tepisode_reward = 0\n\t\t\tepisode_timesteps = 0\n\t\t\tepisode_num += 1 \n\t\t\n\n\t\tif total_timesteps < args.start_timesteps:\n\t\t\taction = env.action_space.sample()\n\t\telse:\n\t\t\taction = policy.select_action(np.array(obs))\n\t\t\taction = (action + np.random.normal(0, args.expl_noise, size=env.action_space.shape[0])).clip(env.action_space.low, env.action_space.high)\t\t\t\t\n\n\t\tnew_obs, reward, done, _ = env.step(action) \n\n\t\tdone_bool = 0 if episode_timesteps + 1 == env._max_episode_steps else float(done)\n\t\tepisode_reward += reward\n\t\treplay_buffer.add((obs, new_obs, action, reward, done_bool))\n\n\t\tobs = new_obs\n\t\tepisode_timesteps += 1\n\t\ttotal_timesteps += 1\n\t\ttimesteps_since_eval += 1\n\t\t\n\t# Final evaluation \n\tevaluations.append(evaluate_policy(policy))\n\ttraining_evaluations.append(episode_reward)\n\n\tif args.use_logger:\n\t\tlogger.record_reward(evaluations)\n\t\tlogger.training_record_reward(training_evaluations)\n\t\tlogger.save()\n\t\tlogger.save_2()\n\t\tif args.save_models: policy.save(\"%s\" % (file_name), directory=\"./pytorch_models\")\n\t\tnp.save(\"./results/%s\" % (file_name), evaluations) "
] |
[
[
"torch.cuda.synchronize",
"numpy.random.seed",
"torch.manual_seed",
"torch.set_num_threads",
"torch.cuda.manual_seed_all",
"torch.cuda.is_available",
"numpy.array",
"numpy.random.randint"
],
[
"numpy.random.seed",
"torch.manual_seed",
"numpy.save",
"numpy.random.normal",
"numpy.array",
"numpy.random.randint"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kylebarron/geopandas
|
[
"22b5a0dc23be8876a3270d0c009db5bd765fabf3"
] |
[
"geopandas/io/file.py"
] |
[
"from distutils.version import LooseVersion\n\nimport numpy as np\n\nimport fiona\n\nfrom geopandas import GeoDataFrame, GeoSeries\n\ntry:\n from fiona import Env as fiona_env\nexcept ImportError:\n from fiona import drivers as fiona_env\n# Adapted from pandas.io.common\nfrom urllib.request import urlopen as _urlopen\nfrom urllib.parse import urlparse as parse_url\nfrom urllib.parse import uses_relative, uses_netloc, uses_params\n\n_FIONA18 = LooseVersion(fiona.__version__) >= LooseVersion(\"1.8\")\n\n\n_VALID_URLS = set(uses_relative + uses_netloc + uses_params)\n_VALID_URLS.discard(\"\")\n\n\ndef _is_url(url):\n \"\"\"Check to see if *url* has a valid protocol.\"\"\"\n try:\n return parse_url(url).scheme in _VALID_URLS\n except Exception:\n return False\n\n\ndef read_file(filename, bbox=None, **kwargs):\n \"\"\"\n Returns a GeoDataFrame from a file or URL.\n\n Parameters\n ----------\n filename: str\n Either the absolute or relative path to the file or URL to\n be opened.\n bbox : tuple | GeoDataFrame or GeoSeries, default None\n Filter features by given bounding box, GeoSeries, or GeoDataFrame.\n CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame.\n **kwargs:\n Keyword args to be passed to the `open` or `BytesCollection` method\n in the fiona library when opening the file. For more information on\n possible keywords, type:\n ``import fiona; help(fiona.open)``\n\n Examples\n --------\n >>> df = geopandas.read_file(\"nybb.shp\")\n\n Returns\n -------\n geodataframe : GeoDataFrame\n \"\"\"\n if _is_url(filename):\n req = _urlopen(filename)\n path_or_bytes = req.read()\n reader = fiona.BytesCollection\n else:\n path_or_bytes = filename\n reader = fiona.open\n\n with fiona_env():\n with reader(path_or_bytes, **kwargs) as features:\n\n # In a future Fiona release the crs attribute of features will\n # no longer be a dict. The following code will be both forward\n # and backward compatible.\n if hasattr(features.crs, \"to_dict\"):\n crs = features.crs.to_dict()\n else:\n crs = features.crs\n\n if bbox is not None:\n if isinstance(bbox, GeoDataFrame) or isinstance(bbox, GeoSeries):\n bbox = tuple(bbox.to_crs(crs).total_bounds)\n assert len(bbox) == 4\n f_filt = features.filter(bbox=bbox)\n else:\n f_filt = features\n\n columns = list(features.meta[\"schema\"][\"properties\"]) + [\"geometry\"]\n gdf = GeoDataFrame.from_features(f_filt, crs=crs, columns=columns)\n\n return gdf\n\n\ndef to_file(df, filename, driver=\"ESRI Shapefile\", schema=None, **kwargs):\n \"\"\"\n Write this GeoDataFrame to an OGR data source\n\n A dictionary of supported OGR providers is available via:\n >>> import fiona\n >>> fiona.supported_drivers\n\n Parameters\n ----------\n df : GeoDataFrame to be written\n filename : string\n File path or file handle to write to.\n driver : string, default 'ESRI Shapefile'\n The OGR format driver used to write the vector file.\n schema : dict, default None\n If specified, the schema dictionary is passed to Fiona to\n better control how the file is written. If None, GeoPandas\n will determine the schema based on each column's dtype\n\n The *kwargs* are passed to fiona.open and can be used to write\n to multi-layer data, store data within archives (zip files), etc.\n The path may specify a fiona VSI scheme.\n \"\"\"\n if schema is None:\n schema = infer_schema(df)\n with fiona_env():\n with fiona.open(\n filename, \"w\", driver=driver, crs=df.crs, schema=schema, **kwargs\n ) as colxn:\n colxn.writerecords(df.iterfeatures())\n\n\ndef infer_schema(df):\n try:\n from collections import OrderedDict\n except ImportError:\n from ordereddict import OrderedDict\n\n def convert_type(column, in_type):\n if in_type == object:\n return \"str\"\n if in_type.name.startswith(\"datetime64\"):\n # numpy datetime type regardless of frequency\n return \"datetime\"\n out_type = type(np.zeros(1, in_type).item()).__name__\n if out_type == \"long\":\n out_type = \"int\"\n if not _FIONA18 and out_type == \"bool\":\n raise ValueError(\n 'column \"{}\" is boolean type, '.format(column)\n + \"which is unsupported in file writing with fiona \"\n \"< 1.8. Consider casting the column to int type.\"\n )\n return out_type\n\n properties = OrderedDict(\n [\n (col, convert_type(col, _type))\n for col, _type in zip(df.columns, df.dtypes)\n if col != df._geometry_column_name\n ]\n )\n\n if df.empty:\n raise ValueError(\"Cannot write empty DataFrame to file.\")\n\n # Since https://github.com/Toblerity/Fiona/issues/446 resolution,\n # Fiona allows a list of geometry types\n geom_types = _geometry_types(df)\n\n schema = {\"geometry\": geom_types, \"properties\": properties}\n\n return schema\n\n\ndef _geometry_types(df):\n \"\"\"\n Determine the geometry types in the GeoDataFrame for the schema.\n \"\"\"\n if _FIONA18:\n # Starting from Fiona 1.8, schema submitted to fiona to write a gdf\n # can have mixed geometries:\n # - 3D and 2D shapes can coexist in inferred schema\n # - Shape and MultiShape types can (and must) coexist in inferred\n # schema\n geom_types_2D = df[~df.geometry.has_z].geometry.geom_type.unique()\n geom_types_2D = [gtype for gtype in geom_types_2D if gtype is not None]\n geom_types_3D = df[df.geometry.has_z].geometry.geom_type.unique()\n geom_types_3D = [\"3D \" + gtype for gtype in geom_types_3D if gtype is not None]\n geom_types = geom_types_3D + geom_types_2D\n\n else:\n # Before Fiona 1.8, schema submitted to write a gdf should have\n # one single geometry type whenever possible:\n # - 3D and 2D shapes cannot coexist in inferred schema\n # - Shape and MultiShape can not coexist in inferred schema\n geom_types = _geometry_types_back_compat(df)\n\n if len(geom_types) == 0:\n # Default geometry type supported by Fiona\n # (Since https://github.com/Toblerity/Fiona/issues/446 resolution)\n return \"Unknown\"\n\n if len(geom_types) == 1:\n geom_types = geom_types[0]\n\n return geom_types\n\n\ndef _geometry_types_back_compat(df):\n \"\"\"\n for backward compatibility with Fiona<1.8 only\n \"\"\"\n unique_geom_types = df.geometry.geom_type.unique()\n unique_geom_types = [gtype for gtype in unique_geom_types if gtype is not None]\n\n # merge single and Multi types (eg Polygon and MultiPolygon)\n unique_geom_types = [\n gtype\n for gtype in unique_geom_types\n if not gtype.startswith(\"Multi\") or gtype[5:] not in unique_geom_types\n ]\n\n if df.geometry.has_z.any():\n # declare all geometries as 3D geometries\n unique_geom_types = [\"3D \" + type for type in unique_geom_types]\n # by default, all geometries are 2D geometries\n\n return unique_geom_types\n"
] |
[
[
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zehuilu/DrMaMP-Distributed-Real-time-Multi-agent-Mission-Planning-Algorithm
|
[
"894875ebddf7d1f6bbf7a47ce82f05d7be2bafdc",
"894875ebddf7d1f6bbf7a47ce82f05d7be2bafdc"
] |
[
"src/PathPlanner.py",
"test/single_compare_MissionPlanning_with_legacy.py"
] |
[
"#!/usr/bin/env python3\nimport asyncio\nimport time\nfrom itertools import chain\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pathmagic\nwith pathmagic.context():\n import DrMaMP\n from discrete_path_to_time_traj import discrete_path_to_time_traj\n from interpolate_traj import interpolate_traj\n from AgentFSM import AgentFSM\n\n\n# when distance between A and B < this number, we say A and B have same position\nDISTANCE_THRESHOLD = 1.414\n\n\nclass PathPlanner:\n solver_mode: str\n num_agents: int # number of agents\n planning_frequency: int # planning and visualization frequency in Hz\n list_AgentFSM: list # a list of AgentFSM objects\n\n def __init__(self, MySimulator):\n \"\"\"\n Initialize a Planner Object.\n \"\"\"\n self.MySimulator = MySimulator\n self.list_AgentFSM = list()\n\n async def run_planner(self, input_dict: dict):\n \"\"\"\n Run the planner online.\n\n Inputs:\n input_dict: a dictionary includes solver_mode, agent_velocity_ave,\n planning_frequency, and positions for agents and targets\n \"\"\"\n self.solver_mode = input_dict[\"solver_mode\"]\n self.planning_frequency = input_dict[\"planning_frequency\"]\n self.loading_planning_function()\n\n # a list includes the average velocity of each agent\n agent_velocity_ave = input_dict[\"agent_velocity_ave\"]\n # the initial agents and targets positions\n if \"agents_position\" in input_dict and \"targets_position\" in input_dict:\n agents_position = input_dict[\"agents_position\"]\n targets_position = input_dict[\"targets_position\"]\n self.num_agents = int(len(agents_position) / 2)\n else:\n Exception(\"Need agents positions and targets positions\")\n\n # initialize Finite State Machine for each agent\n for idx_agent in range(self.num_agents):\n self.list_AgentFSM.append(AgentFSM(agentIdx=idx_agent, distanceThreshold=DISTANCE_THRESHOLD))\n # initialize the FSM with a set of targets\n self.list_AgentFSM[idx_agent].initFSM(targetSetTotal=targets_position[idx_agent])\n\n time_escape = 50 # shut down the iteration after this time [sec]\n time_begin = time.time()\n time_used = 0 # initialize the global time as 0\n end_flag_list = False # initialize, False when at least one agent state is not \"End\"\n ax = self.MySimulator.create_realtime_plot() # create a realtime plotting figure\n\n while((time_used < time_escape) and not end_flag_list):\n t_start = time.time()\n\n # update the map by MySimulator.map_array\n # convert 2D numpy array to 1D list\n # world_map = self.MySimulator.map_array.flatten().tolist()\n\n t0 = time.time()\n # do the planning\n path_all_agents = self.PlanningFunction({\"agents_position\": agents_position, \"targets_position\": targets_position})\n t1 = time.time()\n time_algorithm_ms = round((t1-t0)*1000, 2) # milliseconds\n # print(\"Time used [sec]:\" + str(t1 - t0))\n\n # update the figure\n self.MySimulator.update_realtime_plot(path_all_agents, agents_position, list(chain.from_iterable(targets_position)), [], [], [], ax)\n\n # update the agents positions\n agents_position, targets_position, end_flag_list = self.update_agents_positions(\n path_all_agents, agents_position, targets_position, agent_velocity_ave, dt_update=1/self.planning_frequency)\n\n # plot the algorithm time\n time_str = \"Computation Time [ms]: \" + str(time_algorithm_ms)\n plt.text(0.25, 0.9, time_str, fontsize=14, transform=plt.gcf().transFigure)\n\n plt.pause(1E-6)\n time_sleep = max(0, 1/self.planning_frequency - time.time() + t_start)\n time_used = time.time() - time_begin\n print(\"Current Time [sec]: \" + str(time_used))\n await asyncio.sleep(time_sleep)\n\n # update the figure one more time\n self.MySimulator.update_realtime_plot([], agents_position, list(chain.from_iterable(targets_position)), [], [], [], ax)\n plt.pause(5)\n\n def loading_planning_function(self):\n \"\"\"\n Loading a planning function by self.solver_mode.\n \"\"\"\n PlanningFunction = getattr(DrMaMP, self.solver_mode)\n self.PlanningFunction = {\n \"PathPlanningMultiAgent\": lambda input_dict: \\\n PlanningFunction(input_dict[\"agents_position\"], input_dict[\"targets_position\"],\n self.MySimulator.map_array.flatten().tolist(), self.MySimulator.map_width, self.MySimulator.map_height)\n }[self.solver_mode]\n\n def update_agents_positions(self, path_all_agents: list, agents_position: list,\n targets_position: list, agent_velocity_ave: list, dt_update: float):\n \"\"\"\n Update the agents positions by moving forward along the previous planning trajectory.\n\n Inputs:\n path_all_agents: a 3D list, each sub-list is a path of an agent.\n For example, path_all_agents[0] = [[x0,y0, ..., x1,y1], [x1,y1, ..., x2,y2], [x2,y2, ..., x3,y3], ...]\n \"\"\"\n # initialize the output\n agents_position_now = list()\n end_flag_list = list()\n targets_position_new = list()\n\n for idx_agent in range(len(path_all_agents)):\n # get current agent and targets\n agent_position_this = agents_position[2*idx_agent : 2*idx_agent+2]\n targets_position_set_this = targets_position[idx_agent]\n\n # 2d path to 1d path [x0,y0, ..., x1,y1, x1,y1, ..., x2,y2, x2,y2, ..., x3,y3, x3,y3, ...]\n path_agent_this = list(chain.from_iterable(path_all_agents[idx_agent]))\n\n # transit states\n _, targets_position_new_this = self.list_AgentFSM[idx_agent].transition(agentPositionNow=agent_position_this, targetSetTotal=targets_position_set_this)\n\n # different actions based on current states\n if self.list_AgentFSM[idx_agent].StateNow.stateName == \"Unassigned\":\n agents_position_now.extend(agent_position_this)\n\n elif self.list_AgentFSM[idx_agent].StateNow.stateName == \"End\":\n # agents_position_now.extend(targets_position_set_this[-2:])\n agents_position_now.extend(agent_position_this)\n\n elif self.list_AgentFSM[idx_agent].StateNow.stateName == \"Assigned\":\n # discrete path without time information converting to time trajectory\n time_queue_vec, position_traj = discrete_path_to_time_traj(\n np.array(path_agent_this).reshape((-1,2)).tolist(),\n dt=0.1, velocity_ave=agent_velocity_ave[idx_agent], interp_kind='linear')\n\n # position_traj is a numpy array\n if len(position_traj) > 0:\n # if there exists feasible path, move one time step (dt_update) forward\n posi_now = interpolate_traj(dt_update, time_queue_vec, position_traj.T, interpolate_kind='traj')\n agents_position_now.extend(posi_now.T.round().astype(int).tolist()[0])\n else:\n # there doesn't exist feasible path, don't move\n agents_position_now.extend(agent_position_this)\n\n elif self.list_AgentFSM[idx_agent].StateNow.stateName == \"Completed\":\n agents_position_now.extend(targets_position_set_this[2*self.list_AgentFSM[idx_agent].targetIdxNow : \n 2*self.list_AgentFSM[idx_agent].targetIdxNow+2])\n else:\n Exception(\"AgentFSM only supports 4 states: Unassigned, Assigned, Completed, End!\")\n\n # if state is \"End\", this agent completed all assigned tasks\n if self.list_AgentFSM[idx_agent].StateNow.stateName == \"End\":\n end_flag_list.append(True)\n else:\n end_flag_list.append(False)\n\n # update new targets positions list\n targets_position_new.append(targets_position_new_this)\n\n # True if all agents states are \"End\"\n end_flag_list = all(end_flag_list)\n return agents_position_now, targets_position_new, end_flag_list\n",
"#!/usr/bin/env python3\nimport time\nimport matplotlib.pyplot as plt\nimport pathmagic\nwith pathmagic.context():\n import DrMaMP\n from Simulator import Simulator\n\n\nif __name__ == \"__main__\":\n # define the world\n map_width_meter = 25.0\n map_height_meter = 25.0\n map_resolution = 2\n value_non_obs = 0 # the cell is empty\n value_obs = 255 # the cell is blocked\n # create a simulator\n Simulator = Simulator(map_width_meter, map_height_meter, map_resolution, value_non_obs, value_obs)\n # number of obstacles\n num_obs = 20\n # [width, length] size of each obstacle [meter]\n size_obs = [1, 1]\n # generate random obstacles\n Simulator.generate_random_obs(num_obs, size_obs)\n # convert 2D numpy array to 1D list\n world_map = Simulator.map_array.flatten().tolist()\n\n # generate agents and targets randomly\n num_agents = 10\n num_targets = 50\n agent_position, targets_position = Simulator.generate_agents_and_targets(num_agents, num_targets)\n\n # parameters for k-means\n num_cluster = num_agents\n number_of_iterations = 200\n\n # legacy method\n t0 = time.time()\n path_all_agents, task_allocation_all_agents, cluster_centers, points_idx_for_clusters, cluster_assigned_idx\\\n = DrMaMP.MissionPlanning_legacy(agent_position, targets_position, num_cluster,\n number_of_iterations, world_map, Simulator.map_width,\n Simulator.map_height)\n t1 = time.time()\n print(\"Legacy time [sec]:\" + str(t1 - t0))\n # visualization\n Simulator.plot_paths(path_all_agents, agent_position, targets_position, task_allocation_all_agents, cluster_centers, points_idx_for_clusters)\n Simulator.plot_cluster_assign(agent_position, targets_position, points_idx_for_clusters, cluster_centers, cluster_assigned_idx)\n\n # current method\n t0 = time.time()\n path_all_agents, task_allocation_all_agents, cluster_centers, points_idx_for_clusters, cluster_assigned_idx\\\n = DrMaMP.MissionPlanning(agent_position, targets_position, num_cluster,\n number_of_iterations, world_map, Simulator.map_width,\n Simulator.map_height)\n t1 = time.time()\n print(\"Current method time [sec]:\" + str(t1 - t0))\n # visualization\n Simulator.plot_paths(path_all_agents, agent_position, targets_position, task_allocation_all_agents, cluster_centers, points_idx_for_clusters)\n Simulator.plot_cluster_assign(agent_position, targets_position, points_idx_for_clusters, cluster_centers, cluster_assigned_idx)\n plt.show()\n"
] |
[
[
"numpy.array",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.gcf"
],
[
"matplotlib.pyplot.show"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
crmauceri/pytorch-deeplab-xception
|
[
"aec2cb7b0c09c346519c6bf22c2cbf419021fdc7"
] |
[
"deeplab3/doc/deeplab_xception.py"
] |
[
"import math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.model_zoo as model_zoo\nfrom deeplab3.modeling.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d\n\nBatchNorm2d = SynchronizedBatchNorm2d\n\nclass SeparableConv2d(nn.Module):\n def __init__(self, inplanes, planes, kernel_size=3, stride=1, padding=0, dilation=1, bias=False):\n super(SeparableConv2d, self)._init_()\n\n self.conv1 = nn.Conv2d(inplanes, inplanes, kernel_size, stride, padding, dilation,\n groups=inplanes, bias=bias)\n self.pointwise = nn.Conv2d(inplanes, planes, 1, 1, 0, 1, 1, bias=bias)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.pointwise(x)\n return x\n\n\ndef fixed_padding(inputs, kernel_size, dilation):\n kernel_size_effective = kernel_size + (kernel_size - 1) * (dilation - 1)\n pad_total = kernel_size_effective - 1\n pad_beg = pad_total // 2\n pad_end = pad_total - pad_beg\n padded_inputs = F.pad(inputs, (pad_beg, pad_end, pad_beg, pad_end))\n return padded_inputs\n\n\nclass SeparableConv2d_same(nn.Module):\n def __init__(self, inplanes, planes, kernel_size=3, stride=1, dilation=1, bias=False):\n super(SeparableConv2d_same, self).__init__()\n\n self.conv1 = nn.Conv2d(inplanes, inplanes, kernel_size, stride, 0, dilation,\n groups=inplanes, bias=bias)\n self.pointwise = nn.Conv2d(inplanes, planes, 1, 1, 0, 1, 1, bias=bias)\n\n def forward(self, x):\n x = fixed_padding(x, self.conv1.kernel_size[0], dilation=self.conv1.dilation[0])\n x = self.conv1(x)\n x = self.pointwise(x)\n return x\n\n\nclass Block(nn.Module):\n def __init__(self, inplanes, planes, reps, stride=1, dilation=1, start_with_relu=True, grow_first=True, is_last=False):\n super(Block, self).__init__()\n\n if planes != inplanes or stride != 1:\n self.skip = nn.Conv2d(inplanes, planes, 1, stride=stride, bias=False)\n self.skipbn = BatchNorm2d(planes)\n else:\n self.skip = None\n\n self.relu = nn.ReLU(inplace=True)\n rep = []\n\n filters = inplanes\n if grow_first:\n rep.append(self.relu)\n rep.append(SeparableConv2d_same(inplanes, planes, 3, stride=1, dilation=dilation))\n rep.append(BatchNorm2d(planes))\n filters = planes\n\n for i in range(reps - 1):\n rep.append(self.relu)\n rep.append(SeparableConv2d_same(filters, filters, 3, stride=1, dilation=dilation))\n rep.append(BatchNorm2d(filters))\n\n if not grow_first:\n rep.append(self.relu)\n rep.append(SeparableConv2d_same(inplanes, planes, 3, stride=1, dilation=dilation))\n rep.append(BatchNorm2d(planes))\n\n if not start_with_relu:\n rep = rep[1:]\n\n if stride != 1:\n rep.append(SeparableConv2d_same(planes, planes, 3, stride=2))\n\n if stride == 1 and is_last:\n rep.append(SeparableConv2d_same(planes, planes, 3, stride=1))\n\n\n self.rep = nn.Sequential(*rep)\n\n def forward(self, inp):\n x = self.rep(inp)\n\n if self.skip is not None:\n skip = self.skip(inp)\n skip = self.skipbn(skip)\n else:\n skip = inp\n\n x += skip\n\n return x\n\n\nclass Xception(nn.Module):\n \"\"\"\n Modified Alighed Xception\n \"\"\"\n def __init__(self, inplanes=3, os=16, pretrained=False):\n super(Xception, self).__init__()\n\n if os == 16:\n entry_block3_stride = 2\n middle_block_dilation = 1\n exit_block_dilations = (1, 2)\n elif os == 8:\n entry_block3_stride = 1\n middle_block_dilation = 2\n exit_block_dilations = (2, 4)\n else:\n raise NotImplementedError\n\n\n # Entry flow\n self.conv1 = nn.Conv2d(inplanes, 32, 3, stride=2, padding=1, bias=False)\n self.bn1 = BatchNorm2d(32)\n self.relu = nn.ReLU(inplace=True)\n\n self.conv2 = nn.Conv2d(32, 64, 3, stride=1, padding=1, bias=False)\n self.bn2 = BatchNorm2d(64)\n\n self.block1 = Block(64, 128, reps=2, stride=2, start_with_relu=False)\n self.block2 = Block(128, 256, reps=2, stride=2, start_with_relu=True, grow_first=True)\n self.block3 = Block(256, 728, reps=2, stride=entry_block3_stride, start_with_relu=True, grow_first=True,\n is_last=True)\n\n # Middle flow\n self.block4 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n self.block5 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n self.block6 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n self.block7 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n self.block8 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n self.block9 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n self.block10 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n self.block11 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n self.block12 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n self.block13 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n self.block14 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n self.block15 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n self.block16 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n self.block17 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n self.block18 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n self.block19 = Block(728, 728, reps=3, stride=1, dilation=middle_block_dilation, start_with_relu=True, grow_first=True)\n\n # Exit flow\n self.block20 = Block(728, 1024, reps=2, stride=1, dilation=exit_block_dilations[0],\n start_with_relu=True, grow_first=False, is_last=True)\n\n self.conv3 = SeparableConv2d_same(1024, 1536, 3, stride=1, dilation=exit_block_dilations[1])\n self.bn3 = BatchNorm2d(1536)\n\n self.conv4 = SeparableConv2d_same(1536, 1536, 3, stride=1, dilation=exit_block_dilations[1])\n self.bn4 = BatchNorm2d(1536)\n\n self.conv5 = SeparableConv2d_same(1536, 2048, 3, stride=1, dilation=exit_block_dilations[1])\n self.bn5 = BatchNorm2d(2048)\n\n # Init weights\n self._init_weight()\n\n # Load pretrained model\n if pretrained:\n self._load_xception_pretrained()\n\n def forward(self, x):\n # Entry flow\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.relu(x)\n\n x = self.block1(x)\n low_level_feat = x\n x = self.block2(x)\n x = self.block3(x)\n\n # Middle flow\n x = self.block4(x)\n x = self.block5(x)\n x = self.block6(x)\n x = self.block7(x)\n x = self.block8(x)\n x = self.block9(x)\n x = self.block10(x)\n x = self.block11(x)\n x = self.block12(x)\n x = self.block13(x)\n x = self.block14(x)\n x = self.block15(x)\n x = self.block16(x)\n x = self.block17(x)\n x = self.block18(x)\n x = self.block19(x)\n\n # Exit flow\n x = self.block20(x)\n x = self.conv3(x)\n x = self.bn3(x)\n x = self.relu(x)\n\n x = self.conv4(x)\n x = self.bn4(x)\n x = self.relu(x)\n\n x = self.conv5(x)\n x = self.bn5(x)\n x = self.relu(x)\n\n return x, low_level_feat\n\n def _init_weight(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, math.sqrt(2. / n))\n elif isinstance(m, BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _load_xception_pretrained(self):\n pretrain_dict = model_zoo.load_url('http://data.lip6.fr/cadene/pretrainedmodels/xception-b5690688.pth')\n model_dict = {}\n state_dict = self.state_dict()\n\n for k, v in pretrain_dict.items():\n if k in model_dict:\n if 'pointwise' in k:\n v = v.unsqueeze(-1).unsqueeze(-1)\n if k.startswith('block11'):\n model_dict[k] = v\n model_dict[k.replace('block11', 'block12')] = v\n model_dict[k.replace('block11', 'block13')] = v\n model_dict[k.replace('block11', 'block14')] = v\n model_dict[k.replace('block11', 'block15')] = v\n model_dict[k.replace('block11', 'block16')] = v\n model_dict[k.replace('block11', 'block17')] = v\n model_dict[k.replace('block11', 'block18')] = v\n model_dict[k.replace('block11', 'block19')] = v\n elif k.startswith('block12'):\n model_dict[k.replace('block12', 'block20')] = v\n elif k.startswith('bn3'):\n model_dict[k] = v\n model_dict[k.replace('bn3', 'bn4')] = v\n elif k.startswith('conv4'):\n model_dict[k.replace('conv4', 'conv5')] = v\n elif k.startswith('bn4'):\n model_dict[k.replace('bn4', 'bn5')] = v\n else:\n model_dict[k] = v\n state_dict.update(model_dict)\n self.load_state_dict(state_dict)\n\nclass ASPP_module(nn.Module):\n def __init__(self, inplanes, planes, dilation):\n super(ASPP_module, self).__init__()\n if dilation == 1:\n kernel_size = 1\n padding = 0\n else:\n kernel_size = 3\n padding = dilation\n self.atrous_convolution = nn.Conv2d(inplanes, planes, kernel_size=kernel_size,\n stride=1, padding=padding, dilation=dilation, bias=False)\n self.bn = BatchNorm2d(planes)\n self.relu = nn.ReLU()\n\n self._init_weight()\n\n def forward(self, x):\n x = self.atrous_convolution(x)\n x = self.bn(x)\n\n return self.relu(x)\n\n def _init_weight(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, math.sqrt(2. / n))\n elif isinstance(m, BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n\nclass DeepLabv3_plus(nn.Module):\n def __init__(self, nInputChannels=3, n_classes=21, os=16, pretrained=False, freeze_bn=False, _print=True):\n if _print:\n print(\"Constructing DeepLabv3+ model...\")\n print(\"Backbone: Xception\")\n print(\"Number of classes: {}\".format(n_classes))\n print(\"Output stride: {}\".format(os))\n print(\"Number of Input Channels: {}\".format(nInputChannels))\n super(DeepLabv3_plus, self).__init__()\n\n # Atrous Conv\n self.xception_features = Xception(nInputChannels, os, pretrained)\n\n # ASPP\n if os == 16:\n dilations = [1, 6, 12, 18]\n elif os == 8:\n dilations = [1, 12, 24, 36]\n else:\n raise NotImplementedError\n\n self.aspp1 = ASPP_module(2048, 256, dilation=dilations[0])\n self.aspp2 = ASPP_module(2048, 256, dilation=dilations[1])\n self.aspp3 = ASPP_module(2048, 256, dilation=dilations[2])\n self.aspp4 = ASPP_module(2048, 256, dilation=dilations[3])\n\n self.relu = nn.ReLU()\n\n self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),\n nn.Conv2d(2048, 256, 1, stride=1, bias=False),\n BatchNorm2d(256),\n nn.ReLU())\n\n self.conv1 = nn.Conv2d(1280, 256, 1, bias=False)\n self.bn1 = BatchNorm2d(256)\n\n # adopt [1x1, 48] for channel reduction.\n self.conv2 = nn.Conv2d(128, 48, 1, bias=False)\n self.bn2 = BatchNorm2d(48)\n\n self.last_conv = nn.Sequential(nn.Conv2d(304, 256, kernel_size=3, stride=1, padding=1, bias=False),\n BatchNorm2d(256),\n nn.ReLU(),\n nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1, bias=False),\n BatchNorm2d(256),\n nn.ReLU(),\n nn.Conv2d(256, n_classes, kernel_size=1, stride=1))\n if freeze_bn:\n self._freeze_bn()\n\n def forward(self, input):\n x, low_level_features = self.xception_features(input)\n x1 = self.aspp1(x)\n x2 = self.aspp2(x)\n x3 = self.aspp3(x)\n x4 = self.aspp4(x)\n x5 = self.global_avg_pool(x)\n x5 = F.interpolate(x5, size=x4.size()[2:], mode='bilinear', align_corners=True)\n\n x = torch.cat((x1, x2, x3, x4, x5), dim=1)\n\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = F.interpolate(x, size=(int(math.ceil(input.size()[-2]/4)),\n int(math.ceil(input.size()[-1]/4))), mode='bilinear', align_corners=True)\n\n low_level_features = self.conv2(low_level_features)\n low_level_features = self.bn2(low_level_features)\n low_level_features = self.relu(low_level_features)\n\n\n x = torch.cat((x, low_level_features), dim=1)\n x = self.last_conv(x)\n x = F.interpolate(x, size=input.size()[2:], mode='bilinear', align_corners=True)\n\n return x\n\n def _freeze_bn(self):\n for m in self.modules():\n if isinstance(m, BatchNorm2d):\n m.eval()\n\n def _init_weight(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, math.sqrt(2. / n))\n elif isinstance(m, BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\ndef get_1x_lr_params(model):\n \"\"\"\n This generator returns all the parameters of the net except for\n the last classification layer. Note that for each batchnorm layer,\n requires_grad is set to False in deeplab_resnet.py, therefore this function does not return\n any batchnorm parameter\n \"\"\"\n b = [model.xception_features]\n for i in range(len(b)):\n for k in b[i].parameters():\n if k.requires_grad:\n yield k\n\n\ndef get_10x_lr_params(model):\n \"\"\"\n This generator returns all the parameters for the last layer of the net,\n which does the classification of pixel into classes\n \"\"\"\n b = [model.aspp1, model.aspp2, model.aspp3, model.aspp4, model.conv1, model.conv2, model.last_conv]\n for j in range(len(b)):\n for k in b[j].parameters():\n if k.requires_grad:\n yield k\n\n\nif __name__ == \"__main__\":\n model = DeepLabv3_plus(nInputChannels=3, n_classes=21, os=16, pretrained=True, _print=True)\n model.eval()\n image = torch.randn(1, 3, 512, 512)\n with torch.no_grad():\n output = model.forward(image)\n print(output.size())\n\n\n\n"
] |
[
[
"torch.nn.Sequential",
"torch.cat",
"torch.randn",
"torch.nn.Conv2d",
"torch.no_grad",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.ReLU",
"torch.utils.model_zoo.load_url",
"torch.nn.functional.pad"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ZuhongLi/tensorflow
|
[
"d8717a34799b3a70170caec38c39ed4fe893003d"
] |
[
"Linear regression/utils.py"
] |
[
"import os\nimport gzip\nimport shutil\nimport struct\nimport urllib\n\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport tensorflow as tf\n\ndef huber_loss(labels, predictions, delta=14.0):\n residual = tf.abs(labels - predictions)\n def f1(): return 0.5 * tf.square(residual)\n def f2(): return delta * residual - 0.5 * tf.square(delta)\n return tf.cond(residual < delta, f1, f2)\n\ndef safe_mkdir(path):\n \"\"\" Create a directory if there isn't one already. \"\"\"\n try:\n os.mkdir(path)\n except OSError:\n pass\n\ndef read_birth_life_data(filename):\n \"\"\"\n Read in birth_life_2010.txt and return:\n data in the form of NumPy array\n n_samples: number of samples\n \"\"\"\n text = open(filename, 'r').readlines()[1:]\n data = [line[:-1].split('\\t') for line in text]\n births = [float(line[1]) for line in data]\n lifes = [float(line[2]) for line in data]\n data = list(zip(births, lifes))\n n_samples = len(data)\n data = np.asarray(data, dtype=np.float32)\n return data, n_samples\n\ndef download_one_file(download_url, \n local_dest, \n expected_byte=None, \n unzip_and_remove=False):\n \"\"\" \n Download the file from download_url into local_dest\n if the file doesn't already exists.\n If expected_byte is provided, check if \n the downloaded file has the same number of bytes.\n If unzip_and_remove is True, unzip the file and remove the zip file\n \"\"\"\n if os.path.exists(local_dest) or os.path.exists(local_dest[:-3]):\n print('%s already exists' %local_dest)\n else:\n print('Downloading %s' %download_url)\n local_file, _ = urllib.request.urlretrieve(download_url, local_dest)\n file_stat = os.stat(local_dest)\n if expected_byte:\n if file_stat.st_size == expected_byte:\n print('Successfully downloaded %s' %local_dest)\n if unzip_and_remove:\n with gzip.open(local_dest, 'rb') as f_in, open(local_dest[:-3],'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n os.remove(local_dest)\n else:\n print('The downloaded file has unexpected number of bytes')\n\ndef download_mnist(path):\n \"\"\" \n Download and unzip the dataset mnist if it's not already downloaded \n Download from http://yann.lecun.com/exdb/mnist\n \"\"\"\n safe_mkdir(path)\n url = 'http://yann.lecun.com/exdb/mnist'\n filenames = ['train-images-idx3-ubyte.gz',\n 'train-labels-idx1-ubyte.gz',\n 't10k-images-idx3-ubyte.gz',\n 't10k-labels-idx1-ubyte.gz']\n expected_bytes = [9912422, 28881, 1648877, 4542]\n\n for filename, byte in zip(filenames, expected_bytes):\n download_url = os.path.join(url, filename)\n local_dest = os.path.join(path, filename)\n download_one_file(download_url, local_dest, byte, True)\n\ndef parse_data(path, dataset, flatten):\n if dataset != 'train' and dataset != 't10k':\n raise NameError('dataset must be train or t10k')\n\n label_file = os.path.join(path, dataset + '-labels-idx1-ubyte')\n with open(label_file, 'rb') as file:\n _, num = struct.unpack(\">II\", file.read(8))\n labels = np.fromfile(file, dtype=np.int8) #int8\n new_labels = np.zeros((num, 10))\n new_labels[np.arange(num), labels] = 1\n \n img_file = os.path.join(path, dataset + '-images-idx3-ubyte')\n with open(img_file, 'rb') as file:\n _, num, rows, cols = struct.unpack(\">IIII\", file.read(16))\n imgs = np.fromfile(file, dtype=np.uint8).reshape(num, rows, cols) #uint8\n imgs = imgs.astype(np.float32) / 255.0\n if flatten:\n imgs = imgs.reshape([num, -1])\n\n return imgs, new_labels\n\ndef read_mnist(path, flatten=True, num_train=55000):\n \"\"\"\n Read in the mnist dataset, given that the data is stored in path\n Return two tuples of numpy arrays\n ((train_imgs, train_labels), (test_imgs, test_labels))\n \"\"\"\n imgs, labels = parse_data(path, 'train', flatten)\n indices = np.random.permutation(labels.shape[0])\n train_idx, val_idx = indices[:num_train], indices[num_train:]\n train_img, train_labels = imgs[train_idx, :], labels[train_idx, :]\n val_img, val_labels = imgs[val_idx, :], labels[val_idx, :]\n test = parse_data(path, 't10k', flatten)\n return (train_img, train_labels), (val_img, val_labels), test\n\ndef get_mnist_dataset(batch_size):\n # Step 1: Read in data\n mnist_folder = 'data/mnist'\n download_mnist(mnist_folder)\n train, val, test = read_mnist(mnist_folder, flatten=False)\n\n # Step 2: Create datasets and iterator\n train_data = tf.data.Dataset.from_tensor_slices(train)\n train_data = train_data.shuffle(10000) # if you want to shuffle your data\n train_data = train_data.batch(batch_size)\n\n test_data = tf.data.Dataset.from_tensor_slices(test)\n test_data = test_data.batch(batch_size)\n\n return train_data, test_data\n \ndef show(image):\n \"\"\"\n Render a given numpy.uint8 2D array of pixel data.\n \"\"\"\n plt.imshow(image, cmap='gray')\n plt.show()\n"
] |
[
[
"tensorflow.cond",
"matplotlib.pyplot.imshow",
"numpy.fromfile",
"numpy.asarray",
"numpy.arange",
"tensorflow.data.Dataset.from_tensor_slices",
"numpy.random.permutation",
"tensorflow.square",
"matplotlib.pyplot.show",
"numpy.zeros",
"tensorflow.abs"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
yizx-1017/modin
|
[
"2eee697135b30a9694c202456db0635c52c9e6c9"
] |
[
"modin/experimental/core/execution/native/implementations/omnisci_on_native/exchange/dataframe_protocol/column.py"
] |
[
"# Licensed to Modin Development Team under one or more contributor license agreements.\n# See the NOTICE file distributed with this work for additional information regarding\n# copyright ownership. The Modin Development Team licenses this file to you under the\n# Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n# compliance 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, software distributed under\n# the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific language\n# governing permissions and limitations under the License.\n\n\"\"\"The module houses OmnisciOnNative implementation of the Column class of DataFrame exchange protocol.\"\"\"\n\nimport pyarrow as pa\nimport pandas\nimport numpy as np\nfrom typing import Any, Optional, Tuple, Dict, Iterable\nfrom math import ceil\n\nfrom modin.core.dataframe.base.exchange.dataframe_protocol.utils import (\n DTypeKind,\n ColumnNullType,\n ArrowCTypes,\n Endianness,\n pandas_dtype_to_arrow_c,\n raise_copy_alert,\n)\nfrom modin.core.dataframe.base.exchange.dataframe_protocol.dataframe import (\n ProtocolColumn,\n)\nfrom modin.utils import _inherit_docstrings\nfrom .buffer import OmnisciProtocolBuffer\nfrom .utils import arrow_dtype_to_arrow_c, arrow_types_map\n\n\n@_inherit_docstrings(ProtocolColumn)\nclass OmnisciProtocolColumn(ProtocolColumn):\n \"\"\"\n Wrapper of ``OmnisciProtocolDataframe`` holding a single column.\n\n The Column object wraps a ``ProtocolDataframe`` to ease referencing original\n Modin DataFrame with no materialization of PyArrow table where possible.\n ``ProtocolDataframe`` also already implements methods like chunking and ``allow_copy``\n checks, so we can just forward calls for the methods to ``ProtocolDataFrame`` without\n reimplementing them.\n\n Parameters\n ----------\n column : OmnisciProtocolDataframe\n DataFrame protocol object holding a PyArrow table with a single column.\n\n Notes\n -----\n The object could be modified inplace due to either casting PyArrow buffers to a new dtype\n or combining physical chunks into a single congingous buffer:\n ``_propagate_dtype``, ``_cast_at``, ``_combine_chunks`` - the methods replace the wrapped\n ``OmnisciProtocolDataframe`` object with the new one holding the modified PyArrow table.\n \"\"\"\n\n def __init__(self, column: \"OmnisciProtocolDataframe\") -> None:\n self._col = column\n\n @property\n def size(self) -> int:\n return self._col.num_rows()\n\n @property\n def offset(self) -> int:\n # The offset may change if it would require to cast buffers as the casted ones\n # no longer depend on their parent tables. So materializing buffers\n # before returning the offset\n self._materialize_actual_buffers()\n return self._pyarrow_table.column(0).chunks[0].offset\n\n @property\n def dtype(self) -> Tuple[DTypeKind, int, str, str]:\n dtype = self._pandas_dtype\n\n if pandas.api.types.is_bool_dtype(dtype):\n return (DTypeKind.BOOL, 1, ArrowCTypes.BOOL, Endianness.NATIVE)\n elif pandas.api.types.is_datetime64_dtype(\n dtype\n ) or pandas.api.types.is_categorical_dtype(dtype):\n # We can't fully describe an actual underlying type's metadata from pandas dtype,\n # use a `._arrow_dtype` for missing parts of information like datetime resulution,\n # dictionary metadata, etc?...\n return self._dtype_from_pyarrow(self._arrow_dtype)\n elif pandas.api.types.is_string_dtype(dtype):\n return (\n DTypeKind.STRING,\n 8,\n pandas_dtype_to_arrow_c(dtype),\n Endianness.NATIVE,\n )\n else:\n return self._dtype_from_primitive_numpy(dtype)\n\n def _dtype_from_pyarrow(self, dtype):\n \"\"\"\n Build protocol dtype from PyArrow type.\n\n Parameters\n ----------\n dtype : pyarrow.DataType\n Data type to convert from.\n\n Returns\n -------\n tuple(DTypeKind, bitwidth: int, format_str: str, edianess: str)\n \"\"\"\n kind = None\n if (\n pa.types.is_timestamp(dtype)\n or pa.types.is_date(dtype)\n or pa.types.is_time(dtype)\n ):\n kind = DTypeKind.DATETIME\n bit_width = dtype.bit_width\n elif pa.types.is_dictionary(dtype):\n kind = DTypeKind.CATEGORICAL\n bit_width = dtype.bit_width\n elif pa.types.is_string(dtype):\n kind = DTypeKind.STRING\n bit_width = 8\n elif pa.types.is_boolean(dtype):\n kind = DTypeKind.BOOL\n bit_width = dtype.bit_width\n\n if kind is not None:\n return (kind, bit_width, arrow_dtype_to_arrow_c(dtype), Endianness.NATIVE)\n else:\n return self._dtype_from_primitive_numpy(np.dtype(dtype.to_pandas_dtype()))\n\n def _dtype_from_primitive_numpy(\n self, dtype: np.dtype\n ) -> Tuple[DTypeKind, int, str, str]:\n \"\"\"\n Build protocol dtype from primitive pandas dtype.\n\n Parameters\n ----------\n dtype : np.dtype\n Data type to convert from.\n\n Returns\n -------\n tuple(DTypeKind, bitwidth: int, format_str: str, edianess: str)\n \"\"\"\n np_kinds = {\n \"i\": DTypeKind.INT,\n \"u\": DTypeKind.UINT,\n \"f\": DTypeKind.FLOAT,\n \"b\": DTypeKind.BOOL,\n }\n kind = np_kinds.get(dtype.kind, None)\n if kind is None:\n raise NotImplementedError(\n f\"Data type {dtype} not supported by exchange protocol\"\n )\n return (\n kind,\n dtype.itemsize * 8,\n pandas_dtype_to_arrow_c(dtype),\n dtype.byteorder,\n )\n\n @property\n def describe_categorical(self) -> Dict[str, Any]:\n dtype = self._pandas_dtype\n\n if dtype != \"category\":\n raise RuntimeError(\n \"`describe_categorical only works on a column with \"\n + \"categorical dtype!\"\n )\n\n ordered = dtype.ordered\n\n # Category codes may change during materialization flow, so trigger\n # materialization before returning the codes\n self._materialize_actual_buffers()\n\n # Although we can retrieve codes from pandas dtype, they're unsynced with\n # the actual PyArrow data most of the time. So getting the mapping directly\n # from the materialized PyArrow table.\n col = self._pyarrow_table.column(0)\n if len(col.chunks) > 1:\n if not self._col._allow_copy:\n raise_copy_alert(\n copy_reason=\"physical chunks combining due to contiguous buffer materialization\"\n )\n col = col.combine_chunks()\n\n col = col.chunks[0]\n mapping = dict(enumerate(col.dictionary.tolist()))\n\n return {\n \"is_ordered\": ordered,\n \"is_dictionary\": True,\n \"mapping\": mapping,\n }\n\n @property\n def describe_null(self) -> Tuple[ColumnNullType, Any]:\n null_buffer = self._pyarrow_table.column(0).chunks[0].buffers()[0]\n if null_buffer is None:\n return (ColumnNullType.NON_NULLABLE, None)\n else:\n return (ColumnNullType.USE_BITMASK, 0)\n\n @property\n def null_count(self) -> int:\n return self._pyarrow_table.column(0).null_count\n\n @property\n def metadata(self) -> Dict[str, Any]:\n return self._col.metadata\n\n @property\n def _pandas_dtype(self) -> np.dtype:\n \"\"\"\n Get column's dtype representation in Modin DataFrame.\n\n Returns\n -------\n numpy.dtype\n \"\"\"\n return self._col._df.dtypes.iloc[0]\n\n @property\n def _arrow_dtype(self) -> pa.DataType:\n \"\"\"\n Get column's dtype representation in underlying PyArrow table.\n\n Returns\n -------\n pyarrow.DataType\n \"\"\"\n return self._pyarrow_table.column(0).type\n\n @property\n def _pyarrow_table(self) -> pa.Table:\n \"\"\"\n Get PyArrow table representing the column.\n\n Returns\n -------\n pyarrow.Table\n \"\"\"\n return self._col._pyarrow_table\n\n def num_chunks(self) -> int:\n return self._col.num_chunks()\n\n def get_chunks(self, n_chunks: Optional[int] = None) -> Iterable[\"Column\"]:\n for chunk in self._col.get_chunks(n_chunks):\n yield OmnisciProtocolColumn(chunk)\n\n def get_buffers(self) -> Dict[str, Any]:\n self._materialize_actual_buffers()\n at = self._pyarrow_table\n pyarrow_array = at.column(0).chunks[0]\n\n result = dict()\n result[\"data\"] = self._get_data_buffer(pyarrow_array)\n result[\"validity\"] = self._get_validity_buffer(pyarrow_array)\n result[\"offsets\"] = self._get_offsets_buffer(pyarrow_array)\n\n return result\n\n def _materialize_actual_buffers(self):\n \"\"\"\n Materialize PyArrow table's buffers that can be zero-copy returned to a consumer, if they aren't already materialized.\n\n Besides materializing PyArrow table itself (if there were some delayed computations)\n the function also may do the following if required:\n 1. Propagate external dtypes to the PyArrow table. For example,\n if ``self.dtype`` is a string kind, but internal PyArrow dtype is a dictionary\n (if the table were just exported from OmniSci), then the dictionary will be casted\n to string dtype.\n 2. Combine physical chunks of PyArrow table into a single contiguous buffer.\n \"\"\"\n if self.num_chunks() != 1:\n if not self._col._allow_copy:\n raise_copy_alert(\n copy_reason=\"physical chunks combining due to contiguous buffer materialization\"\n )\n self._combine_chunks()\n\n external_dtype = self.dtype\n internal_dtype = self._dtype_from_pyarrow(self._arrow_dtype)\n\n if external_dtype[0] != internal_dtype[0]:\n self._propagate_dtype(external_dtype)\n\n def _get_buffer_size(self, bit_width: int, is_offset_buffer: bool = False) -> int:\n \"\"\"\n Compute buffer's size in bytes for the current chunk.\n\n Parameters\n ----------\n bit_width : int\n Bit width of the underlying data type.\n is_offset_buffer : bool, default: False\n Whether the buffer describes offsets.\n\n Returns\n -------\n int\n Number of bytes to read from the start of the buffer + offset to retrieve the whole chunk.\n \"\"\"\n # Offset buffer always has ``size + 1`` elements in it as it describes slices bounds\n elements_in_buffer = self.size + 1 if is_offset_buffer else self.size\n result = ceil((bit_width * elements_in_buffer) / 8)\n # For a bitmask, if the chunk started in the middle of the byte then we need to\n # read one extra byte from the buffer to retrieve the chunk's tail in the last byte. Example:\n # Bitmask of 3 bytes, the chunk offset is 3 elements and its size is 16\n # |* * * * * * * *|* * * * * * * *|* * * * * * * *|\n # ^- the chunk starts here ^- the chunk ends here\n # Although ``ceil(bit_width * elements_in_buffer / 8)`` gives us '2 bytes',\n # the chunk is located in 3 bytes, that's why we assume the chunk's buffer size\n # to be 'result += 1' in this case:\n if bit_width == 1 and self.offset % 8 + self.size > result * 8:\n result += 1\n return result\n\n def _get_data_buffer(\n self, arr: pa.Array\n ) -> Tuple[OmnisciProtocolBuffer, Tuple[DTypeKind, int, str, str]]:\n \"\"\"\n Get column's data buffer.\n\n Parameters\n ----------\n arr : pa.Array\n PyArrow array holding column's data.\n\n Returns\n -------\n tuple\n Tuple of ``OmnisciProtocolBuffer`` and protocol dtype representation of the buffer's underlying data.\n \"\"\"\n if self.dtype[0] == DTypeKind.CATEGORICAL:\n # For dictionary data the buffer has to return categories codes\n arr = arr.indices\n\n arrow_type = self._dtype_from_pyarrow(arr.type)\n buff_size = (\n self._get_buffer_size(bit_width=arrow_type[1])\n if self.dtype[0] != DTypeKind.STRING\n # We don't chunk string buffers as it would require modifying offset values,\n # so just return the whole data buffer for every chunk.\n else None\n )\n\n return (\n # According to the Arrow's memory layout, the data buffer is always present\n # at the last position of `.buffers()`:\n # https://arrow.apache.org/docs/format/Columnar.html#buffer-listing-for-each-layout\n OmnisciProtocolBuffer(arr.buffers()[-1], buff_size),\n arrow_type,\n )\n\n def _get_validity_buffer(\n self, arr: pa.Array\n ) -> Optional[Tuple[OmnisciProtocolBuffer, Tuple[DTypeKind, int, str, str]]]:\n \"\"\"\n Get column's validity buffer.\n\n Parameters\n ----------\n arr : pa.Array\n PyArrow array holding column's data.\n\n Returns\n -------\n tuple or None\n Tuple of ``OmnisciProtocolBuffer`` and protocol dtype representation of the buffer's underlying data.\n None if column is non-nullable (``self.describe_null == ColumnNullType.NON_NULLABLE``).\n \"\"\"\n # According to the Arrow's memory layout, the validity buffer is always present at zero position:\n # https://arrow.apache.org/docs/format/Columnar.html#buffer-listing-for-each-layout\n validity_buffer = arr.buffers()[0]\n if validity_buffer is None:\n return None\n\n # If exist, validity buffer is always a bit-mask.\n data_size = self._get_buffer_size(bit_width=1)\n return (\n OmnisciProtocolBuffer(validity_buffer, data_size),\n (DTypeKind.BOOL, 1, ArrowCTypes.BOOL, Endianness.NATIVE),\n )\n\n def _get_offsets_buffer(\n self, arr: pa.Array\n ) -> Optional[Tuple[OmnisciProtocolBuffer, Tuple[DTypeKind, int, str, str]]]:\n \"\"\"\n Get column's offsets buffer.\n\n Parameters\n ----------\n arr : pa.Array\n PyArrow array holding column's data.\n\n Returns\n -------\n tuple or None\n Tuple of ``OmnisciProtocolBuffer`` and protocol dtype representation of the buffer's underlying data.\n None if the column's dtype is fixed-size.\n \"\"\"\n buffs = arr.buffers()\n # According to the Arrow's memory layout, the offsets buffer is always at the second position\n # of `.buffers()` if present. Considering the support of only Primitive, Variable-length binary,\n # and Dict-encoded types from the layout table, we can assume that there's no offsets buffer\n # if there are fewer than 3 buffers available.\n # https://arrow.apache.org/docs/format/Columnar.html#buffer-listing-for-each-layout\n if len(buffs) < 3:\n return None\n\n offset_buff = buffs[1]\n # According to Arrow's data layout, the offset buffer type is \"int32\"\n dtype = self._dtype_from_primitive_numpy(np.dtype(\"int32\"))\n return (\n OmnisciProtocolBuffer(\n offset_buff,\n self._get_buffer_size(bit_width=dtype[1], is_offset_buffer=True),\n ),\n dtype,\n )\n\n def _propagate_dtype(self, dtype: Tuple[DTypeKind, int, str, str]):\n \"\"\"\n Propagate `dtype` to the underlying PyArrow table.\n\n Modifies the column object inplace by replacing underlying PyArrow table with\n the casted one.\n\n Parameters\n ----------\n dtype : tuple\n Data type conforming protocol dtypes format to cast underlying PyArrow table.\n \"\"\"\n if not self._col._allow_copy:\n raise_copy_alert(\n copy_reason=\"casting to align pandas and PyArrow data types\"\n )\n\n kind, bit_width, format_str, _ = dtype\n arrow_type = None\n\n if kind in arrow_types_map:\n arrow_type = arrow_types_map[kind].get(bit_width, None)\n elif kind == DTypeKind.DATETIME:\n arrow_type = pa.timestamp(\"ns\")\n elif kind == DTypeKind.CATEGORICAL:\n index_type = arrow_types_map[DTypeKind.INT].get(bit_width, None)\n if index_type is not None:\n arrow_type = pa.dictionary(\n index_type=index_type,\n # There is no way to deduce an actual value type, so casting to a string\n # as it's the most common one\n value_type=pa.string(),\n )\n\n if arrow_type is None:\n raise NotImplementedError(f\"Propagation for type {dtype} is not supported.\")\n\n at = self._pyarrow_table\n schema_to_cast = at.schema\n field = at.schema[0]\n\n schema_to_cast = schema_to_cast.set(\n 0, pa.field(field.name, arrow_type, field.nullable)\n )\n\n # TODO: currently, each column chunk casts its buffers independently which results\n # in an `N_CHUNKS - 1` amount of redundant casts. We can make the PyArrow table\n # being shared across all the chunks, so the cast being triggered in a single chunk\n # propagate to all of them.\n self._cast_at(schema_to_cast)\n\n def _cast_at(self, new_schema: pa.Schema):\n \"\"\"\n Cast underlying PyArrow table with the passed schema.\n\n Parameters\n ----------\n new_schema : pyarrow.Schema\n New schema to cast the table.\n\n Notes\n -----\n This method modifies the column inplace by replacing the wrapped ``OmnisciProtocolDataframe``\n with the new one holding the casted PyArrow table.\n \"\"\"\n casted_at = self._pyarrow_table.cast(new_schema)\n self._col = type(self._col)(\n self._col._df.from_arrow(casted_at),\n self._col._nan_as_null,\n self._col._allow_copy,\n )\n\n def _combine_chunks(self):\n \"\"\"\n Combine physical chunks of underlying PyArrow table.\n\n Notes\n -----\n This method modifies the column inplace by replacing the wrapped ``OmnisciProtocolDataframe``\n with the new one holding PyArrow table with the column's data placed in a single contingous buffer.\n \"\"\"\n contiguous_at = self._pyarrow_table.combine_chunks()\n self._col = type(self._col)(\n self._col._df.from_arrow(contiguous_at),\n self._col._nan_as_null,\n self._col._allow_copy,\n )\n"
] |
[
[
"pandas.api.types.is_categorical_dtype",
"pandas.api.types.is_datetime64_dtype",
"numpy.dtype",
"pandas.api.types.is_string_dtype",
"pandas.api.types.is_bool_dtype"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
michiboo/HARK
|
[
"de2aab467de19da2ce76de1b58fb420f421bc85b"
] |
[
"HARK/utilities.py"
] |
[
"'''\nGeneral purpose / miscellaneous functions. Includes functions to approximate\ncontinuous distributions with discrete ones, utility functions (and their\nderivatives), manipulation of discrete distributions, and basic plotting tools.\n'''\n\nfrom __future__ import division # Import Python 3.x division function\nfrom __future__ import print_function\nfrom builtins import str\nfrom builtins import range\nfrom builtins import object\nimport functools\nimport warnings\nimport numpy as np # Python's numeric library, abbreviated \"np\"\nimport math\n# try:\n# import matplotlib.pyplot as plt # Python's plotting library\n# except ImportError:\n# import sys\n# exception_type, value, traceback = sys.exc_info()\n# raise ImportError('HARK must be used in a graphical environment.', exception_type, value, traceback)\nimport scipy.stats as stats # Python's statistics library\nfrom scipy.interpolate import interp1d\nfrom scipy.special import erf, erfc\n\ndef memoize(obj):\n '''\n A decorator to (potentially) make functions more efficient.\n\n With this decorator, functions will \"remember\" if they have been evaluated with given inputs\n before. If they have, they will \"remember\" the outputs that have already been calculated\n for those inputs, rather than calculating them again.\n '''\n cache = obj._cache = {}\n\n @functools.wraps(obj)\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in cache:\n cache[key] = obj(*args, **kwargs)\n return cache[key]\n return memoizer\n\n\n# ==============================================================================\n# ============== Some basic function tools ====================================\n# ==============================================================================\ndef getArgNames(function):\n '''\n Returns a list of strings naming all of the arguments for the passed function.\n\n Parameters\n ----------\n function : function\n A function whose argument names are wanted.\n\n Returns\n -------\n argNames : [string]\n The names of the arguments of function.\n '''\n argCount = function.__code__.co_argcount\n argNames = function.__code__.co_varnames[:argCount]\n return argNames\n\n\nclass NullFunc(object):\n '''\n A trivial class that acts as a placeholder \"do nothing\" function.\n '''\n def __call__(self,*args):\n '''\n Returns meaningless output no matter what the input(s) is. If no input,\n returns None. Otherwise, returns an array of NaNs (or a single NaN) of\n the same size as the first input.\n '''\n if len(args) == 0:\n return None\n else:\n arg = args[0]\n if hasattr(arg,'shape'):\n return np.zeros_like(arg) + np.nan\n else:\n return np.nan\n\n def distance(self,other):\n '''\n Trivial distance metric that only cares whether the other object is also\n an instance of NullFunc. Intentionally does not inherit from HARKobject\n as this might create dependency problems.\n\n Parameters\n ----------\n other : any\n Any object for comparison to this instance of NullFunc.\n\n Returns\n -------\n (unnamed) : float\n The distance between self and other. Returns 0 if other is also a\n NullFunc; otherwise returns an arbitrary high number.\n '''\n try:\n if other.__class__ is self.__class__:\n return 0.0\n else:\n return 1000.0\n except:\n return 10000.0\n\n# ==============================================================================\n# ============== Define utility functions ===============================\n# ==============================================================================\ndef CRRAutility(c, gam):\n '''\n Evaluates constant relative risk aversion (CRRA) utility of consumption c\n given risk aversion parameter gam.\n\n Parameters\n ----------\n c : float\n Consumption value\n gam : float\n Risk aversion\n\n Returns\n -------\n (unnamed) : float\n Utility\n\n Tests\n -----\n Test a value which should pass:\n >>> c, gamma = 1.0, 2.0 # Set two values at once with Python syntax\n >>> utility(c=c, gam=gamma)\n -1.0\n '''\n if gam == 1:\n return np.log(c)\n else:\n return( c**(1.0 - gam) / (1.0 - gam) )\n\ndef CRRAutilityP(c, gam):\n '''\n Evaluates constant relative risk aversion (CRRA) marginal utility of consumption\n c given risk aversion parameter gam.\n\n Parameters\n ----------\n c : float\n Consumption value\n gam : float\n Risk aversion\n\n Returns\n -------\n (unnamed) : float\n Marginal utility\n '''\n return( c**-gam )\n\ndef CRRAutilityPP(c, gam):\n '''\n Evaluates constant relative risk aversion (CRRA) marginal marginal utility of\n consumption c given risk aversion parameter gam.\n\n Parameters\n ----------\n c : float\n Consumption value\n gam : float\n Risk aversion\n\n Returns\n -------\n (unnamed) : float\n Marginal marginal utility\n '''\n return( -gam*c**(-gam-1.0) )\n\ndef CRRAutilityPPP(c, gam):\n '''\n Evaluates constant relative risk aversion (CRRA) marginal marginal marginal\n utility of consumption c given risk aversion parameter gam.\n\n Parameters\n ----------\n c : float\n Consumption value\n gam : float\n Risk aversion\n\n Returns\n -------\n (unnamed) : float\n Marginal marginal marginal utility\n '''\n return( (gam+1.0)*gam*c**(-gam-2.0) )\n\ndef CRRAutilityPPPP(c, gam):\n '''\n Evaluates constant relative risk aversion (CRRA) marginal marginal marginal\n marginal utility of consumption c given risk aversion parameter gam.\n\n Parameters\n ----------\n c : float\n Consumption value\n gam : float\n Risk aversion\n\n Returns\n -------\n (unnamed) : float\n Marginal marginal marginal marginal utility\n '''\n return( -(gam+2.0)*(gam+1.0)*gam*c**(-gam-3.0) )\n\ndef CRRAutility_inv(u, gam):\n '''\n Evaluates the inverse of the CRRA utility function (with risk aversion para-\n meter gam) at a given utility level u.\n\n Parameters\n ----------\n u : float\n Utility value\n gam : float\n Risk aversion\n\n Returns\n -------\n (unnamed) : float\n Consumption corresponding to given utility value\n '''\n if gam == 1:\n return np.exp(u)\n else:\n return( ((1.0-gam)*u)**(1/(1.0-gam)) )\n\ndef CRRAutilityP_inv(uP, gam):\n '''\n Evaluates the inverse of the CRRA marginal utility function (with risk aversion\n parameter gam) at a given marginal utility level uP.\n\n Parameters\n ----------\n uP : float\n Marginal utility value\n gam : float\n Risk aversion\n\n Returns\n -------\n (unnamed) : float\n Consumption corresponding to given marginal utility value.\n '''\n return( uP**(-1.0/gam) )\n\ndef CRRAutility_invP(u, gam):\n '''\n Evaluates the derivative of the inverse of the CRRA utility function (with\n risk aversion parameter gam) at a given utility level u.\n\n Parameters\n ----------\n u : float\n Utility value\n gam : float\n Risk aversion\n\n Returns\n -------\n (unnamed) : float\n Marginal consumption corresponding to given utility value\n '''\n if gam == 1:\n return np.exp(u)\n else:\n return( ((1.0-gam)*u)**(gam/(1.0-gam)) )\n\ndef CRRAutilityP_invP(uP, gam):\n '''\n Evaluates the derivative of the inverse of the CRRA marginal utility function\n (with risk aversion parameter gam) at a given marginal utility level uP.\n\n Parameters\n ----------\n uP : float\n Marginal utility value\n gam : float\n Risk aversion\n\n Returns\n -------\n (unnamed) : float\n Marginal consumption corresponding to given marginal utility value\n '''\n return( (-1.0/gam)*uP**(-1.0/gam-1.0) )\n\n\ndef CARAutility(c, alpha):\n '''\n Evaluates constant absolute risk aversion (CARA) utility of consumption c\n given risk aversion parameter alpha.\n\n Parameters\n ----------\n c: float\n Consumption value\n alpha: float\n Risk aversion\n\n Returns\n -------\n (unnamed): float\n Utility\n '''\n return( 1 - np.exp(-alpha*c)/alpha )\n\ndef CARAutilityP(c, alpha):\n '''\n Evaluates constant absolute risk aversion (CARA) marginal utility of\n consumption c given risk aversion parameter alpha.\n\n Parameters\n ----------\n c: float\n Consumption value\n alpha: float\n Risk aversion\n\n Returns\n -------\n (unnamed): float\n Marginal utility\n '''\n return( np.exp(-alpha*c) )\n\ndef CARAutilityPP(c, alpha):\n '''\n Evaluates constant absolute risk aversion (CARA) marginal marginal utility\n of consumption c given risk aversion parameter alpha.\n\n Parameters\n ----------\n c: float\n Consumption value\n alpha: float\n Risk aversion\n\n Returns\n -------\n (unnamed): float\n Marginal marginal utility\n '''\n return( -alpha*np.exp(-alpha*c) )\n\ndef CARAutilityPPP(c, alpha):\n '''\n Evaluates constant absolute risk aversion (CARA) marginal marginal marginal\n utility of consumption c given risk aversion parameter alpha.\n\n Parameters\n ----------\n c: float\n Consumption value\n alpha: float\n Risk aversion\n\n Returns\n -------\n (unnamed): float\n Marginal marginal marginal utility\n '''\n return( alpha**2.0*np.exp(-alpha*c) )\n\ndef CARAutility_inv(u, alpha):\n '''\n Evaluates inverse of constant absolute risk aversion (CARA) utility function\n at utility level u given risk aversion parameter alpha.\n\n Parameters\n ----------\n u: float\n Utility value\n alpha: float\n Risk aversion\n\n Returns\n -------\n (unnamed): float\n Consumption value corresponding to u\n '''\n return( -1.0/alpha * np.log(alpha*(1-u)) )\n\ndef CARAutilityP_inv(u, alpha):\n '''\n Evaluates the inverse of constant absolute risk aversion (CARA) marginal\n utility function at marginal utility uP given risk aversion parameter alpha.\n\n Parameters\n ----------\n u: float\n Utility value\n alpha: float\n Risk aversion\n\n Returns\n -------\n (unnamed): float\n Consumption value corresponding to uP\n '''\n return( -1.0/alpha*np.log(u) )\n\ndef CARAutility_invP(u, alpha):\n '''\n Evaluates the derivative of inverse of constant absolute risk aversion (CARA)\n utility function at utility level u given risk aversion parameter alpha.\n\n Parameters\n ----------\n u: float\n Utility value\n alpha: float\n Risk aversion\n\n Returns\n -------\n (unnamed): float\n Marginal onsumption value corresponding to u\n '''\n return( 1.0/(alpha*(1.0-u)) )\n\n\ndef approxLognormal(N, mu=0.0, sigma=1.0, tail_N=0, tail_bound=[0.02,0.98], tail_order=np.e):\n '''\n Construct a discrete approximation to a lognormal distribution with underlying\n normal distribution N(mu,sigma). Makes an equiprobable distribution by\n default, but user can optionally request augmented tails with exponentially\n sized point masses. This can improve solution accuracy in some models.\n\n Parameters\n ----------\n N: int\n Number of discrete points in the \"main part\" of the approximation.\n mu: float\n Mean of underlying normal distribution.\n sigma: float\n Standard deviation of underlying normal distribution.\n tail_N: int\n Number of points in each \"tail part\" of the approximation; 0 = no tail.\n tail_bound: [float]\n CDF boundaries of the tails vs main portion; tail_bound[0] is the lower\n tail bound, tail_bound[1] is the upper tail bound. Inoperative when\n tail_N = 0. Can make \"one tailed\" approximations with 0.0 or 1.0.\n tail_order: float\n Factor by which consecutive point masses in a \"tail part\" differ in\n probability. Should be >= 1 for sensible spacing.\n\n Returns\n -------\n pmf: np.ndarray\n Probabilities for discrete probability mass function.\n X: np.ndarray\n Discrete values in probability mass function.\n\n Written by Luca Gerotto\n Based on Matab function \"setup_workspace.m,\" from Chris Carroll's\n [Solution Methods for Microeconomic Dynamic Optimization Problems]\n (http://www.econ2.jhu.edu/people/ccarroll/solvingmicrodsops/) toolkit.\n Latest update: 11 February 2017 by Matthew N. White\n '''\n # Find the CDF boundaries of each segment\n if sigma > 0.0:\n if tail_N > 0:\n lo_cut = tail_bound[0]\n hi_cut = tail_bound[1]\n else:\n lo_cut = 0.0\n hi_cut = 1.0\n inner_size = hi_cut - lo_cut\n inner_CDF_vals = [lo_cut + x*N**(-1.0)*inner_size for x in range(1, N)]\n if inner_size < 1.0:\n scale = 1.0/tail_order\n mag = (1.0-scale**tail_N)/(1.0-scale)\n lower_CDF_vals = [0.0]\n if lo_cut > 0.0:\n for x in range(tail_N-1,-1,-1):\n lower_CDF_vals.append(lower_CDF_vals[-1] + lo_cut*scale**x/mag)\n upper_CDF_vals = [hi_cut]\n if hi_cut < 1.0:\n for x in range(tail_N):\n upper_CDF_vals.append(upper_CDF_vals[-1] + (1.0-hi_cut)*scale**x/mag)\n CDF_vals = lower_CDF_vals + inner_CDF_vals + upper_CDF_vals\n temp_cutoffs = list(stats.lognorm.ppf(CDF_vals[1:-1], s=sigma, loc=0, scale=np.exp(mu)))\n cutoffs = [0] + temp_cutoffs + [np.inf]\n CDF_vals = np.array(CDF_vals)\n\n # Construct the discrete approximation by finding the average value within each segment.\n # This codeblock ignores warnings because it throws a \"divide by zero encountered in log\"\n # warning due to computing erf(infty) at the tail boundary. This is irrelevant and\n # apparently freaks new users out.\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n K = CDF_vals.size-1 # number of points in approximation\n pmf = CDF_vals[1:(K+1)] - CDF_vals[0:K]\n X = np.zeros(K)\n for i in range(K):\n zBot = cutoffs[i]\n zTop = cutoffs[i+1]\n tempBot = (mu+sigma**2-np.log(zBot))/(np.sqrt(2)*sigma)\n tempTop = (mu+sigma**2-np.log(zTop))/(np.sqrt(2)*sigma)\n if tempBot <= 4:\n X[i] = -0.5*np.exp(mu+(sigma**2)*0.5)*(erf(tempTop) - erf(tempBot))/pmf[i]\n else:\n X[i] = -0.5*np.exp(mu+(sigma**2)*0.5)*(erfc(tempBot) - erfc(tempTop))/pmf[i]\n\n else:\n pmf = np.ones(N)/N\n X = np.exp(mu)*np.ones(N)\n return [pmf, X]\n\n@memoize\ndef approxMeanOneLognormal(N, sigma=1.0, **kwargs):\n '''\n Calculate a discrete approximation to a mean one lognormal distribution.\n Based on function approxLognormal; see that function's documentation for\n further notes.\n\n Parameters\n ----------\n N : int\n Size of discrete space vector to be returned.\n sigma : float\n standard deviation associated with underlying normal probability distribution.\n\n Returns\n -------\n X : np.array\n Discrete points for discrete probability mass function.\n pmf : np.array\n Probability associated with each point in X.\n\n Written by Nathan M. Palmer\n Based on Matab function \"setup_shocks.m,\" from Chris Carroll's\n [Solution Methods for Microeconomic Dynamic Optimization Problems]\n (http://www.econ2.jhu.edu/people/ccarroll/solvingmicrodsops/) toolkit.\n Latest update: 01 May 2015\n '''\n mu_adj = - 0.5*sigma**2;\n pmf,X = approxLognormal(N=N, mu=mu_adj, sigma=sigma, **kwargs)\n return [pmf,X]\n\ndef approxNormal(N, mu=0.0, sigma=1.0):\n x, w = np.polynomial.hermite.hermgauss(N)\n # normalize w\n pmf = w*np.pi**-0.5\n # correct x\n X = math.sqrt(2.0)*sigma*x + mu\n return [pmf, X]\n\ndef approxLognormalGaussHermite(N, mu=0.0, sigma=1.0):\n pmf, X = approxNormal(N, mu, sigma)\n return pmf, np.exp(X)\n\ndef calcNormalStyleParsFromLognormalPars(avgLognormal, stdLognormal):\n varLognormal = stdLognormal**2\n avgNormal = math.log(avgLognormal/math.sqrt(1+varLognormal/avgLognormal**2))\n varNormal = math.sqrt(math.log(1+varLognormal/avgLognormal**2))\n stdNormal = math.sqrt(varNormal)\n return avgNormal, stdNormal\n\ndef calcLognormalStyleParsFromNormalPars(muNormal, stdNormal):\n varNormal = stdNormal**2\n avgLognormal = math.exp(muNormal+varNormal*0.5)\n varLognormal = (math.exp(varNormal)-1)*math.exp(2*muNormal+varNormal)\n stdLognormal = math.sqrt(varLognormal)\n return avgLognormal, stdLognormal\n\ndef approxBeta(N,a=1.0,b=1.0):\n '''\n Calculate a discrete approximation to the beta distribution. May be quite\n slow, as it uses a rudimentary numeric integration method to generate the\n discrete approximation.\n\n Parameters\n ----------\n N : int\n Size of discrete space vector to be returned.\n a : float\n First shape parameter (sometimes called alpha).\n b : float\n Second shape parameter (sometimes called beta).\n\n Returns\n -------\n X : np.array\n Discrete points for discrete probability mass function.\n pmf : np.array\n Probability associated with each point in X.\n '''\n P = 1000\n vals = np.reshape(stats.beta.ppf(np.linspace(0.0,1.0,N*P),a,b),(N,P))\n X = np.mean(vals,axis=1)\n pmf = np.ones(N)/float(N)\n return( [pmf, X] )\n\ndef approxUniform(N,bot=0.0,top=1.0):\n '''\n Makes a discrete approximation to a uniform distribution, given its bottom\n and top limits and number of points.\n\n Parameters\n ----------\n N : int\n The number of points in the discrete approximation\n bot : float\n The bottom of the uniform distribution\n top : float\n The top of the uniform distribution\n\n Returns\n -------\n (unnamed) : np.array\n An equiprobable discrete approximation to the uniform distribution.\n '''\n pmf = np.ones(N)/float(N)\n center = (top+bot)/2.0\n width = (top-bot)/2.0\n X = center + width*np.linspace(-(N-1.0)/2.0,(N-1.0)/2.0,N)/(N/2.0)\n return [pmf,X]\n\n\ndef makeMarkovApproxToNormal(x_grid,mu,sigma,K=351,bound=3.5):\n '''\n Creates an approximation to a normal distribution with mean mu and standard\n deviation sigma, returning a stochastic vector called p_vec, corresponding\n to values in x_grid. If a RV is distributed x~N(mu,sigma), then the expectation\n of a continuous function f() is E[f(x)] = numpy.dot(p_vec,f(x_grid)).\n\n Parameters\n ----------\n x_grid: numpy.array\n A sorted 1D array of floats representing discrete values that a normally\n distributed RV could take on.\n mu: float\n Mean of the normal distribution to be approximated.\n sigma: float\n Standard deviation of the normal distribution to be approximated.\n K: int\n Number of points in the normal distribution to sample.\n bound: float\n Truncation bound of the normal distribution, as +/- bound*sigma.\n\n Returns\n -------\n p_vec: numpy.array\n A stochastic vector with probability weights for each x in x_grid.\n '''\n x_n = x_grid.size # Number of points in the outcome grid\n lower_bound = -bound # Lower bound of normal draws to consider, in SD\n upper_bound = bound # Upper bound of normal draws to consider, in SD\n raw_sample = np.linspace(lower_bound,upper_bound,K) # Evenly spaced draws between bounds\n f_weights = stats.norm.pdf(raw_sample) # Relative probability of each draw\n sample = mu + sigma*raw_sample # Adjusted bounds, given mean and stdev\n w_vec = np.zeros(x_n) # A vector of outcome weights\n\n # Find the relative position of each of the draws\n sample_pos = np.searchsorted(x_grid,sample)\n sample_pos[sample_pos < 1] = 1\n sample_pos[sample_pos > x_n-1] = x_n-1\n\n # Make arrays of the x_grid point directly above and below each draw\n bot = x_grid[sample_pos-1]\n top = x_grid[sample_pos]\n alpha = (sample-bot)/(top-bot)\n\n # Keep the weights (alpha) in bounds\n alpha_clipped = np.clip(alpha,0.,1.)\n\n # Loop through each x_grid point and add up the probability that each nearby\n # draw contributes to it (accounting for distance)\n for j in range(1,x_n):\n c = sample_pos == j\n w_vec[j-1] = w_vec[j-1] + np.dot(f_weights[c],1.0-alpha_clipped[c])\n w_vec[j] = w_vec[j] + np.dot(f_weights[c],alpha_clipped[c])\n\n # Reweight the probabilities so they sum to 1\n W = np.sum(w_vec)\n p_vec = w_vec/W\n\n # Check for obvious errors, and return p_vec\n assert (np.all(p_vec>=0.)) and (np.all(p_vec<=1.)) and (np.isclose(np.sum(p_vec),1.))\n return p_vec\n\ndef makeMarkovApproxToNormalByMonteCarlo(x_grid,mu,sigma,N_draws = 10000):\n '''\n Creates an approximation to a normal distribution with mean mu and standard\n deviation sigma, by Monte Carlo.\n Returns a stochastic vector called p_vec, corresponding\n to values in x_grid. If a RV is distributed x~N(mu,sigma), then the expectation\n of a continuous function f() is E[f(x)] = numpy.dot(p_vec,f(x_grid)).\n\n Parameters\n ----------\n x_grid: numpy.array\n A sorted 1D array of floats representing discrete values that a normally\n distributed RV could take on.\n mu: float\n Mean of the normal distribution to be approximated.\n sigma: float\n Standard deviation of the normal distribution to be approximated.\n N_draws: int\n Number of draws to use in Monte Carlo.\n\n Returns\n -------\n p_vec: numpy.array\n A stochastic vector with probability weights for each x in x_grid.\n '''\n\n # Take random draws from the desired normal distribution\n random_draws = np.random.normal(loc = mu, scale = sigma, size = N_draws)\n\n # Compute the distance between the draws and points in x_grid\n distance = np.abs(x_grid[:,np.newaxis] - random_draws[np.newaxis,:])\n\n # Find the indices of the points in x_grid that are closest to the draws\n distance_minimizing_index = np.argmin(distance,axis=0)\n\n # For each point in x_grid, the approximate probability of that point is the number\n # of Monte Carlo draws that are closest to that point\n p_vec = np.zeros_like(x_grid)\n for p_index,p in enumerate(p_vec):\n p_vec[p_index] = np.sum(distance_minimizing_index==p_index) / N_draws\n\n # Check for obvious errors, and return p_vec\n assert (np.all(p_vec>=0.)) and (np.all(p_vec<=1.)) and (np.isclose(np.sum(p_vec)),1.)\n return p_vec\n\n\ndef makeTauchenAR1(N, sigma=1.0, rho=0.9, bound=3.0):\n '''\n Function to return a discretized version of an AR1 process.\n See http://www.fperri.net/TEACHING/macrotheory08/numerical.pdf for details\n\n Parameters\n ----------\n N: int\n Size of discretized grid\n sigma: float\n Standard deviation of the error term\n rho: float\n AR1 coefficient\n bound: float\n The highest (lowest) grid point will be bound (-bound) multiplied by the unconditional\n standard deviation of the process\n\n Returns\n -------\n y: np.array\n Grid points on which the discretized process takes values\n trans_matrix: np.array\n Markov transition array for the discretized process\n\n Written by Edmund S. Crawley\n Latest update: 27 October 2017\n '''\n yN = bound*sigma/((1-rho**2)**0.5)\n y = np.linspace(-yN,yN,N)\n d = y[1]-y[0]\n trans_matrix = np.ones((N,N))\n for j in range(N):\n for k_1 in range(N-2):\n k=k_1+1\n trans_matrix[j,k] = stats.norm.cdf((y[k] + d/2.0 - rho*y[j])/sigma) - stats.norm.cdf((y[k] - d/2.0 - rho*y[j])/sigma)\n trans_matrix[j,0] = stats.norm.cdf((y[0] + d/2.0 - rho*y[j])/sigma)\n trans_matrix[j,N-1] = 1.0 - stats.norm.cdf((y[N-1] - d/2.0 - rho*y[j])/sigma)\n\n return y, trans_matrix\n\n\n# ================================================================================\n# ==================== Functions for manipulating discrete distributions =========\n# ================================================================================\n\ndef addDiscreteOutcomeConstantMean(distribution, x, p, sort = False):\n '''\n Adds a discrete outcome of x with probability p to an existing distribution,\n holding constant the relative probabilities of other outcomes and overall mean.\n\n Parameters\n ----------\n distribution : [np.array]\n Two element list containing a list of probabilities and a list of outcomes.\n x : float\n The new value to be added to the distribution.\n p : float\n The probability of the discrete outcome x occuring.\n sort: bool\n Whether or not to sort X before returning it\n\n Returns\n -------\n X : np.array\n Discrete points for discrete probability mass function.\n pmf : np.array\n Probability associated with each point in X.\n\n Written by Matthew N. White\n Latest update: 08 December 2015 by David Low\n '''\n X = np.append(x,distribution[1]*(1-p*x)/(1-p))\n pmf = np.append(p,distribution[0]*(1-p))\n\n if sort:\n indices = np.argsort(X)\n X = X[indices]\n pmf = pmf[indices]\n\n return([pmf,X])\n\ndef addDiscreteOutcome(distribution, x, p, sort = False):\n '''\n Adds a discrete outcome of x with probability p to an existing distribution,\n holding constant the relative probabilities of other outcomes.\n\n Parameters\n ----------\n distribution : [np.array]\n Two element list containing a list of probabilities and a list of outcomes.\n x : float\n The new value to be added to the distribution.\n p : float\n The probability of the discrete outcome x occuring.\n\n Returns\n -------\n X : np.array\n Discrete points for discrete probability mass function.\n pmf : np.array\n Probability associated with each point in X.\n\n Written by Matthew N. White\n Latest update: 11 December 2015\n '''\n\n X = np.append(x,distribution[1])\n pmf = np.append(p,distribution[0]*(1-p))\n\n if sort:\n indices = np.argsort(X)\n X = X[indices]\n pmf = pmf[indices]\n\n return([pmf,X])\n\ndef combineIndepDstns(*distributions):\n '''\n Given n lists (or tuples) whose elements represent n independent, discrete\n probability spaces (probabilities and values), construct a joint pmf over\n all combinations of these independent points. Can take multivariate discrete\n distributions as inputs.\n\n Parameters\n ----------\n distributions : [np.array]\n Arbitrary number of distributions (pmfs). Each pmf is a list or tuple.\n For each pmf, the first vector is probabilities and all subsequent vectors\n are values. For each pmf, this should be true:\n len(X_pmf[0]) == len(X_pmf[j]) for j in range(1,len(distributions))\n\n Returns\n -------\n List of arrays, consisting of:\n\n P_out: np.array\n Probability associated with each point in X_out.\n\n X_out: np.array (as many as in *distributions)\n Discrete points for the joint discrete probability mass function.\n\n Written by Nathan Palmer\n Latest update: 5 July August 2017 by Matthew N White\n '''\n # Very quick and incomplete parameter check:\n for dist in distributions:\n assert len(dist[0]) == len(dist[-1]), \"len(dist[0]) != len(dist[-1])\"\n\n # Get information on the distributions\n dist_lengths = ()\n dist_dims = ()\n for dist in distributions:\n dist_lengths += (len(dist[0]),)\n dist_dims += (len(dist)-1,)\n number_of_distributions = len(distributions)\n\n # Initialize lists we will use\n X_out = []\n P_temp = []\n\n # Now loop through the distributions, tiling and flattening as necessary.\n for dd,dist in enumerate(distributions):\n\n # The shape we want before we tile\n dist_newshape = (1,) * dd + (len(dist[0]),) + \\\n (1,) * (number_of_distributions - dd)\n\n # The tiling we want to do\n dist_tiles = dist_lengths[:dd] + (1,) + dist_lengths[dd+1:]\n\n # Now we are ready to tile.\n # We don't use the np.meshgrid commands, because they do not\n # easily support non-symmetric grids.\n\n # First deal with probabilities\n Pmesh = np.tile(dist[0].reshape(dist_newshape),dist_tiles) # Tiling\n flatP = Pmesh.ravel() # Flatten the tiled arrays\n P_temp += [flatP,] #Add the flattened arrays to the output lists\n\n # Then loop through each value variable\n for n in range(1,dist_dims[dd]+1):\n Xmesh = np.tile(dist[n].reshape(dist_newshape),dist_tiles)\n flatX = Xmesh.ravel()\n X_out += [flatX,]\n\n # We're done getting the flattened X_out arrays we wanted.\n # However, we have a bunch of flattened P_temp arrays, and just want one\n # probability array. So get the probability array, P_out, here.\n P_out = np.prod(np.array(P_temp),axis=0)\n\n assert np.isclose(np.sum(P_out),1),'Probabilities do not sum to 1!'\n return [P_out,] + X_out\n\n# ==============================================================================\n# ============== Functions for generating state space grids ===================\n# ==============================================================================\ndef makeGridExpMult(ming, maxg, ng, timestonest=20):\n '''\n Make a multi-exponentially spaced grid.\n\n Parameters\n ----------\n ming : float\n Minimum value of the grid\n maxg : float\n Maximum value of the grid\n ng : int\n The number of grid points\n timestonest : int\n the number of times to nest the exponentiation\n\n Returns\n -------\n points : np.array\n A multi-exponentially spaced grid\n\n Original Matab code can be found in Chris Carroll's\n [Solution Methods for Microeconomic Dynamic Optimization Problems]\n (http://www.econ2.jhu.edu/people/ccarroll/solvingmicrodsops/) toolkit.\n Latest update: 01 May 2015\n '''\n if timestonest > 0:\n Lming = ming\n Lmaxg = maxg\n for j in range(timestonest):\n Lming = np.log(Lming + 1)\n Lmaxg = np.log(Lmaxg + 1)\n Lgrid = np.linspace(Lming,Lmaxg,ng)\n grid = Lgrid\n for j in range(timestonest):\n grid = np.exp(grid) - 1\n else:\n Lming = np.log(ming)\n Lmaxg = np.log(maxg)\n Lstep = (Lmaxg - Lming)/(ng - 1)\n Lgrid = np.arange(Lming,Lmaxg+0.000001,Lstep)\n grid = np.exp(Lgrid)\n return(grid)\n\n\n# ==============================================================================\n# ============== Uncategorized general functions ===================\n# ==============================================================================\ndef calcWeightedAvg(data,weights):\n '''\n Generates a weighted average of simulated data. The Nth row of data is averaged\n and then weighted by the Nth element of weights in an aggregate average.\n\n Parameters\n ----------\n data : numpy.array\n An array of data with N rows of J floats\n weights : numpy.array\n A length N array of weights for the N rows of data.\n\n Returns\n -------\n weighted_sum : float\n The weighted sum of the data.\n '''\n data_avg = np.mean(data,axis=1)\n weighted_sum = np.dot(data_avg,weights)\n return weighted_sum\n\ndef getPercentiles(data,weights=None,percentiles=[0.5],presorted=False):\n '''\n Calculates the requested percentiles of (weighted) data. Median by default.\n\n Parameters\n ----------\n data : numpy.array\n A 1D array of float data.\n weights : np.array\n A weighting vector for the data.\n percentiles : [float]\n A list of percentiles to calculate for the data. Each element should\n be in (0,1).\n presorted : boolean\n Indicator for whether data has already been sorted.\n\n Returns\n -------\n pctl_out : numpy.array\n The requested percentiles of the data.\n '''\n if data.size < 2:\n return np.zeros(np.array(percentiles).shape) + np.nan\n \n if weights is None: # Set equiprobable weights if none were passed\n weights = np.ones(data.size)/float(data.size)\n\n if presorted: # Sort the data if it is not already\n data_sorted = data\n weights_sorted = weights\n else:\n order = np.argsort(data)\n data_sorted = data[order]\n weights_sorted = weights[order]\n\n cum_dist = np.cumsum(weights_sorted)/np.sum(weights_sorted) # cumulative probability distribution\n\n # Calculate the requested percentiles by interpolating the data over the\n # cumulative distribution, then evaluating at the percentile values\n inv_CDF = interp1d(cum_dist,data_sorted,bounds_error=False,assume_sorted=True)\n pctl_out = inv_CDF(percentiles)\n return pctl_out\n\ndef getLorenzShares(data,weights=None,percentiles=[0.5],presorted=False):\n '''\n Calculates the Lorenz curve at the requested percentiles of (weighted) data.\n Median by default.\n\n Parameters\n ----------\n data : numpy.array\n A 1D array of float data.\n weights : numpy.array\n A weighting vector for the data.\n percentiles : [float]\n A list of percentiles to calculate for the data. Each element should\n be in (0,1).\n presorted : boolean\n Indicator for whether data has already been sorted.\n\n Returns\n -------\n lorenz_out : numpy.array\n The requested Lorenz curve points of the data.\n '''\n if weights is None: # Set equiprobable weights if none were given\n weights = np.ones(data.size)\n\n if presorted: # Sort the data if it is not already\n data_sorted = data\n weights_sorted = weights\n else:\n order = np.argsort(data)\n data_sorted = data[order]\n weights_sorted = weights[order]\n\n cum_dist = np.cumsum(weights_sorted)/np.sum(weights_sorted) # cumulative probability distribution\n temp = data_sorted*weights_sorted\n cum_data = np.cumsum(temp)/sum(temp) # cumulative ownership shares\n\n # Calculate the requested Lorenz shares by interpolating the cumulative ownership\n # shares over the cumulative distribution, then evaluating at requested points\n lorenzFunc = interp1d(cum_dist,cum_data,bounds_error=False,assume_sorted=True)\n lorenz_out = lorenzFunc(percentiles)\n return lorenz_out\n\ndef calcSubpopAvg(data,reference,cutoffs,weights=None):\n '''\n Calculates the average of (weighted) data between cutoff percentiles of a\n reference variable.\n\n Parameters\n ----------\n data : numpy.array\n A 1D array of float data.\n reference : numpy.array\n A 1D array of float data of the same length as data.\n cutoffs : [(float,float)]\n A list of doubles with the lower and upper percentile bounds (should be\n in [0,1]).\n weights : numpy.array\n A weighting vector for the data.\n\n Returns\n -------\n slice_avg\n The (weighted) average of data that falls within the cutoff percentiles\n of reference.\n\n '''\n if weights is None: # Set equiprobable weights if none were given\n weights = np.ones(data.size)\n\n # Sort the data and generate a cumulative distribution\n order = np.argsort(reference)\n data_sorted = data[order]\n weights_sorted = weights[order]\n cum_dist = np.cumsum(weights_sorted)/np.sum(weights_sorted)\n\n # For each set of cutoffs, calculate the average of data that falls within\n # the cutoff percentiles of reference\n slice_avg = []\n for j in range(len(cutoffs)):\n bot = np.searchsorted(cum_dist,cutoffs[j][0])\n top = np.searchsorted(cum_dist,cutoffs[j][1])\n slice_avg.append(np.sum(data_sorted[bot:top]*weights_sorted[bot:top])/\n np.sum(weights_sorted[bot:top]))\n return slice_avg\n\ndef kernelRegression(x,y,bot=None,top=None,N=500,h=None):\n '''\n Performs a non-parametric Nadaraya-Watson 1D kernel regression on given data\n with optionally specified range, number of points, and kernel bandwidth.\n\n Parameters\n ----------\n x : np.array\n The independent variable in the kernel regression.\n y : np.array\n The dependent variable in the kernel regression.\n bot : float\n Minimum value of interest in the regression; defaults to min(x).\n top : float\n Maximum value of interest in the regression; defaults to max(y).\n N : int\n Number of points to compute.\n h : float\n The bandwidth of the (Epanechnikov) kernel. To-do: GENERALIZE.\n\n Returns\n -------\n regression : LinearInterp\n A piecewise locally linear kernel regression: y = f(x).\n '''\n # Fix omitted inputs\n if bot is None:\n bot = np.min(x)\n if top is None:\n top = np.max(x)\n if h is None:\n h = 2.0*(top - bot)/float(N) # This is an arbitrary default\n\n # Construct a local linear approximation\n x_vec = np.linspace(bot,top,num=N)\n y_vec = np.zeros_like(x_vec) + np.nan\n for j in range(N):\n x_here = x_vec[j]\n weights = epanechnikovKernel(x,x_here,h)\n y_vec[j] = np.dot(weights,y)/np.sum(weights)\n regression = interp1d(x_vec,y_vec,bounds_error=False,assume_sorted=True)\n return regression\n\ndef epanechnikovKernel(x,ref_x,h=1.0):\n '''\n The Epanechnikov kernel.\n\n Parameters\n ----------\n x : np.array\n Values at which to evaluate the kernel\n x_ref : float\n The reference point\n h : float\n Kernel bandwidth\n\n Returns\n -------\n out : np.array\n Kernel values at each value of x\n '''\n u = (x-ref_x)/h # Normalize distance by bandwidth\n these = np.abs(u) <= 1.0 # Kernel = 0 outside [-1,1]\n out = np.zeros_like(x) # Initialize kernel output\n out[these] = 0.75*(1.0-u[these]**2.0) # Evaluate kernel\n return out\n\n\n# ==============================================================================\n# ============== Some basic plotting tools ====================================\n# ==============================================================================\n\ndef plotFuncs(functions,bottom,top,N=1000,legend_kwds = None):\n '''\n Plots 1D function(s) over a given range.\n\n Parameters\n ----------\n functions : [function] or function\n A single function, or a list of functions, to be plotted.\n bottom : float\n The lower limit of the domain to be plotted.\n top : float\n The upper limit of the domain to be plotted.\n N : int\n Number of points in the domain to evaluate.\n legend_kwds: None, or dictionary\n If not None, the keyword dictionary to pass to plt.legend\n\n Returns\n -------\n none\n '''\n import matplotlib.pyplot as plt\n if type(functions)==list:\n function_list = functions\n else:\n function_list = [functions]\n\n for function in function_list:\n x = np.linspace(bottom,top,N,endpoint=True)\n y = function(x)\n plt.plot(x,y)\n plt.xlim([bottom, top])\n if legend_kwds is not None:\n plt.legend(**legend_kwds)\n plt.show()\n\ndef plotFuncsDer(functions,bottom,top,N=1000,legend_kwds = None):\n '''\n Plots the first derivative of 1D function(s) over a given range.\n\n Parameters\n ----------\n function : function\n A function or list of functions, the derivatives of which are to be plotted.\n bottom : float\n The lower limit of the domain to be plotted.\n top : float\n The upper limit of the domain to be plotted.\n N : int\n Number of points in the domain to evaluate.\n legend_kwds: None, or dictionary\n If not None, the keyword dictionary to pass to plt.legend\n\n Returns\n -------\n none\n '''\n import matplotlib.pyplot as plt\n if type(functions)==list:\n function_list = functions\n else:\n function_list = [functions]\n\n step = (top-bottom)/N\n for function in function_list:\n x = np.arange(bottom,top,step)\n y = function.derivative(x)\n plt.plot(x,y)\n plt.xlim([bottom, top])\n if legend_kwds is not None:\n plt.legend(**legend_kwds)\n plt.show()\n\n\ndef determine_platform():\n \"\"\" Untility function to return the platform currenlty in use.\n\n Returns\n ---------\n pf: str\n 'darwin' (MacOS), 'debian'(debian Linux) or 'win' (windows)\n \"\"\"\n import platform\n pform = platform.platform().lower()\n if 'darwin' in pform:\n pf = 'darwin' # MacOS\n elif 'debian' in pform:\n pf = 'debian' # Probably cloud (MyBinder, CoLab, ...)\n elif 'ubuntu' in pform:\n pf = 'debian' # Probably cloud (MyBinder, CoLab, ...)\n elif 'win' in pform:\n pf = 'win'\n else:\n raise ValueError('Not able to find out the platform.')\n return pf\n\ndef test_latex_installation(pf):\n \"\"\" Test to check if latex is installed on the machine.\n\n Parameters\n -----------\n pf: str (platform)\n output of determine_platform()\n\n Returns\n --------\n bool: Boolean\n True if latex found, else installed in the case of debian\n otherwise ImportError raised to direct user to install latex manually\n \"\"\"\n # Test whether latex is installed (some of the figures require it)\n from distutils.spawn import find_executable\n\n latexExists = False\n\n if find_executable('latex'):\n latexExists = True\n return True\n\n if not latexExists:\n print('Some of the figures below require a full installation of LaTeX')\n # If running on Mac or Win, user can be assumed to be able to install\n # any missing packages in response to error messages; but not on cloud\n # so load LaTeX by hand (painfully slowly)\n if 'debian' in pf: # CoLab and MyBinder are both ubuntu\n print('Installing LaTeX now; please wait 3-5 minutes')\n from IPython.utils import io\n \n with io.capture_output() as captured: # Hide hideously long output \n os.system('apt-get update')\n os.system('apt-get install texlive texlive-latex-extra texlive-xetex dvipng')\n latexExists=True\n return True\n else:\n raise ImportError('Please install a full distribution of LaTeX on your computer then rerun. \\n \\\n A full distribution means textlive, texlive-latex-extras, texlive-xetex, dvipng, and ghostscript')\n\ndef in_ipynb():\n \"\"\" If the ipython process contains 'terminal' assume not in a notebook.\n\n Returns\n --------\n bool: Boolean\n True if called from a jupyter notebook, else False\n \"\"\"\n try:\n if 'terminal' in str(type(get_ipython())):\n return False\n else:\n return True\n except NameError:\n return False\n\n\ndef setup_latex_env_notebook(pf, latexExists):\n \"\"\" This is needed for use of the latex_envs notebook extension\n which allows the use of environments in Markdown.\n\n Parameters\n -----------\n pf: str (platform)\n output of determine_platform()\n \"\"\"\n import os\n from matplotlib import rc\n import matplotlib.pyplot as plt\n plt.rc('font', family='serif')\n plt.rc('text', usetex=latexExists)\n if latexExists:\n latex_preamble = r'\\usepackage{amsmath}\\usepackage{amsfonts}\\usepackage[T1]{fontenc}'\n latexdefs_path = os.getcwd()+'/latexdefs.tex'\n if os.path.isfile(latexdefs_path):\n latex_preamble = latex_preamble+r'\\input{'+latexdefs_path+r'}'\n else: # the required latex_envs package needs this file to exist even if it is empty\n from pathlib import Path\n Path(latexdefs_path).touch()\n plt.rcParams['text.latex.preamble'] = latex_preamble\n\n\ndef make_figs(figure_name, saveFigs, drawFigs, target_dir=\"Figures\"):\n \"\"\" Utility function to save figure in multiple formats and display the image.\n\n Parameters\n ----------\n figure_name: str\n name of the figure\n saveFigs: bool\n True if the figure needs to be written to disk else False\n drawFigs: bool\n True if the figure should be displayed using plt.draw()\n target_dir: str, default = 'Figures/'\n Name of folder to save figures to in the current directory\n \n \"\"\"\n import matplotlib.pyplot as plt\n if saveFigs:\n import os\n # Where to put any figures that the user wants to save\n my_file_path = os.getcwd() # Find pathname to this file:\n Figures_dir = os.path.join(my_file_path, \"{}\".format(figure_name)) # LaTeX document assumes figures will be here\n if not os.path.exists(Figures_dir): \n os.makedirs(Figures_dir) # If dir does not exist, create it\n # Save the figures in several formats\n print(\"Saving figure {} in {}\".format(figure_name, target_dir))\n plt.savefig(os.path.join(target_dir, '{}.jpg'.format(figure_name))) # For web/html\n plt.savefig(os.path.join(target_dir, '{}.png'.format(figure_name))) # For web/html\n plt.savefig(os.path.join(target_dir, '{}.pdf'.format(figure_name))) # For LaTeX\n plt.savefig(os.path.join(target_dir, '{}.svg'.format(figure_name))) # For html5\n # Make sure it's possible to plot it by checking for GUI\n if drawFigs and find_gui():\n plt.ion() # Counterintuitively, you want interactive mode on if you don't want to interact\n plt.draw() # Change to false if you want to pause after the figure\n plt.pause(2)\n\ndef find_gui():\n \"\"\" Quick fix to check if matplotlib is running in a GUI environment.\n\n Returns\n -------\n bool: Boolean\n True if it's a GUI environment, False if not.\n \"\"\"\n try:\n import matplotlib.pyplot as plt\n except:\n return False\n if plt.get_backend() == 'Agg':\n return False\n return True\n"
] |
[
[
"numpy.dot",
"matplotlib.pyplot.legend",
"scipy.stats.norm.cdf",
"numpy.linspace",
"numpy.sqrt",
"matplotlib.pyplot.rc",
"numpy.cumsum",
"numpy.all",
"numpy.max",
"matplotlib.pyplot.plot",
"numpy.mean",
"numpy.argmin",
"numpy.searchsorted",
"numpy.zeros_like",
"numpy.exp",
"numpy.clip",
"numpy.arange",
"scipy.special.erfc",
"scipy.interpolate.interp1d",
"scipy.special.erf",
"numpy.polynomial.hermite.hermgauss",
"numpy.zeros",
"numpy.log",
"numpy.min",
"matplotlib.pyplot.get_backend",
"numpy.append",
"numpy.argsort",
"matplotlib.pyplot.show",
"numpy.array",
"numpy.sum",
"matplotlib.pyplot.ion",
"numpy.abs",
"scipy.stats.norm.pdf",
"numpy.ones",
"matplotlib.pyplot.draw",
"numpy.random.normal",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.pause"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tridao/metal
|
[
"a077d52d42453be9ca345db73281fb3dc198399c"
] |
[
"tests/metal/tuners/test_random_search_tuner.py"
] |
[
"import unittest\n\nimport numpy as np\n\nfrom metal.tuners.random_tuner import RandomSearchTuner\n\n\nclass RandomSearchModelTunerTest(unittest.TestCase):\n def test_config_constant(self):\n search_space = {\"a\": 1}\n tuner = RandomSearchTuner(None, None, seed=123)\n configs = list(tuner.config_generator(search_space, max_search=10))\n self.assertEqual(len(configs), 1)\n\n def test_config_list(self):\n search_space = {\"a\": [1, 2]}\n tuner = RandomSearchTuner(None, None, seed=123)\n configs = list(tuner.config_generator(search_space, max_search=10))\n self.assertEqual(len(configs), 2)\n\n def test_config_two_values(self):\n search_space = {\"a\": [1], \"b\": [1, 2, 3]}\n tuner = RandomSearchTuner(None, None, seed=123)\n configs = list(tuner.config_generator(search_space, max_search=10))\n self.assertEqual(len(configs), 3)\n\n def test_config_range(self):\n search_space = {\"a\": [1], \"b\": [1, 2, 3], \"c\": {\"range\": [1, 10]}}\n tuner = RandomSearchTuner(None, None, seed=123)\n configs = list(tuner.config_generator(search_space, max_search=10))\n self.assertEqual(len(configs), 10)\n\n def test_config_unbounded_max_search(self):\n search_space = {\"a\": [1], \"b\": [1, 2, 3], \"c\": {\"range\": [1, 10]}}\n tuner = RandomSearchTuner(None, None, seed=123)\n configs = list(tuner.config_generator(search_space, max_search=0))\n self.assertEqual(len(configs), 3)\n\n def test_config_log_range(self):\n search_space = {\n \"a\": [1],\n \"b\": [1, 2, 3],\n \"c\": {\"range\": [1, 10]},\n \"d\": {\"range\": [1, 10], \"scale\": \"log\"},\n }\n tuner = RandomSearchTuner(None, None, seed=123)\n configs = list(tuner.config_generator(search_space, max_search=20))\n self.assertEqual(len(configs), 20)\n self.assertGreater(\n np.mean([c[\"c\"] for c in configs]),\n np.mean([c[\"d\"] for c in configs]),\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] |
[
[
"numpy.mean"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
fkhiro/kws-ode
|
[
"5751f9b665511908b26e77f6ea5a97bf87823aab"
] |
[
"src/train.py"
] |
[
"from collections import ChainMap\nimport argparse\nimport os\nimport random\nimport sys\n\nfrom torch.autograd import Variable\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.utils.data as data\n\nfrom . import model_ode as mod\nfrom .manage_audio import AudioPreprocessor\n\nimport pickle\n\nclass ConfigBuilder(object):\n def __init__(self, *default_configs):\n self.default_config = ChainMap(*default_configs)\n\n def build_argparse(self):\n parser = argparse.ArgumentParser()\n for key, value in self.default_config.items():\n key = \"--{}\".format(key)\n if isinstance(value, tuple):\n parser.add_argument(key, default=list(value), nargs=len(value), type=type(value[0]))\n elif isinstance(value, list):\n parser.add_argument(key, default=value, nargs=\"+\", type=type(value[0]))\n elif isinstance(value, bool) and not value:\n parser.add_argument(key, action=\"store_true\")\n else:\n parser.add_argument(key, default=value, type=type(value))\n return parser\n\n def config_from_argparse(self, parser=None):\n if not parser:\n parser = self.build_argparse()\n args = vars(parser.parse_known_args()[0])\n return ChainMap(args, self.default_config)\n\ndef print_eval(name, scores, labels, loss, end=\"\\n\"):\n batch_size = labels.size(0)\n accuracy = (torch.max(scores, 1)[1].view(batch_size).data == labels.data).float().sum() / batch_size\n loss = loss.item()\n print(\"{} accuracy: {:>5}, loss: {:<25}\".format(name, accuracy, loss), end=end)\n return accuracy.item()\n\ndef set_seed(config):\n seed = config[\"seed\"]\n torch.manual_seed(seed)\n np.random.seed(seed)\n if not config[\"no_cuda\"]:\n torch.cuda.manual_seed(seed)\n random.seed(seed)\n\ndef evaluate(config, model=None, test_loader=None):\n calc_batch_size = config[\"calc_batch_size\"]\n calc_count = config[\"calc_count\"] \n if not test_loader:\n _, _, test_set = mod.SpeechDataset.splits(config)\n if not calc_batch_size:\n test_loader = data.DataLoader(\n test_set,\n batch_size=len(test_set),\n collate_fn=test_set.collate_fn)\n calc_batch_size = len(test_set)\n calc_count = len(test_set)\n else:\n test_loader = data.DataLoader(\n test_set,\n batch_size=calc_batch_size,\n collate_fn=test_set.collate_fn)\n if not calc_count:\n calc_count = len(test_set)\n\n if not config[\"no_cuda\"]:\n torch.cuda.set_device(config[\"gpu_no\"])\n if not model:\n model = config[\"model_class\"](config)\n model.load(config[\"input_file\"])\n if not config[\"no_cuda\"]:\n torch.cuda.set_device(config[\"gpu_no\"])\n model.cuda()\n \n if config[\"input_run_bn_file\"]:\n print(\"Input run_bn_file file: {}\".format(config[\"input_run_bn_file\"]))\n model.load_bn_statistics(config[\"input_run_bn_file\"])\n print(model.odefunc.bn_statistics[\"norm1\"].mean_t[0])\n \n print(\"integration time: {}\".format(model.odeblock.integration_time))\n print(\"tol: {}\".format(model.odeblock.tol))\n print(\"frame length: {} ms\".format(config[\"n_fft\"]*1000/16000))\n print(\"stride: {} ms\".format(config[\"hop_ms\"]))\n print(\"audio preprocessor type: {}\".format(config[\"audio_preprocess_type\"])) \n print(\"batch size = {}, calc count = {}\".format(calc_batch_size, calc_count))\n print(\"bn mode: {}\".format(config[\"bn_mode\"]))\n\n model.eval()\n criterion = nn.CrossEntropyLoss()\n results = []\n total = 0\n nfe_total = 0\n \n for model_in, labels in test_loader:\n model.odeblock.nfe = 0\n model_in = Variable(model_in, requires_grad=False)\n if not config[\"no_cuda\"]:\n model_in = model_in.cuda()\n labels = labels.cuda()\n scores = model(model_in)\n labels = Variable(labels, requires_grad=False)\n loss = criterion(scores, labels)\n results.append(print_eval(\"test\", scores, labels, loss) * model_in.size(0))\n print(\"nfe counts = {}\".format(model.odeblock.nfe))\n total += model_in.size(0)\n nfe_total += model.odeblock.nfe\n if total >= calc_count:\n break\n \n print(\"final test accuracy: {}\".format(sum(results) / total))\n print(\"average nfe: {}\".format(nfe_total*calc_batch_size / total))\n\n\ndef train(config):\n output_dir = os.path.dirname(os.path.abspath(config[\"output_file\"]))\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n \n f = None\n if config[\"log\"]:\n output_dir = os.path.dirname(os.path.abspath(config[\"log\"]))\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n print(\"Out log file: {}\".format(config[\"log\"]))\n f = open(config[\"log\"], \"w\")\n \n f_eval = None\n if config[\"log_eval\"]:\n output_dir = os.path.dirname(os.path.abspath(config[\"log_eval\"]))\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n print(\"Out log_eval file: {}\".format(config[\"log_eval\"]))\n f_eval = open(config[\"log_eval\"], \"w\")\n \n if config[\"out_run_bn_file\"]:\n output_dir = os.path.dirname(os.path.abspath(config[\"out_run_bn_file\"]))\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n print(\"Out run_bn_file file: {}\".format(config[\"out_run_bn_file\"]))\n\n train_set, dev_set, test_set = mod.SpeechDataset.splits(config)\n\n model = config[\"model_class\"](config)\n if config[\"input_file\"]:\n model.load(config[\"input_file\"])\n if not config[\"no_cuda\"]:\n torch.cuda.set_device(config[\"gpu_no\"])\n model.cuda()\n \n optimizer = torch.optim.SGD(model.parameters(), lr=config[\"lr\"][0], nesterov=config[\"use_nesterov\"], weight_decay=config[\"weight_decay\"], momentum=config[\"momentum\"])\n schedule_steps = config[\"schedule\"]\n schedule_steps.append(np.inf)\n sched_idx = 0\n criterion = nn.CrossEntropyLoss()\n max_acc = 0\n\n train_loader = data.DataLoader(\n train_set,\n batch_size=config[\"batch_size\"],\n shuffle=True, drop_last=True,\n collate_fn=train_set.collate_fn)\n dev_loader = data.DataLoader(\n dev_set,\n batch_size=min(len(dev_set), 16),\n shuffle=True,\n collate_fn=dev_set.collate_fn)\n test_loader = data.DataLoader(\n test_set,\n batch_size=min(len(test_set), 16),\n shuffle=True,\n collate_fn=test_set.collate_fn)\n step_no = 0\n acc_total = 0\n loss_total = 0\n statistics_divided = False\n\n print(\"learning rate: {}\".format(config[\"lr\"][sched_idx]))\n print(\"weight decay: {}\".format(config[\"weight_decay\"]))\n print(\"batch size: {}\".format(config[\"batch_size\"])) \n print(\"integration time: {}\".format(model.odeblock.integration_time))\n print(\"tol: {}\".format(model.odeblock.tol))\n print(\"frame length: {} ms\".format(config[\"n_fft\"]*1000/16000))\n print(\"stride: {} ms\".format(config[\"hop_ms\"]))\n print(\"audio preprocessor type: {}\".format(config[\"audio_preprocess_type\"]))\n print(\"bn mode: {}\".format(config[\"bn_mode\"]))\n print(\"Start outputting log_eval at step_no = {}\".format(schedule_steps[-2])) # [-1] == inf\n\n for epoch_idx in range(config[\"n_epochs\"]):\n model.reset_bn_statistics()\n statistics_divided = False\n for batch_idx, (model_in, labels) in enumerate(train_loader):\n model.train()\n optimizer.zero_grad()\n if not config[\"no_cuda\"]:\n model_in = model_in.cuda()\n labels = labels.cuda()\n model_in = Variable(model_in, requires_grad=False)\n scores = model(model_in)\n labels = Variable(labels, requires_grad=False) \n loss = criterion(scores, labels)\n\n model.switch_backward()\n loss.backward()\n optimizer.step()\n model.switch_forward()\n\n step_no += 1\n if step_no > schedule_steps[sched_idx]:\n sched_idx += 1\n print(\"changing learning rate to {}\".format(config[\"lr\"][sched_idx]))\n optimizer = torch.optim.SGD(model.parameters(), lr=config[\"lr\"][sched_idx], nesterov=config[\"use_nesterov\"], momentum=config[\"momentum\"], weight_decay=config[\"weight_decay\"])\n \n acc_total += print_eval(\"train step #{}\".format(step_no), scores, labels, loss)\n loss_total += loss.item()\n if step_no%10 == 0:\n if f:\n f.write(\"{}, {}, {}\\n\".format(step_no, loss_total/10.0, acc_total/10.0))\n f.flush()\n loss_total = 0\n acc_total = 0\n \n model.odeblock.nfe = 0\n \n if epoch_idx % config[\"dev_every\"] == config[\"dev_every\"] - 1: \n model.average_bn_statistics()\n statistics_divided = True\n if step_no < schedule_steps[-2]:\n print(\"auto-saving model...\")\n model.save(config[\"output_file\"])\n model.save_bn_statistics(config[\"out_run_bn_file\"])\n else:\n model.eval()\n accs = []\n saved = ' '\n for model_in, labels in dev_loader:\n model_in = Variable(model_in, requires_grad=False)\n if not config[\"no_cuda\"]:\n model_in = model_in.cuda()\n labels = labels.cuda()\n scores = model(model_in)\n labels = Variable(labels, requires_grad=False)\n loss = criterion(scores, labels)\n loss_numeric = loss.item()\n accs.append(print_eval(\"dev\", scores, labels, loss))\n avg_acc = np.mean(accs)\n print(\"final dev accuracy: {}\".format(avg_acc))\n if avg_acc > max_acc:\n print(\"saving best model...\")\n max_acc = avg_acc\n model.save(config[\"output_file\"])\n model.save_bn_statistics(config[\"out_run_bn_file\"])\n saved = '*'\n \n if f_eval:\n f_eval.write(\"{}, {}, {}, {}\\n\".format(epoch_idx, avg_acc, step_no, saved))\n f_eval.flush()\n\n\n if f:\n f.close()\n if f_eval:\n f_eval.close()\n\n\n\ndef main():\n output_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"model\", \"model.pt\")\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--model\", choices=[x.value for x in list(mod.ConfigType)], default=\"ode-res8-narrow\", type=str)\n config, _ = parser.parse_known_args()\n\n global_config = dict(no_cuda=False, n_epochs=500, lr=[0.001], schedule=[np.inf], batch_size=64, dev_every=10, seed=0,\n use_nesterov=False, input_file=\"\", output_file=output_file, gpu_no=1, cache_size=32768, momentum=0.9, weight_decay=0.00001)\n \n mod_cls = mod.find_model(config.model)\n if not mod_cls:\n print(\"Error, not implemented: {}\".format(config.model))\n exit()\n \n builder = ConfigBuilder(\n mod.find_config(config.model),\n mod.SpeechDataset.default_config(),\n global_config)\n parser = builder.build_argparse()\n parser.add_argument(\"--type\", choices=[\"train\", \"eval\", \"calc\"], default=\"train\", type=str)\n\n parser.add_argument(\"--integration_time\", default=1.0, type=float)\n parser.add_argument(\"--tol\", default=1e-3, type=float)\n parser.add_argument(\"--log\", default=None, type=str)\n parser.add_argument(\"--log_eval\", default=None, type=str)\n parser.add_argument(\"--hop_ms\", default=10, type=int)\n parser.add_argument(\"--n_fft\", default=480, type=int) # 30ms\n parser.add_argument(\"--out_run_bn_file\", default=None, type=str)\n parser.add_argument(\"--input_run_bn_file\", default=None, type=str)\n parser.add_argument(\"--calc_batch_size\", default=None, type=int)\n parser.add_argument(\"--calc_count\", default=None, type=int)\n parser.add_argument(\"--bn_mode\", choices=[\"complement\", \"polyfit2\"], default=\"complement\", type=str)\n\n config = builder.config_from_argparse(parser)\n config[\"model_class\"] = mod_cls\n set_seed(config)\n\n if config[\"type\"] == \"train\":\n train(config)\n elif config[\"type\"] == \"eval\":\n evaluate(config)\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.max",
"torch.cuda.manual_seed",
"numpy.random.seed",
"torch.cuda.set_device",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"numpy.mean",
"torch.autograd.Variable"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
matpompili/Cirq
|
[
"b9ce387a7fc1f571b3d6e903c46543c3578677cb",
"b9ce387a7fc1f571b3d6e903c46543c3578677cb"
] |
[
"cirq/ion/convert_to_ion_gates_test.py",
"cirq/ops/common_channels_test.py"
] |
[
"# Copyright 2018 The Cirq Developers\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\nimport pytest\n\nimport numpy as np\n\nimport cirq\n\n\nclass OtherX(cirq.SingleQubitGate):\n def _unitary_(self) -> np.ndarray:\n return np.array([[0, 1], [1, 0]])\n\n\nclass NoUnitary(cirq.SingleQubitGate):\n pass\n\n\nclass OtherCNOT(cirq.TwoQubitGate):\n def _unitary_(self) -> np.ndarray:\n return np.array([[1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 0, 1],\n [0, 0, 1, 0]])\n\n\ndef test_convert_to_ion_gates():\n q0 = cirq.GridQubit(0, 0)\n q1 = cirq.GridQubit(0, 1)\n op = cirq.CNOT(q0, q1)\n circuit = cirq.Circuit()\n\n with pytest.raises(TypeError):\n cirq.ion.ConvertToIonGates().convert_one(circuit)\n\n with pytest.raises(TypeError):\n cirq.ion.ConvertToIonGates().convert_one(NoUnitary().on(q0))\n\n no_unitary_op = NoUnitary().on(q0)\n assert cirq.ion.ConvertToIonGates(ignore_failures=True).convert_one(\n no_unitary_op) == [no_unitary_op]\n\n rx = cirq.ion.ConvertToIonGates().convert_one(OtherX().on(q0))\n rop = cirq.ion.ConvertToIonGates().convert_one(op)\n rcnot = cirq.ion.ConvertToIonGates().convert_one(OtherCNOT().on(q0, q1))\n assert rx == [\n cirq.PhasedXPowGate(phase_exponent=1).on(cirq.GridQubit(0, 0))\n ]\n assert rop == [\n cirq.ry(np.pi / 2).on(op.qubits[0]),\n cirq.ms(np.pi / 4).on(op.qubits[0], op.qubits[1]),\n cirq.rx(-1 * np.pi / 2).on(op.qubits[0]),\n cirq.rx(-1 * np.pi / 2).on(op.qubits[1]),\n cirq.ry(-1 * np.pi / 2).on(op.qubits[0])\n ]\n assert rcnot == [\n cirq.PhasedXPowGate(phase_exponent=-0.75,\n exponent=0.5).on(cirq.GridQubit(0, 0)),\n cirq.PhasedXPowGate(phase_exponent=1,\n exponent=0.25).on(cirq.GridQubit(0, 1)),\n cirq.T.on(cirq.GridQubit(0, 0)),\n cirq.ms(-0.5 * np.pi / 2).on(cirq.GridQubit(0, 0), cirq.GridQubit(0,\n 1)),\n (cirq.Y**0.5).on(cirq.GridQubit(0, 0)),\n cirq.PhasedXPowGate(phase_exponent=1,\n exponent=0.25).on(cirq.GridQubit(0, 1)),\n (cirq.Z**-0.75).on(cirq.GridQubit(0, 0))\n ]\n\n\ndef test_convert_to_ion_circuit():\n q0 = cirq.LineQubit(0)\n q1 = cirq.LineQubit(1)\n us = cirq.Duration(nanos=1000)\n ion_device = cirq.IonDevice(us, us, us, [q0, q1])\n\n clifford_circuit_1 = cirq.Circuit()\n clifford_circuit_1.append(\n [cirq.X(q0), cirq.H(q1),\n cirq.ms(np.pi / 4).on(q0, q1)])\n ion_circuit_1 = cirq.ion.ConvertToIonGates().convert_circuit(\n clifford_circuit_1)\n\n ion_device.validate_circuit(ion_circuit_1)\n cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(\n clifford_circuit_1, ion_circuit_1, atol=1e-6)\n clifford_circuit_2 = cirq.Circuit()\n clifford_circuit_2.append(\n [cirq.X(q0),\n cirq.CNOT(q1, q0),\n cirq.ms(np.pi / 4).on(q0, q1)])\n ion_circuit_2 = cirq.ion.ConvertToIonGates().convert_circuit(\n clifford_circuit_2)\n ion_device.validate_circuit(ion_circuit_2)\n cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(\n clifford_circuit_2, ion_circuit_2, atol=1e-6)\n",
"# Copyright 2018 The Cirq Developers\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\nimport numpy as np\nimport pytest\n\nimport cirq\n\nX = np.array([[0, 1], [1, 0]])\nY = np.array( [[0, -1j], [1j, 0]])\nZ = np.array( [[1, 0], [0, -1]])\n\nround_to_6_prec = cirq.CircuitDiagramInfoArgs(known_qubits=None,\n known_qubit_count=None,\n use_unicode_characters=True,\n precision=6,\n qubit_map=None)\n\nround_to_2_prec = cirq.CircuitDiagramInfoArgs(known_qubits=None,\n known_qubit_count=None,\n use_unicode_characters=True,\n precision=2,\n qubit_map=None)\n\n\ndef assert_mixtures_equal(actual, expected):\n \"\"\"Assert equal for tuple of mixed scalar and array types.\"\"\"\n for a, e in zip(actual, expected):\n np.testing.assert_almost_equal(a[0], e[0])\n np.testing.assert_almost_equal(a[1], e[1])\n\n\ndef test_asymmetric_depolarizing_channel():\n d = cirq.asymmetric_depolarize(0.1, 0.2, 0.3)\n np.testing.assert_almost_equal(cirq.channel(d),\n (np.sqrt(0.4) * np.eye(2),\n np.sqrt(0.1) * X,\n np.sqrt(0.2) * Y,\n np.sqrt(0.3) * Z))\n assert cirq.has_channel(d)\n\n\ndef test_asymmetric_depolarizing_mixture():\n d = cirq.asymmetric_depolarize(0.1, 0.2, 0.3)\n assert_mixtures_equal(cirq.mixture(d),\n ((0.4, np.eye(2)),\n (0.1, X),\n (0.2, Y),\n (0.3, Z)))\n assert cirq.has_mixture(d)\n\n\ndef test_asymmetric_depolarizing_channel_repr():\n cirq.testing.assert_equivalent_repr(\n cirq.AsymmetricDepolarizingChannel(0.1, 0.2, 0.3))\n\n\ndef test_asymmetric_depolarizing_channel_str():\n assert (str(cirq.asymmetric_depolarize(0.1, 0.2, 0.3))\n == 'asymmetric_depolarize(p_x=0.1,p_y=0.2,p_z=0.3)')\n\n\ndef test_asymmetric_depolarizing_channel_eq():\n et = cirq.testing.EqualsTester()\n c = cirq.asymmetric_depolarize(0.0, 0.0, 0.0)\n et.make_equality_group(lambda: c)\n et.add_equality_group(cirq.asymmetric_depolarize(0.0, 0.0, 0.1))\n et.add_equality_group(cirq.asymmetric_depolarize(0.0, 0.1, 0.0))\n et.add_equality_group(cirq.asymmetric_depolarize(0.1, 0.0, 0.0))\n et.add_equality_group(cirq.asymmetric_depolarize(0.1, 0.2, 0.3))\n et.add_equality_group(cirq.asymmetric_depolarize(0.3, 0.4, 0.3))\n et.add_equality_group(cirq.asymmetric_depolarize(1.0, 0.0, 0.0))\n et.add_equality_group(cirq.asymmetric_depolarize(0.0, 1.0, 0.0))\n et.add_equality_group(cirq.asymmetric_depolarize(0.0, 0.0, 1.0))\n\n\[email protected]('p_x,p_y,p_z', (\n (-0.1, 0.0, 0.0),\n (0.0, -0.1, 0.0),\n (0.0, 0.0, -0.1),\n (0.1, -0.1, 0.1)))\ndef test_asymmetric_depolarizing_channel_negative_probability(p_x, p_y, p_z):\n with pytest.raises(ValueError, match='was less than 0'):\n cirq.asymmetric_depolarize(p_x, p_y, p_z)\n\n\[email protected]('p_x,p_y,p_z', (\n (1.1, 0.0, 0.0),\n (0.0, 1.1, 0.0),\n (0.0, 0.0, 1.1),\n (0.1, 0.9, 0.1)))\ndef test_asymmetric_depolarizing_channel_bigly_probability(p_x, p_y, p_z):\n with pytest.raises(ValueError, match='was greater than 1'):\n cirq.asymmetric_depolarize(p_x, p_y, p_z)\n\n\ndef test_asymmetric_depolarizing_channel_text_diagram():\n a = cirq.asymmetric_depolarize(1 / 9, 2 / 9, 3 / 9)\n assert (cirq.circuit_diagram_info(\n a, args=round_to_6_prec) == cirq.CircuitDiagramInfo(\n wire_symbols=('A(0.111111,0.222222,0.333333)',)))\n assert (cirq.circuit_diagram_info(\n a, args=round_to_2_prec) == cirq.CircuitDiagramInfo(\n wire_symbols=('A(0.11,0.22,0.33)',)))\n\n\ndef test_depolarizing_channel():\n d = cirq.depolarize(0.3)\n np.testing.assert_almost_equal(cirq.channel(d),\n (np.sqrt(0.7) * np.eye(2),\n np.sqrt(0.1) * X,\n np.sqrt(0.1) * Y,\n np.sqrt(0.1) * Z))\n assert cirq.has_channel(d)\n\ndef test_depolarizing_mixture():\n d = cirq.depolarize(0.3)\n assert_mixtures_equal(cirq.mixture(d),\n ((0.7, np.eye(2)),\n (0.1, X),\n (0.1, Y),\n (0.1, Z)))\n assert cirq.has_mixture(d)\n\n\ndef test_depolarizing_channel_repr():\n cirq.testing.assert_equivalent_repr(cirq.DepolarizingChannel(0.3))\n\n\ndef test_depolarizing_channel_str():\n assert str(cirq.depolarize(0.3)) == 'depolarize(p=0.3)'\n\n\ndef test_depolarizing_channel_eq():\n et = cirq.testing.EqualsTester()\n c = cirq.depolarize(0.0)\n et.make_equality_group(lambda: c)\n et.add_equality_group(cirq.depolarize(0.1))\n et.add_equality_group(cirq.depolarize(0.9))\n et.add_equality_group(cirq.depolarize(1.0))\n\n\ndef test_depolarizing_channel_invalid_probability():\n with pytest.raises(ValueError, match='was less than 0'):\n cirq.depolarize(-0.1)\n with pytest.raises(ValueError, match='was greater than 1'):\n cirq.depolarize(1.1)\n\n\ndef test_depolarizing_channel_text_diagram():\n d = cirq.depolarize(0.1234567)\n assert (cirq.circuit_diagram_info(\n d, args=round_to_6_prec) == cirq.CircuitDiagramInfo(\n wire_symbols=('D(0.123457)',)))\n assert (cirq.circuit_diagram_info(\n d, args=round_to_2_prec) == cirq.CircuitDiagramInfo(\n wire_symbols=('D(0.12)',)))\n\n\ndef test_generalized_amplitude_damping_channel():\n d = cirq.generalized_amplitude_damp(0.1, 0.3)\n np.testing.assert_almost_equal(cirq.channel(d),\n (np.sqrt(0.1) * np.array([[1., 0.], [0., np.sqrt(1.-0.3)]]),\n np.sqrt(0.1) * np.array([[0., np.sqrt(0.3)], [0., 0.]]),\n np.sqrt(0.9) * np.array([[np.sqrt(1. - 0.3), 0.], [0., 1.]]),\n np.sqrt(0.9) * np.array([[0., 0.], [np.sqrt(0.3), 0.]])))\n assert cirq.has_channel(d)\n assert not cirq.has_mixture(d)\n\n\ndef test_generalized_amplitude_damping_repr():\n cirq.testing.assert_equivalent_repr(\n cirq.GeneralizedAmplitudeDampingChannel(0.1, 0.3))\n\ndef test_generalized_amplitude_damping_str():\n assert (str(cirq.generalized_amplitude_damp(0.1, 0.3))\n == 'generalized_amplitude_damp(p=0.1,gamma=0.3)')\n\n\ndef test_generalized_amplitude_damping_channel_eq():\n et = cirq.testing.EqualsTester()\n c = cirq.generalized_amplitude_damp(0.0, 0.0)\n et.make_equality_group(lambda: c)\n et.add_equality_group(cirq.generalized_amplitude_damp(0.1, 0.0))\n et.add_equality_group(cirq.generalized_amplitude_damp(0.0, 0.1))\n et.add_equality_group(cirq.generalized_amplitude_damp(0.6, 0.4))\n et.add_equality_group(cirq.generalized_amplitude_damp(0.8, 0.2))\n\n\[email protected]('p, gamma', (\n (-0.1, 0.0),\n (0.0, -0.1),\n (0.1, -0.1),\n (-0.1, 0.1)))\ndef test_generalized_amplitude_damping_channel_negative_probability(p, gamma):\n with pytest.raises(ValueError, match='was less than 0'):\n cirq.generalized_amplitude_damp(p, gamma)\n\n\[email protected]('p,gamma', (\n (1.1, 0.0),\n (0.0, 1.1),\n (1.1, 1.1)))\ndef test_generalized_amplitude_damping_channel_bigly_probability(p, gamma):\n with pytest.raises(ValueError, match='was greater than 1'):\n cirq.generalized_amplitude_damp(p, gamma)\n\n\n\ndef test_generalized_amplitude_damping_channel_text_diagram():\n a = cirq.generalized_amplitude_damp(0.1, 0.39558391)\n assert (cirq.circuit_diagram_info(\n a, args=round_to_6_prec) == cirq.CircuitDiagramInfo(\n wire_symbols=('GAD(0.1,0.395584)',)))\n assert (cirq.circuit_diagram_info(\n a, args=round_to_2_prec) == cirq.CircuitDiagramInfo(\n wire_symbols=('GAD(0.1,0.4)',)))\n\n\ndef test_amplitude_damping_channel():\n d = cirq.amplitude_damp(0.3)\n np.testing.assert_almost_equal(cirq.channel(d),\n (np.array([[1., 0.], [0., np.sqrt(1. - 0.3)]]),\n np.array([[0., np.sqrt(0.3)], [0., 0.]])))\n assert cirq.has_channel(d)\n assert not cirq.has_mixture(d)\n\n\ndef test_amplitude_damping_channel_repr():\n cirq.testing.assert_equivalent_repr(\n cirq.AmplitudeDampingChannel(0.3))\n\n\ndef test_amplitude_damping_channel_str():\n assert (str(cirq.amplitude_damp(0.3))\n == 'amplitude_damp(gamma=0.3)')\n\n\ndef test_amplitude_damping_channel_eq():\n et = cirq.testing.EqualsTester()\n c = cirq.amplitude_damp(0.0)\n et.make_equality_group(lambda: c)\n et.add_equality_group(cirq.amplitude_damp(0.1))\n et.add_equality_group(cirq.amplitude_damp(0.4))\n et.add_equality_group(cirq.amplitude_damp(0.6))\n et.add_equality_group(cirq.amplitude_damp(0.8))\n\ndef test_amplitude_damping_channel_invalid_probability():\n with pytest.raises(ValueError, match='was less than 0'):\n cirq.amplitude_damp(-0.1)\n with pytest.raises(ValueError, match='was greater than 1'):\n cirq.amplitude_damp(1.1)\n\n\ndef test_amplitude_damping_channel_text_diagram():\n ad = cirq.amplitude_damp(0.38059322)\n assert (cirq.circuit_diagram_info(\n ad, args=round_to_6_prec) == cirq.CircuitDiagramInfo(\n wire_symbols=('AD(0.380593)',)))\n assert (cirq.circuit_diagram_info(\n ad, args=round_to_2_prec) == cirq.CircuitDiagramInfo(\n wire_symbols=('AD(0.38)',)))\n\n\ndef test_reset_channel():\n r = cirq.reset(cirq.LineQubit(0))\n np.testing.assert_almost_equal(\n cirq.channel(r),\n (np.array([[1., 0.], [0., 0]]), np.array([[0., 1.], [0., 0.]])))\n assert cirq.has_channel(r)\n assert not cirq.has_mixture(r)\n assert cirq.qid_shape(r) == (2,)\n\n r = cirq.reset(cirq.LineQid(0, dimension=3))\n np.testing.assert_almost_equal(\n cirq.channel(r),\n (np.array([[1, 0, 0], [0, 0, 0], [0, 0, 0]]),\n np.array([[0, 1, 0], [0, 0, 0], [0, 0, 0]]),\n np.array([[0, 0, 1], [0, 0, 0], [0, 0, 0]]))) # yapf: disable\n assert cirq.has_channel(r)\n assert not cirq.has_mixture(r)\n assert cirq.qid_shape(r) == (3,)\n\n\ndef test_reset_channel_equality():\n assert cirq.reset(cirq.LineQubit(0)).gate == cirq.ResetChannel()\n assert cirq.reset(cirq.LineQid(0, 3)).gate == cirq.ResetChannel(3)\n\n\ndef test_reset_channel_repr():\n cirq.testing.assert_equivalent_repr(cirq.ResetChannel())\n cirq.testing.assert_equivalent_repr(cirq.ResetChannel(3))\n\n\ndef test_reset_channel_str():\n assert str(cirq.ResetChannel()) == 'reset'\n assert str(cirq.ResetChannel(3)) == 'reset'\n\n\ndef test_reset_channel_text_diagram():\n assert (cirq.circuit_diagram_info(\n cirq.ResetChannel()) == cirq.CircuitDiagramInfo(wire_symbols=('R',)))\n assert (cirq.circuit_diagram_info(\n cirq.ResetChannel(3)) == cirq.CircuitDiagramInfo(wire_symbols=('R',)))\n\n\ndef test_reset_act_on():\n with pytest.raises(TypeError, match=\"Failed to act\"):\n cirq.act_on(cirq.ResetChannel(), object())\n\n args = cirq.ActOnStateVectorArgs(\n target_tensor=cirq.one_hot(index=(1, 1, 1, 1, 1),\n shape=(2, 2, 2, 2, 2),\n dtype=np.complex64),\n available_buffer=np.empty(shape=(2, 2, 2, 2, 2)),\n axes=[1],\n prng=np.random.RandomState(),\n log_of_measurement_results={},\n )\n\n cirq.act_on(cirq.ResetChannel(), args)\n assert args.log_of_measurement_results == {}\n np.testing.assert_allclose(\n args.target_tensor,\n cirq.one_hot(index=(1, 0, 1, 1, 1),\n shape=(2, 2, 2, 2, 2),\n dtype=np.complex64))\n\n cirq.act_on(cirq.ResetChannel(), args)\n assert args.log_of_measurement_results == {}\n np.testing.assert_allclose(\n args.target_tensor,\n cirq.one_hot(index=(1, 0, 1, 1, 1),\n shape=(2, 2, 2, 2, 2),\n dtype=np.complex64))\n\n\ndef test_phase_damping_channel():\n d = cirq.phase_damp(0.3)\n np.testing.assert_almost_equal(cirq.channel(d),\n (np.array([[1.0, 0.], [0., np.sqrt(1 - 0.3)]]),\n np.array([[0., 0.], [0., np.sqrt(0.3)]])))\n assert cirq.has_channel(d)\n assert not cirq.has_mixture(d)\n\n\ndef test_phase_damping_channel_repr():\n cirq.testing.assert_equivalent_repr(\n cirq.PhaseDampingChannel(0.3))\n\n\ndef test_phase_damping_channel_str():\n assert (str(cirq.phase_damp(0.3))\n == 'phase_damp(gamma=0.3)')\n\n\ndef test_phase_damping_channel_eq():\n et = cirq.testing.EqualsTester()\n c = cirq.phase_damp(0.0)\n et.make_equality_group(lambda: c)\n et.add_equality_group(cirq.phase_damp(0.1))\n et.add_equality_group(cirq.phase_damp(0.4))\n et.add_equality_group(cirq.phase_damp(0.6))\n et.add_equality_group(cirq.phase_damp(0.8))\n\n\ndef test_phase_damping_channel_invalid_probability():\n with pytest.raises(ValueError, match='was less than 0'):\n cirq.phase_damp(-0.1)\n with pytest.raises(ValueError, match='was greater than 1'):\n cirq.phase_damp(1.1)\n\n\ndef test_phase_damping_channel_text_diagram():\n pd = cirq.phase_damp(0.1000009)\n assert (cirq.circuit_diagram_info(\n pd, args=round_to_6_prec) == cirq.CircuitDiagramInfo(\n wire_symbols=('PD(0.100001)',)))\n assert (cirq.circuit_diagram_info(\n pd, args=round_to_2_prec) == cirq.CircuitDiagramInfo(\n wire_symbols=('PD(0.1)',)))\n\n\ndef test_phase_flip_channel():\n d = cirq.phase_flip(0.3)\n np.testing.assert_almost_equal(\n cirq.channel(d), (np.sqrt(1. - 0.3) * np.eye(2), np.sqrt(0.3) * Z))\n assert cirq.has_channel(d)\n\n\ndef test_phase_flip_mixture():\n d = cirq.phase_flip(0.3)\n assert_mixtures_equal(cirq.mixture(d), ((0.7, np.eye(2)), (0.3, Z)))\n assert cirq.has_mixture(d)\n\n\ndef test_phase_flip_overload():\n d = cirq.phase_flip()\n d2 = cirq.phase_flip(0.3)\n assert str(d) == 'Z'\n assert str(d2) == 'phase_flip(p=0.3)'\n\ndef test_phase_flip_channel_repr():\n cirq.testing.assert_equivalent_repr(\n cirq.PhaseFlipChannel(0.3))\n\n\ndef test_phase_flip_channel_str():\n assert (str(cirq.phase_flip(0.3))\n == 'phase_flip(p=0.3)')\n\n\ndef test_phase_flip_channel_eq():\n et = cirq.testing.EqualsTester()\n c = cirq.phase_flip(0.0)\n et.make_equality_group(lambda: c)\n et.add_equality_group(cirq.phase_flip(0.1))\n et.add_equality_group(cirq.phase_flip(0.4))\n et.add_equality_group(cirq.phase_flip(0.6))\n et.add_equality_group(cirq.phase_flip(0.8))\n\n\n\ndef test_phase_flip_channel_invalid_probability():\n with pytest.raises(ValueError, match='was less than 0'):\n cirq.phase_flip(-0.1)\n with pytest.raises(ValueError, match='was greater than 1'):\n cirq.phase_flip(1.1)\n\n\ndef test_phase_flip_channel_text_diagram():\n pf = cirq.phase_flip(0.987654)\n assert (cirq.circuit_diagram_info(\n pf, args=round_to_6_prec) == cirq.CircuitDiagramInfo(\n wire_symbols=('PF(0.987654)',)))\n assert (cirq.circuit_diagram_info(\n pf, args=round_to_2_prec) == cirq.CircuitDiagramInfo(\n wire_symbols=('PF(0.99)',)))\n\n\ndef test_bit_flip_channel():\n d = cirq.bit_flip(0.3)\n np.testing.assert_almost_equal(\n cirq.channel(d), (np.sqrt(1.0 - 0.3) * np.eye(2), np.sqrt(.3) * X))\n assert cirq.has_channel(d)\n\n\ndef test_bit_flip_mixture():\n d = cirq.bit_flip(0.3)\n assert_mixtures_equal(cirq.mixture(d), ((0.7, np.eye(2)), (0.3, X)))\n assert cirq.has_mixture(d)\n\n\ndef test_bit_flip_overload():\n d = cirq.bit_flip()\n d2 = cirq.bit_flip(0.3)\n assert str(d) == 'X'\n assert str(d2) == 'bit_flip(p=0.3)'\n\n\ndef test_bit_flip_channel_repr():\n cirq.testing.assert_equivalent_repr(\n cirq.BitFlipChannel(0.3))\n\n\ndef test_bit_flip_channel_str():\n assert (str(cirq.bit_flip(0.3))\n == 'bit_flip(p=0.3)')\n\n\ndef test_bit_flip_channel_eq():\n et = cirq.testing.EqualsTester()\n c = cirq.bit_flip(0.0)\n et.make_equality_group(lambda: c)\n et.add_equality_group(cirq.bit_flip(0.1))\n et.add_equality_group(cirq.bit_flip(0.4))\n et.add_equality_group(cirq.bit_flip(0.6))\n et.add_equality_group(cirq.bit_flip(0.8))\n\ndef test_bit_flip_channel_invalid_probability():\n with pytest.raises(ValueError, match='was less than 0'):\n cirq.bit_flip(-0.1)\n with pytest.raises(ValueError, match='was greater than 1'):\n cirq.bit_flip(1.1)\n\n\n\ndef test_bit_flip_channel_text_diagram():\n bf = cirq.bit_flip(0.1234567)\n assert (cirq.circuit_diagram_info(\n bf, args=round_to_6_prec) == cirq.CircuitDiagramInfo(\n wire_symbols=('BF(0.123457)',)))\n assert (cirq.circuit_diagram_info(\n bf, args=round_to_2_prec) == cirq.CircuitDiagramInfo(\n wire_symbols=('BF(0.12)',)))\n"
] |
[
[
"numpy.array"
],
[
"numpy.sqrt",
"numpy.eye",
"numpy.testing.assert_almost_equal",
"numpy.array",
"numpy.random.RandomState",
"numpy.empty"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ikanher/numpy-MNIST
|
[
"f41daa6181a04d82667ba4e3f694afcd4b291845"
] |
[
"taivasnet/taivasnet/dataloaders.py"
] |
[
"\"\"\"\nContains different dataloaders\n\"\"\"\n\n__author__ = 'Aki Rehn'\n__project__ = 'taivasnet'\n\nimport numpy as np\nimport pickle\nimport gzip\n\nclass MNISTDataLoader():\n \"\"\"\n Loads the MNIST training, validation and testing data.\n\n Data from http://deeplearning.net/data/mnist/mnist.pkl.gz--2018-07-25\n \"\"\"\n\n def __init__(self, mnist_path='../data', n_samples=None):\n \"\"\"\n Constructor\n\n mnist_path - path to mnist.pkl.gz\n n_samples - how many samples to use (default all)\n \"\"\"\n self.mnist_path = mnist_path\n self.mnist_fname = 'mnist.pkl.gz'\n self.n_samples = n_samples\n\n def _load_mnist(self):\n mnist_data_file = self.mnist_path + '/' + self.mnist_fname\n\n with gzip.open(mnist_data_file, 'rb') as f:\n ((x_train, y_train), (x_valid, y_valid), (x_test, y_test)) = pickle.load(f, encoding='latin-1')\n if self.n_samples != None:\n x_train = x_train[:self.n_samples]\n y_train = y_train[:self.n_samples]\n\n # normalize training data\n (x_train, y_train), (x_valid, y_valid) = \\\n self._normalize(((x_train, y_train), (x_valid, y_valid)))\n\n return ((x_train, y_train), (x_valid, y_valid), (x_test, y_test))\n\n def _normalize(self, data):\n \"\"\"\n Normalizes training and validation data.\n \"\"\"\n (x_train, y_train), (x_valid, y_valid) = data\n\n # calculate mean and standard deviation\n mean = x_train.mean()\n std = x_train.std()\n\n # normalize training data\n x_train = (x_train - mean)/std\n\n # normalize validation data\n x_valid = (x_valid-mean)/std\n\n return ((x_train, y_train), (x_valid, y_valid))\n\n def load_data(self):\n \"\"\"\n Loads MNIST data.\n\n Returns training, validation and test sets.\n \"\"\"\n ((x_train, y_train), (x_valid, y_valid), (x_test, y_test)) = self._load_mnist()\n return ((x_train, y_train), (x_valid, y_valid), (x_test, y_test))\n\nclass RegressionDataLoader():\n\n def load_data(self):\n \"\"\"\n Generates some data for linear regression, y = 2x\n\n Returns training, validation and test sets.\n \"\"\"\n randoms = np.random.randint(1, 1000, 100)\n x = np.array([[x] for x in randoms])\n y = np.multiply(x, 2)\n\n ((x_train, y_train), (x_valid, y_valid), (x_test, y_test)) = \\\n ((x[:60], y[:60]), (x[60:80], y[60:80]), (x[80:], y[80:]))\n\n return ((x_train, y_train), (x_valid, y_valid), (x_test, y_test))\n"
] |
[
[
"numpy.array",
"numpy.multiply",
"numpy.random.randint"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Nebula4869/real-time-object-detection-YOLOv3
|
[
"37a36a822840ffa160fc707b570ec279fbdcce34"
] |
[
"realtime_detection.py"
] |
[
"from yolo_v3 import *\nimport tensorflow as tf\nimport time\nimport cv2\n\n\nINPUT_SIZE = 416\n\n\ndef load_coco_names(file_name):\n names = {}\n with open(file_name) as f:\n for id_, name in enumerate(f):\n names[id_] = name.split('\\n')[0]\n return names\n\n\ndef detect_from_image(image_path, model, model_file):\n\n classes = load_coco_names('coco.names')\n\n tf.reset_default_graph()\n inputs = tf.placeholder(tf.float32, [None, INPUT_SIZE, INPUT_SIZE, 3])\n with tf.variable_scope('detector'):\n scores, boxes, box_classes = model(inputs, len(classes))\n\n saver = tf.train.Saver()\n with tf.Session() as sess:\n saver.restore(sess, model_file)\n\n img = cv2.imread(image_path)\n img_h, img_w, _ = img.shape\n img_resized = cv2.resize(img, (INPUT_SIZE, INPUT_SIZE))\n img_rgb = cv2.cvtColor(img_resized, cv2.COLOR_BGR2RGB)\n img_in = img_rgb.reshape((1, INPUT_SIZE, INPUT_SIZE, 3)) / 255.\n\n scores, boxes, box_classes = sess.run([scores, boxes, box_classes], feed_dict={inputs: img_in})\n\n for i in range(len(scores)):\n box_class = classes[box_classes[i]]\n\n left = int((boxes[i, 0] - boxes[i, 2] / 2) * img_w / INPUT_SIZE)\n right = int((boxes[i, 0] + boxes[i, 2] / 2) * img_w / INPUT_SIZE)\n top = int((boxes[i, 1] - boxes[i, 3] / 2) * img_h / INPUT_SIZE)\n bottom = int((boxes[i, 1] + boxes[i, 3] / 2) * img_h / INPUT_SIZE)\n\n score = scores[i]\n\n cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 2)\n cv2.rectangle(img, (left, top - 20), (right, top), (125, 125, 125), -1)\n cv2.putText(img, box_class + ': %.2f' % score, (left + 5, top - 7),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)\n\n cv2.imshow('YOLOv3 result', img)\n cv2.waitKey()\n\n\ndef detect_from_video(video_path, model, model_file):\n\n classes = load_coco_names('coco.names')\n\n tf.reset_default_graph()\n inputs = tf.placeholder(tf.float32, [None, INPUT_SIZE, INPUT_SIZE, 3])\n with tf.variable_scope('detector'):\n scores_, boxes_, box_classes_ = model(inputs, len(classes))\n\n saver = tf.train.Saver()\n with tf.Session() as sess:\n saver.restore(sess, model_file)\n\n cap = cv2.VideoCapture(video_path)\n while True:\n timer = time.time()\n _, frame = cap.read()\n\n img_h, img_w, _ = frame.shape\n img_resized = cv2.resize(frame, (INPUT_SIZE, INPUT_SIZE))\n img_rgb = cv2.cvtColor(img_resized, cv2.COLOR_BGR2RGB)\n img_in = img_rgb.reshape((1, INPUT_SIZE, INPUT_SIZE, 3)) / 255.\n scores, boxes, box_classes = sess.run([scores_, boxes_, box_classes_], feed_dict={inputs: img_in})\n\n if scores is not None:\n for i in range(len(scores)):\n\n box_class = classes[box_classes[i]]\n\n left = int((boxes[i, 0] - boxes[i, 2] / 2) * img_w / INPUT_SIZE)\n right = int((boxes[i, 0] + boxes[i, 2] / 2) * img_w / INPUT_SIZE)\n top = int((boxes[i, 1] - boxes[i, 3] / 2) * img_h / INPUT_SIZE)\n bottom = int((boxes[i, 1] + boxes[i, 3] / 2) * img_h / INPUT_SIZE)\n\n score = scores[i]\n\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)\n cv2.rectangle(frame, (left, top - 20), (right, top), (125, 125, 125), -1)\n cv2.putText(frame, box_class + ' : %.2f' % score, (left + 5, top - 7),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)\n print('Inference Time: %.4fs' % (time.time() - timer))\n cv2.imshow('YOLOv3 result', frame)\n cv2.waitKey(1)\n\n\nif __name__ == '__main__':\n # detect_from_image('test.jpg', yolo_v3, './yolov3/model.ckpt')\n detect_from_video(1, yolo_v3, './yolov3/model.ckpt')\n"
] |
[
[
"tensorflow.placeholder",
"tensorflow.reset_default_graph",
"tensorflow.variable_scope",
"tensorflow.Session",
"tensorflow.train.Saver"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
jieming2002/models-quiz8
|
[
"421dc407a10444cab4bd88c25599077acca96bdb",
"421dc407a10444cab4bd88c25599077acca96bdb",
"421dc407a10444cab4bd88c25599077acca96bdb"
] |
[
"official/resnet/resnet_run_loop.py",
"official/resnet/cifar10_test.py",
"official/utils/logging/hooks_helper_test.py"
] |
[
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Contains utility and supporting functions for ResNet.\n\n This module contains ResNet code which does not directly build layers. This\nincludes dataset management, hyperparameter and optimizer code, and argument\nparsing. Code for defining the ResNet layers can be found in resnet_model.py.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport os\n\nimport tensorflow as tf # pylint: disable=g-bad-import-order\n\nfrom official.resnet import resnet_model\nfrom official.utils.arg_parsers import parsers\nfrom official.utils.logging import hooks_helper\n\n\n################################################################################\n# Functions for input processing.\n################################################################################\ndef process_record_dataset(dataset, is_training, batch_size, shuffle_buffer,\n parse_record_fn, num_epochs=1, num_parallel_calls=1,\n examples_per_epoch=0, multi_gpu=False):\n \"\"\"Given a Dataset with raw records, return an iterator over the records.\n\n Args:\n dataset: A Dataset representing raw records\n is_training: A boolean denoting whether the input is for training.\n batch_size: The number of samples per batch.\n shuffle_buffer: The buffer size to use when shuffling records. A larger\n value results in better randomness, but smaller values reduce startup\n time and use less memory.\n parse_record_fn: A function that takes a raw record and returns the\n corresponding (image, label) pair.\n num_epochs: The number of epochs to repeat the dataset.\n num_parallel_calls: The number of records that are processed in parallel.\n This can be optimized per data set but for generally homogeneous data\n sets, should be approximately the number of available CPU cores.\n examples_per_epoch: The number of examples in the current set that\n are processed each epoch. Note that this is only used for multi-GPU mode,\n and only to handle what will eventually be handled inside of Estimator.\n multi_gpu: Whether this is run multi-GPU. Note that this is only required\n currently to handle the batch leftovers (see below), and can be removed\n when that is handled directly by Estimator.\n\n Returns:\n Dataset of (image, label) pairs ready for iteration.\n \"\"\"\n # We prefetch a batch at a time, This can help smooth out the time taken to\n # load input files as we go through shuffling and processing.\n dataset = dataset.prefetch(buffer_size=batch_size)\n if is_training:\n # Shuffle the records. Note that we shuffle before repeating to ensure\n # that the shuffling respects epoch boundaries.\n dataset = dataset.shuffle(buffer_size=shuffle_buffer)\n\n # If we are training over multiple epochs before evaluating, repeat the\n # dataset for the appropriate number of epochs.\n dataset = dataset.repeat(num_epochs)\n\n # Currently, if we are using multiple GPUs, we can't pass in uneven batches.\n # (For example, if we have 4 GPUs, the number of examples in each batch\n # must be divisible by 4.) We already ensured this for the batch_size, but\n # we have to additionally ensure that any \"leftover\" examples-- the remainder\n # examples (total examples % batch_size) that get called a batch for the very\n # last batch of an epoch-- do not raise an error when we try to split them\n # over the GPUs. This will likely be handled by Estimator during replication\n # in the future, but for now, we just drop the leftovers here.\n if multi_gpu:\n total_examples = num_epochs * examples_per_epoch\n dataset = dataset.take(batch_size * (total_examples // batch_size))\n\n # Parse the raw records into images and labels\n dataset = dataset.map(lambda value: parse_record_fn(value, is_training),\n num_parallel_calls=num_parallel_calls)\n\n dataset = dataset.batch(batch_size)\n\n # Operations between the final prefetch and the get_next call to the iterator\n # will happen synchronously during run time. We prefetch here again to\n # background all of the above processing work and keep it out of the\n # critical training path.\n dataset = dataset.prefetch(1)\n\n return dataset\n\n\ndef get_synth_input_fn(height, width, num_channels, num_classes):\n \"\"\"Returns an input function that returns a dataset with zeroes.\n\n This is useful in debugging input pipeline performance, as it removes all\n elements of file reading and image preprocessing.\n\n Args:\n height: Integer height that will be used to create a fake image tensor.\n width: Integer width that will be used to create a fake image tensor.\n num_channels: Integer depth that will be used to create a fake image tensor.\n num_classes: Number of classes that should be represented in the fake labels\n tensor\n\n Returns:\n An input_fn that can be used in place of a real one to return a dataset\n that can be used for iteration.\n \"\"\"\n def input_fn(is_training, data_dir, batch_size, *args): # pylint: disable=unused-argument\n images = tf.zeros((batch_size, height, width, num_channels), tf.float32)\n labels = tf.zeros((batch_size, num_classes), tf.int32)\n return tf.data.Dataset.from_tensors((images, labels)).repeat()\n\n return input_fn\n\n\n################################################################################\n# Functions for running training/eval/validation loops for the model.\n################################################################################\ndef learning_rate_with_decay(\n batch_size, batch_denom, num_images, boundary_epochs, decay_rates):\n \"\"\"Get a learning rate that decays step-wise as training progresses.\n\n Args:\n batch_size: the number of examples processed in each training batch.\n batch_denom: this value will be used to scale the base learning rate.\n `0.1 * batch size` is divided by this number, such that when\n batch_denom == batch_size, the initial learning rate will be 0.1.\n num_images: total number of images that will be used for training.\n boundary_epochs: list of ints representing the epochs at which we\n decay the learning rate.\n decay_rates: list of floats representing the decay rates to be used\n for scaling the learning rate. It should have one more element\n than `boundary_epochs`, and all elements should have the same type.\n\n Returns:\n Returns a function that takes a single argument - the number of batches\n trained so far (global_step)- and returns the learning rate to be used\n for training the next batch.\n \"\"\"\n initial_learning_rate = 0.1 * batch_size / batch_denom\n batches_per_epoch = num_images / batch_size\n\n # Multiply the learning rate by 0.1 at 100, 150, and 200 epochs.\n boundaries = [int(batches_per_epoch * epoch) for epoch in boundary_epochs]\n vals = [initial_learning_rate * decay for decay in decay_rates]\n\n def learning_rate_fn(global_step):\n global_step = tf.cast(global_step, tf.int32)\n return tf.train.piecewise_constant(global_step, boundaries, vals)\n\n return learning_rate_fn\n\n\ndef resnet_model_fn(features, labels, mode, model_class,\n resnet_size, weight_decay, learning_rate_fn, momentum,\n data_format, version, loss_filter_fn=None, multi_gpu=False):\n \"\"\"Shared functionality for different resnet model_fns.\n\n Initializes the ResnetModel representing the model layers\n and uses that model to build the necessary EstimatorSpecs for\n the `mode` in question. For training, this means building losses,\n the optimizer, and the train op that get passed into the EstimatorSpec.\n For evaluation and prediction, the EstimatorSpec is returned without\n a train op, but with the necessary parameters for the given mode.\n\n Args:\n features: tensor representing input images\n labels: tensor representing class labels for all input images\n mode: current estimator mode; should be one of\n `tf.estimator.ModeKeys.TRAIN`, `EVALUATE`, `PREDICT`\n model_class: a class representing a TensorFlow model that has a __call__\n function. We assume here that this is a subclass of ResnetModel.\n resnet_size: A single integer for the size of the ResNet model.\n weight_decay: weight decay loss rate used to regularize learned variables.\n learning_rate_fn: function that returns the current learning rate given\n the current global_step\n momentum: momentum term used for optimization\n data_format: Input format ('channels_last', 'channels_first', or None).\n If set to None, the format is dependent on whether a GPU is available.\n version: Integer representing which version of the ResNet network to use.\n See README for details. Valid values: [1, 2]\n loss_filter_fn: function that takes a string variable name and returns\n True if the var should be included in loss calculation, and False\n otherwise. If None, batch_normalization variables will be excluded\n from the loss.\n multi_gpu: If True, wrap the optimizer in a TowerOptimizer suitable for\n data-parallel distribution across multiple GPUs.\n\n Returns:\n EstimatorSpec parameterized according to the input params and the\n current mode.\n \"\"\"\n\n # Generate a summary node for the images\n tf.summary.image('images', features, max_outputs=6)\n\n model = model_class(resnet_size, data_format, version=version)\n logits = model(features, mode == tf.estimator.ModeKeys.TRAIN)\n\n predictions = {\n 'classes': tf.argmax(logits, axis=1),\n 'probabilities': tf.nn.softmax(logits, name='softmax_tensor')\n }\n\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n\n # Calculate loss, which includes softmax cross entropy and L2 regularization.\n cross_entropy = tf.losses.softmax_cross_entropy(\n logits=logits, onehot_labels=labels)\n\n # Create a tensor named cross_entropy for logging purposes.\n tf.identity(cross_entropy, name='cross_entropy')\n tf.summary.scalar('cross_entropy', cross_entropy)\n\n # If no loss_filter_fn is passed, assume we want the default behavior,\n # which is that batch_normalization variables are excluded from loss.\n def exclude_batch_norm(name):\n return 'batch_normalization' not in name\n loss_filter_fn = loss_filter_fn or exclude_batch_norm\n\n # Add weight decay to the loss.\n loss = cross_entropy + weight_decay * tf.add_n(\n [tf.nn.l2_loss(v) for v in tf.trainable_variables()\n if loss_filter_fn(v.name)])\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n global_step = tf.train.get_or_create_global_step()\n\n learning_rate = learning_rate_fn(global_step)\n\n # Create a tensor named learning_rate for logging purposes\n tf.identity(learning_rate, name='learning_rate')\n tf.summary.scalar('learning_rate', learning_rate)\n\n optimizer = tf.train.MomentumOptimizer(\n learning_rate=learning_rate,\n momentum=momentum)\n\n # If we are running multi-GPU, we need to wrap the optimizer.\n if multi_gpu:\n optimizer = tf.contrib.estimator.TowerOptimizer(optimizer)\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n train_op = tf.group(optimizer.minimize(loss, global_step), update_ops)\n else:\n train_op = None\n\n accuracy = tf.metrics.accuracy(\n tf.argmax(labels, axis=1), predictions['classes'])\n metrics = {'accuracy': accuracy}\n\n # Create a tensor named train_accuracy for logging purposes\n tf.identity(accuracy[1], name='train_accuracy')\n tf.summary.scalar('train_accuracy', accuracy[1])\n\n return tf.estimator.EstimatorSpec(\n mode=mode,\n predictions=predictions,\n loss=loss,\n train_op=train_op,\n eval_metric_ops=metrics)\n\n\ndef validate_batch_size_for_multi_gpu(batch_size):\n \"\"\"For multi-gpu, batch-size must be a multiple of the number of GPUs.\n\n Note that this should eventually be handled by replicate_model_fn\n directly. Multi-GPU support is currently experimental, however,\n so doing the work here until that feature is in place.\n\n Args:\n batch_size: the number of examples processed in each training batch.\n\n Raises:\n ValueError: if no GPUs are found, or selected batch_size is invalid.\n \"\"\"\n from tensorflow.python.client import device_lib # pylint: disable=g-import-not-at-top\n\n local_device_protos = device_lib.list_local_devices()\n num_gpus = sum([1 for d in local_device_protos if d.device_type == 'GPU'])\n if not num_gpus:\n raise ValueError('Multi-GPU mode was specified, but no GPUs '\n 'were found. To use CPU, run without --multi_gpu.')\n\n remainder = batch_size % num_gpus\n if remainder:\n err = ('When running with multiple GPUs, batch size '\n 'must be a multiple of the number of available GPUs. '\n 'Found {} GPUs with a batch size of {}; try --batch_size={} instead.'\n ).format(num_gpus, batch_size, batch_size - remainder)\n raise ValueError(err)\n\n\ndef resnet_main(flags, model_function, input_function):\n \"\"\"Shared main loop for ResNet Models.\"\"\"\n\n # Using the Winograd non-fused algorithms provides a small performance boost.\n os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'\n\n if flags.multi_gpu:\n validate_batch_size_for_multi_gpu(flags.batch_size)\n\n # There are two steps required if using multi-GPU: (1) wrap the model_fn,\n # and (2) wrap the optimizer. The first happens here, and (2) happens\n # in the model_fn itself when the optimizer is defined.\n model_function = tf.contrib.estimator.replicate_model_fn(\n model_function,\n loss_reduction=tf.losses.Reduction.MEAN)\n\n # Create session config based on values of inter_op_parallelism_threads and\n # intra_op_parallelism_threads. Note that we default to having\n # allow_soft_placement = True, which is required for multi-GPU and not\n # harmful for other modes.\n session_config = tf.ConfigProto(\n inter_op_parallelism_threads=flags.inter_op_parallelism_threads,\n intra_op_parallelism_threads=flags.intra_op_parallelism_threads,\n allow_soft_placement=True)\n\n # Set up a RunConfig to save checkpoint and set session config.\n run_config = tf.estimator.RunConfig().replace(save_checkpoints_secs=1e9,\n session_config=session_config)\n classifier = tf.estimator.Estimator(\n model_fn=model_function, model_dir=flags.model_dir, config=run_config,\n params={\n 'resnet_size': flags.resnet_size,\n 'data_format': flags.data_format,\n 'batch_size': flags.batch_size,\n 'multi_gpu': flags.multi_gpu,\n 'version': flags.version,\n })\n\n for _ in range(flags.train_epochs // flags.epochs_between_evals):\n train_hooks = hooks_helper.get_train_hooks(\n flags.hooks, batch_size=flags.batch_size)\n\n print('Starting a training cycle.')\n\n def input_fn_train():\n return input_function(True, flags.data_dir, flags.batch_size,\n flags.epochs_between_evals,\n flags.num_parallel_calls, flags.multi_gpu)\n\n classifier.train(input_fn=input_fn_train, hooks=train_hooks,\n max_steps=flags.max_train_steps)\n\n print('Starting to evaluate.')\n # Evaluate the model and print results\n def input_fn_eval():\n return input_function(False, flags.data_dir, flags.batch_size,\n 1, flags.num_parallel_calls, flags.multi_gpu)\n\n # flags.max_train_steps is generally associated with testing and profiling.\n # As a result it is frequently called with synthetic data, which will\n # iterate forever. Passing steps=flags.max_train_steps allows the eval\n # (which is generally unimportant in those circumstances) to terminate.\n # Note that eval will run for max_train_steps each loop, regardless of the\n # global_step count.\n eval_results = classifier.evaluate(input_fn=input_fn_eval,\n steps=flags.max_train_steps)\n print(eval_results)\n\n\nclass ResnetArgParser(argparse.ArgumentParser):\n \"\"\"Arguments for configuring and running a Resnet Model.\n \"\"\"\n\n def __init__(self, resnet_size_choices=None):\n super(ResnetArgParser, self).__init__(parents=[\n parsers.BaseParser(),\n parsers.PerformanceParser(),\n parsers.ImageModelParser(),\n ])\n\n self.add_argument(\n '--version', '-v', type=int, choices=[1, 2],\n default=resnet_model.DEFAULT_VERSION,\n help='Version of ResNet. (1 or 2) See README.md for details.'\n )\n\n self.add_argument(\n '--resnet_size', '-rs', type=int, default=50,\n choices=resnet_size_choices,\n help='[default: %(default)s] The size of the ResNet model to use.',\n metavar='<RS>' if resnet_size_choices is None else None\n )\n",
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tempfile import mkstemp\n\nimport numpy as np\nimport tensorflow as tf # pylint: disable=g-bad-import-order\n\nfrom official.resnet import cifar10_main\nfrom official.utils.testing import integration\n\ntf.logging.set_verbosity(tf.logging.ERROR)\n\n_BATCH_SIZE = 128\n_HEIGHT = 32\n_WIDTH = 32\n_NUM_CHANNELS = 3\n\n\nclass BaseTest(tf.test.TestCase):\n \"\"\"Tests for the Cifar10 version of Resnet.\n \"\"\"\n\n def tearDown(self):\n super(BaseTest, self).tearDown()\n tf.gfile.DeleteRecursively(self.get_temp_dir())\n\n def test_dataset_input_fn(self):\n fake_data = bytearray()\n fake_data.append(7)\n for i in range(_NUM_CHANNELS):\n for _ in range(_HEIGHT * _WIDTH):\n fake_data.append(i)\n\n _, filename = mkstemp(dir=self.get_temp_dir())\n data_file = open(filename, 'wb')\n data_file.write(fake_data)\n data_file.close()\n\n fake_dataset = tf.data.FixedLengthRecordDataset(\n filename, cifar10_main._RECORD_BYTES) # pylint: disable=protected-access\n fake_dataset = fake_dataset.map(\n lambda val: cifar10_main.parse_record(val, False))\n image, label = fake_dataset.make_one_shot_iterator().get_next()\n\n self.assertAllEqual(label.shape, (10,))\n self.assertAllEqual(image.shape, (_HEIGHT, _WIDTH, _NUM_CHANNELS))\n\n with self.test_session() as sess:\n image, label = sess.run([image, label])\n\n self.assertAllEqual(label, np.array([int(i == 7) for i in range(10)]))\n\n for row in image:\n for pixel in row:\n self.assertAllClose(pixel, np.array([-1.225, 0., 1.225]), rtol=1e-3)\n\n def cifar10_model_fn_helper(self, mode, version, multi_gpu=False):\n input_fn = cifar10_main.get_synth_input_fn()\n dataset = input_fn(True, '', _BATCH_SIZE)\n iterator = dataset.make_one_shot_iterator()\n features, labels = iterator.get_next()\n spec = cifar10_main.cifar10_model_fn(\n features, labels, mode, {\n 'resnet_size': 32,\n 'data_format': 'channels_last',\n 'batch_size': _BATCH_SIZE,\n 'version': version,\n 'multi_gpu': multi_gpu\n })\n\n predictions = spec.predictions\n self.assertAllEqual(predictions['probabilities'].shape,\n (_BATCH_SIZE, 10))\n self.assertEqual(predictions['probabilities'].dtype, tf.float32)\n self.assertAllEqual(predictions['classes'].shape, (_BATCH_SIZE,))\n self.assertEqual(predictions['classes'].dtype, tf.int64)\n\n if mode != tf.estimator.ModeKeys.PREDICT:\n loss = spec.loss\n self.assertAllEqual(loss.shape, ())\n self.assertEqual(loss.dtype, tf.float32)\n\n if mode == tf.estimator.ModeKeys.EVAL:\n eval_metric_ops = spec.eval_metric_ops\n self.assertAllEqual(eval_metric_ops['accuracy'][0].shape, ())\n self.assertAllEqual(eval_metric_ops['accuracy'][1].shape, ())\n self.assertEqual(eval_metric_ops['accuracy'][0].dtype, tf.float32)\n self.assertEqual(eval_metric_ops['accuracy'][1].dtype, tf.float32)\n\n def test_cifar10_model_fn_train_mode_v1(self):\n self.cifar10_model_fn_helper(tf.estimator.ModeKeys.TRAIN, version=1)\n\n def test_cifar10_model_fn_trainmode__v2(self):\n self.cifar10_model_fn_helper(tf.estimator.ModeKeys.TRAIN, version=2)\n\n def test_cifar10_model_fn_train_mode_multi_gpu_v1(self):\n self.cifar10_model_fn_helper(tf.estimator.ModeKeys.TRAIN, version=1,\n multi_gpu=True)\n\n def test_cifar10_model_fn_train_mode_multi_gpu_v2(self):\n self.cifar10_model_fn_helper(tf.estimator.ModeKeys.TRAIN, version=2,\n multi_gpu=True)\n\n def test_cifar10_model_fn_eval_mode_v1(self):\n self.cifar10_model_fn_helper(tf.estimator.ModeKeys.EVAL, version=1)\n\n def test_cifar10_model_fn_eval_mode_v2(self):\n self.cifar10_model_fn_helper(tf.estimator.ModeKeys.EVAL, version=2)\n\n def test_cifar10_model_fn_predict_mode_v1(self):\n self.cifar10_model_fn_helper(tf.estimator.ModeKeys.PREDICT, version=1)\n\n def test_cifar10_model_fn_predict_mode_v2(self):\n self.cifar10_model_fn_helper(tf.estimator.ModeKeys.PREDICT, version=2)\n\n def test_cifar10model_shape(self):\n batch_size = 135\n num_classes = 246\n\n for version in (1, 2):\n model = cifar10_main.Cifar10Model(\n 32, data_format='channels_last', num_classes=num_classes,\n version=version)\n fake_input = tf.random_uniform(\n [batch_size, _HEIGHT, _WIDTH, _NUM_CHANNELS])\n output = model(fake_input, training=True)\n\n self.assertAllEqual(output.shape, (batch_size, num_classes))\n\n def test_cifar10_end_to_end_synthetic_v1(self):\n integration.run_synthetic(\n main=cifar10_main.main, tmp_root=self.get_temp_dir(),\n extra_flags=['-v', '1']\n )\n\n def test_cifar10_end_to_end_synthetic_v2(self):\n integration.run_synthetic(\n main=cifar10_main.main, tmp_root=self.get_temp_dir(),\n extra_flags=['-v', '2']\n )\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Tests for hooks_helper.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport unittest\n\nimport tensorflow as tf # pylint: disable=g-bad-import-order\n\nfrom official.utils.logging import hooks_helper\n\n\nclass BaseTest(unittest.TestCase):\n\n def test_raise_in_non_list_names(self):\n with self.assertRaises(ValueError):\n hooks_helper.get_train_hooks(\n 'LoggingTensorHook, ProfilerHook', batch_size=256)\n\n def test_raise_in_invalid_names(self):\n invalid_names = ['StepCounterHook', 'StopAtStepHook']\n with self.assertRaises(ValueError):\n hooks_helper.get_train_hooks(invalid_names, batch_size=256)\n\n def validate_train_hook_name(self,\n test_hook_name,\n expected_hook_name,\n **kwargs):\n returned_hook = hooks_helper.get_train_hooks([test_hook_name], **kwargs)\n self.assertEqual(len(returned_hook), 1)\n self.assertIsInstance(returned_hook[0], tf.train.SessionRunHook)\n self.assertEqual(returned_hook[0].__class__.__name__.lower(),\n expected_hook_name)\n\n def test_get_train_hooks_logging_tensor_hook(self):\n test_hook_name = 'LoggingTensorHook'\n self.validate_train_hook_name(test_hook_name, 'loggingtensorhook')\n\n def test_get_train_hooks_profiler_hook(self):\n test_hook_name = 'ProfilerHook'\n self.validate_train_hook_name(test_hook_name, 'profilerhook')\n\n def test_get_train_hooks_examples_per_second_hook(self):\n test_hook_name = 'ExamplesPerSecondHook'\n self.validate_train_hook_name(test_hook_name, 'examplespersecondhook')\n\nif __name__ == '__main__':\n tf.test.main()\n"
] |
[
[
"tensorflow.python.client.device_lib.list_local_devices",
"tensorflow.zeros",
"tensorflow.cast",
"tensorflow.contrib.estimator.TowerOptimizer",
"tensorflow.nn.l2_loss",
"tensorflow.estimator.RunConfig",
"tensorflow.summary.scalar",
"tensorflow.get_collection",
"tensorflow.summary.image",
"tensorflow.train.get_or_create_global_step",
"tensorflow.losses.softmax_cross_entropy",
"tensorflow.ConfigProto",
"tensorflow.train.piecewise_constant",
"tensorflow.train.MomentumOptimizer",
"tensorflow.trainable_variables",
"tensorflow.argmax",
"tensorflow.data.Dataset.from_tensors",
"tensorflow.estimator.Estimator",
"tensorflow.identity",
"tensorflow.nn.softmax",
"tensorflow.contrib.estimator.replicate_model_fn",
"tensorflow.estimator.EstimatorSpec"
],
[
"tensorflow.test.main",
"tensorflow.data.FixedLengthRecordDataset",
"tensorflow.logging.set_verbosity",
"numpy.array",
"tensorflow.random_uniform"
],
[
"tensorflow.test.main"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ArgonneCPAC/diffstar
|
[
"4d15a5b2fd2faa86311c543a151fee73a14bd7f1"
] |
[
"scripts/load_smah_data.py"
] |
[
"\"\"\"\n\"\"\"\nimport numpy as np\nimport os\nimport h5py\nimport warnings\nfrom diffstar.utils import _get_dt_array\n\n\nTASSO = \"/Users/aphearin/work/DATA/diffmah_data\"\nBEBOP = \"/lcrc/project/halotools/diffmah_data\"\nLAPTOP = \"/Users/alarcon/Documents/diffmah_data\"\n\nH_BPL = 0.678\nH_TNG = 0.6774\nH_MDPL = H_BPL\n\n\ndef load_fit_mah(filename, data_drn=BEBOP):\n \"\"\" Load the best fit diffmah parameter data.\n\n Parameters\n ----------\n filename : string\n Name of the h5 file where the diffmah best fit parameters are stored.\n data_drn : string\n Filepath where the Diffstar best-fit parameters are stored.\n\n Returns\n -------\n mah_fit_params: ndarray of shape (n_gal, 4)\n Best fit parameters for each halo:\n (logtc, k, early_index, late_index)\n logmp: ndarray of shape (n_gal, )\n Base-10 logarithm of the present day peak halo mass.\n \"\"\"\n fitting_data = dict()\n\n fn = os.path.join(data_drn, filename)\n with h5py.File(fn, \"r\") as hdf:\n for key in hdf.keys():\n if key == \"halo_id\":\n fitting_data[key] = hdf[key][...]\n else:\n fitting_data[\"fit_\" + key] = hdf[key][...]\n\n mah_fit_params = np.array(\n [\n fitting_data[\"fit_mah_logtc\"],\n fitting_data[\"fit_mah_k\"],\n fitting_data[\"fit_early_index\"],\n fitting_data[\"fit_late_index\"],\n ]\n ).T\n logmp = fitting_data[\"fit_logmp_fit\"]\n\n return mah_fit_params, logmp\n\n\ndef load_bolshoi_data(gal_type, data_drn=BEBOP):\n \"\"\"Load the stellar mass histories from UniverseMachine simulation\n applied to the Bolshoi-Planck (BPL) simulation.\n\n The loaded stellar mass data has units of Msun assuming the h = H_BPL\n from the cosmology of the underlying simulation.\n\n The output stellar mass data has units of Msun/h, or units of\n Mstar[h=H_BPL] using the h value of the simulation.\n\n H_BPL is defined at the top of the module.\n\n Parameters\n ----------\n gal_type : string\n Name of the galaxy type of the file being loaded. Options are\n 'cens': central galaxies\n 'sats': satellite galaxies\n 'orphans': orphan galaxies\n data_drn : string\n Filepath where the Diffstar best-fit parameters are stored.\n\n Returns\n -------\n halo_ids: ndarray of shape (n_gal, )\n IDs of the halos in the file.\n log_smahs: ndarray of shape (n_gal, n_times)\n Cumulative stellar mass history in units of Msun assuming h=1.\n sfrh: ndarray of shape (n_gal, n_times)\n Star formation rate history in units of Msun/yr assuming h=1.\n bpl_t : ndarray of shape (n_times, )\n Cosmic time of each simulated snapshot in Gyr\n dt : ndarray of shape (n_times, )\n Cosmic time steps between each simulated snapshot in Gyr\n \"\"\"\n basename = \"bpl_diffmah_{}.npy\".format(gal_type)\n fn = os.path.join(data_drn, basename)\n halos = np.load(fn)\n bpl_t = np.load(os.path.join(data_drn, \"bpl_cosmic_time.npy\"))\n\n halo_ids = halos[\"halo_id\"]\n dt = _get_dt_array(bpl_t)\n sfrh = halos[\"sfr_history_main_prog\"]\n sm_cumsum = np.cumsum(sfrh * dt, axis=1) * 1e9\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n log_smahs = np.where(sm_cumsum == 0, 0, np.log10(sm_cumsum))\n\n return halo_ids, log_smahs, sfrh, bpl_t, dt\n\n\ndef load_bolshoi_small_data(gal_type, data_drn=BEBOP):\n \"\"\"Load a smaller subsample of the stellar mass histories from the\n UniverseMachine simulation applied to the Bolshoi-Planck (BPL) simulation.\n\n The loaded stellar mass data has units of Msun assuming the h = H_BPL\n from the cosmology of the underlying simulation.\n\n The output stellar mass data has units of Msun/h, or units of\n Mstar[h=H_BPL] using the h value of the simulation.\n\n H_BPL is defined at the top of the module.\n\n Parameters\n ----------\n gal_type : string\n Name of the galaxy type of the file being loaded. Options are\n 'cens': central galaxies\n 'sats': satellite galaxies\n 'orphans': orphan galaxies\n data_drn : string\n Filepath where the Diffstar best-fit parameters are stored.\n\n Returns\n -------\n halo_ids: ndarray of shape (n_gal, )\n IDs of the halos in the file.\n log_smahs: ndarray of shape (n_gal, n_times)\n Cumulative stellar mass history in units of Msun assuming h=1.\n sfrh: ndarray of shape (n_gal, n_times)\n Star formation rate history in units of Msun/yr assuming h=1.\n bpl_t : ndarray of shape (n_times, )\n Cosmic time of each simulated snapshot in Gyr\n dt : ndarray of shape (n_times, )\n Cosmic time steps between each simulated snapshot in Gyr\n \"\"\"\n basename = \"um_histories_subsample_dr1_bpl_{}_diffmah.npy\".format(gal_type)\n fn = os.path.join(data_drn, basename)\n halos = np.load(fn)\n bpl_t = np.load(os.path.join(data_drn, \"bpl_cosmic_time.npy\"))\n\n halo_ids = halos[\"halo_id\"]\n dt = _get_dt_array(bpl_t)\n sfrh = halos[\"sfr_history_main_prog\"]\n sm_cumsum = np.cumsum(sfrh * dt, axis=1) * 1e9\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n log_smahs = np.where(sm_cumsum == 0, 0, np.log10(sm_cumsum))\n\n return halo_ids, log_smahs, sfrh, bpl_t, dt\n\n\ndef load_tng_data(gal_type, data_drn=BEBOP):\n \"\"\"Load the stellar mass histories from the IllustrisTNG simulation.\n\n The loaded stellar mass data has units of Msun assuming the h = H_TNG\n from the cosmology of the underlying simulation.\n\n The output stellar mass data has units of Msun/h, or units of\n Mstar[h=H_TNG] using the h value of the simulation.\n\n H_TNG is defined at the top of the module.\n\n Parameters\n ----------\n gal_type : string\n Name of the galaxy type of the file being loaded. Options are\n 'cens': central galaxies\n 'sats': satellite galaxies\n 'orphans': orphan galaxies\n data_drn : string\n Filepath where the Diffstar best-fit parameters are stored.\n\n Returns\n -------\n halo_ids: ndarray of shape (n_gal, )\n IDs of the halos in the file.\n log_smahs: ndarray of shape (n_gal, n_times)\n Cumulative stellar mass history in units of Msun assuming h=1.\n sfrh: ndarray of shape (n_gal, n_times)\n Star formation rate history in units of Msun/yr assuming h=1.\n tng_t : ndarray of shape (n_times, )\n Cosmic time of each simulated snapshot in Gyr\n dt : ndarray of shape (n_times, )\n Cosmic time steps between each simulated snapshot in Gyr\n \"\"\"\n basename = \"tng_diffmah.npy\"\n fn = os.path.join(data_drn, basename)\n halos = np.load(fn)\n tng_t = np.load(os.path.join(data_drn, \"tng_cosmic_time.npy\"))\n\n halo_ids = np.arange(len(halos[\"mpeak\"])).astype(\"i8\")\n dt = _get_dt_array(tng_t)\n sfrh = halos[\"sfh\"]\n sm_cumsum = np.cumsum(sfrh * dt, axis=1) * 1e9\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n log_smahs = np.where(sm_cumsum == 0, 0, np.log10(sm_cumsum))\n\n return halo_ids, log_smahs, sfrh, tng_t, dt\n\n\ndef load_tng_small_data(gal_type, data_drn=BEBOP):\n \"\"\"Load a smaller subsample of the stellar mass histories from\n the IllustrisTNG simulation.\n\n The loaded stellar mass data has units of Msun assuming the h = H_TNG\n from the cosmology of the underlying simulation.\n\n The output stellar mass data has units of Msun/h, or units of\n Mstar[h=H_TNG] using the h value of the simulation.\n\n H_TNG is defined at the top of the module.\n\n Parameters\n ----------\n gal_type : string\n Name of the galaxy type of the file being loaded. Options are\n 'cens': central galaxies\n 'sats': satellite galaxies\n 'orphans': orphan galaxies\n data_drn : string\n Filepath where the Diffstar best-fit parameters are stored.\n\n Returns\n -------\n halo_ids: ndarray of shape (n_gal, )\n IDs of the halos in the file.\n log_smahs: ndarray of shape (n_gal, n_times)\n Cumulative stellar mass history in units of Msun assuming h=1.\n sfrh: ndarray of shape (n_gal, n_times)\n Star formation rate history in units of Msun/yr assuming h=1.\n tng_t : ndarray of shape (n_times, )\n Cosmic time of each simulated snapshot in Gyr\n dt : ndarray of shape (n_times, )\n Cosmic time steps between each simulated snapshot in Gyr\n \"\"\"\n basename = \"tng_small.npy\"\n fn = os.path.join(data_drn, basename)\n halos = np.load(fn)\n tng_t = np.load(os.path.join(data_drn, \"tng_cosmic_time.npy\"))\n\n halo_ids = np.arange(len(halos[\"mpeak\"])).astype(\"i8\")\n dt = _get_dt_array(tng_t)\n sfrh = halos[\"sfh\"]\n sm_cumsum = np.cumsum(sfrh * dt, axis=1) * 1e9\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n log_smahs = np.where(sm_cumsum == 0, 0, np.log10(sm_cumsum))\n\n return halo_ids, log_smahs, sfrh, tng_t, dt\n\n\ndef load_mdpl_data(gal_type, data_drn=BEBOP):\n \"\"\"Load the stellar mass histories from the UniverseMachine simulation\n applied to the MultiDark Planck 2 (MDPL2) simulation.\n\n The loaded stellar mass data has units of Msun assuming the h = H_MDPL\n from the cosmology of the underlying simulation.\n\n The output stellar mass data has units of Msun/h, or units of\n Mstar[h=H_MDPL] using the h value of the simulation.\n\n H_MDPL is defined at the top of the module.\n\n Parameters\n ----------\n gal_type : string\n Name of the galaxy type of the file being loaded. Options are\n 'cens': central galaxies\n 'sats': satellite galaxies\n 'orphans': orphan galaxies\n data_drn : string\n Filepath where the Diffstar best-fit parameters are stored.\n\n Returns\n -------\n halo_ids: ndarray of shape (n_gal, )\n IDs of the halos in the file.\n log_smahs: ndarray of shape (n_gal, n_times)\n Cumulative stellar mass history in units of Msun assuming h=1.\n sfrh: ndarray of shape (n_gal, n_times)\n Star formation rate history in units of Msun/yr assuming h=1.\n mdpl_t : ndarray of shape (n_times, )\n Cosmic time of each simulated snapshot in Gyr\n dt : ndarray of shape (n_times, )\n Cosmic time steps between each simulated snapshot in Gyr\n \"\"\"\n basename = \"mdpl2_diffmah_{}.npy\".format(gal_type)\n fn = os.path.join(data_drn, basename)\n halos = np.load(fn)\n mdpl_t = np.load(os.path.join(data_drn, \"mdpl2_cosmic_time.npy\"))\n\n halo_ids = halos[\"halo_id\"]\n dt = _get_dt_array(mdpl_t)\n sfrh = halos[\"sfr_history_main_prog\"]\n sm_cumsum = np.cumsum(sfrh * dt, axis=1) * 1e9\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n log_smahs = np.where(sm_cumsum == 0, 0, np.log10(sm_cumsum))\n\n return halo_ids, log_smahs, sfrh, mdpl_t, dt\n\n\ndef load_mdpl_small_data(gal_type, data_drn=BEBOP):\n \"\"\"Load a smaller subsample of the stellar mass histories from the\n UniverseMachine simulation applied to the\n MultiDark Planck 2 (MDPL2) simulation.\n\n The loaded stellar mass data has units of Msun assuming the h = H_MDPL\n from the cosmology of the underlying simulation.\n\n The output stellar mass data has units of Msun/h, or units of\n Mstar[h=H_MDPL] using the h value of the simulation.\n\n H_MDPL is defined at the top of the module.\n\n Parameters\n ----------\n gal_type : string\n Name of the galaxy type of the file being loaded. Options are\n 'cens': central galaxies\n 'sats': satellite galaxies\n 'orphans': orphan galaxies\n data_drn : string\n Filepath where the Diffstar best-fit parameters are stored.\n\n Returns\n -------\n halo_ids: ndarray of shape (n_gal, )\n IDs of the halos in the file.\n log_smahs: ndarray of shape (n_gal, n_times)\n Cumulative stellar mass history in units of Msun assuming h=1.\n sfrh: ndarray of shape (n_gal, n_times)\n Star formation rate history in units of Msun/yr assuming h=1.\n mdpl_t : ndarray of shape (n_times, )\n Cosmic time of each simulated snapshot in Gyr\n dt : ndarray of shape (n_times, )\n Cosmic time steps between each simulated snapshot in Gyr\n \"\"\"\n basename = \"um_histories_dr1_mdpl2_small_{}.npy\".format(gal_type)\n fn = os.path.join(data_drn, basename)\n halos = np.load(fn)\n mdpl_t = np.load(os.path.join(data_drn, \"mdpl2_cosmic_time.npy\"))\n\n halo_ids = halos[\"halo_id\"]\n dt = _get_dt_array(mdpl_t)\n sfrh = halos[\"sfr_history_main_prog\"]\n sm_cumsum = np.cumsum(sfrh * dt, axis=1) * 1e9\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n log_smahs = np.where(sm_cumsum == 0, 0, np.log10(sm_cumsum))\n\n return halo_ids, log_smahs, sfrh, mdpl_t, dt\n"
] |
[
[
"numpy.load",
"numpy.log10",
"numpy.array",
"numpy.cumsum"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kshen6/byol-pytorch
|
[
"49e303adf89ed3d990025262fd30226a00a98d45"
] |
[
"examples/lightning/train.py"
] |
[
"import os\nimport argparse\nimport multiprocessing\nfrom pathlib import Path\nfrom PIL import Image\n\nimport torch\nfrom torchvision import models, transforms\nfrom torch.utils.data import DataLoader, Dataset\n\nfrom byol_pytorch import BYOL\nimport pytorch_lightning as pl\n\n# test model, a resnet 50\n\nresnet = models.resnet50(pretrained=True)\n\n# arguments\n\nparser = argparse.ArgumentParser(description='byol-lightning-test')\n\nparser.add_argument('--image_folder', type=str, required = True,\n help='path to your folder of images for self-supervised learning')\n\nargs = parser.parse_args()\n\n# constants\n\nBATCH_SIZE = 32\nEPOCHS = 1000\nLR = 3e-4\nNUM_GPUS = 2\nIMAGE_SIZE = 256\nIMAGE_EXTS = ['.jpg', '.png', '.jpeg']\nNUM_WORKERS = multiprocessing.cpu_count()\n\n# pytorch lightning module\n\nclass SelfSupervisedLearner(pl.LightningModule):\n def __init__(self, net, **kwargs):\n super().__init__()\n self.learner = BYOL(net, **kwargs)\n\n def forward(self, images):\n return self.learner(images)\n\n def training_step(self, images, _):\n loss = self.forward(images)\n return {'loss': loss}\n\n def configure_optimizers(self):\n return torch.optim.Adam(self.parameters(), lr=LR)\n\n def on_before_zero_grad(self, _):\n self.learner.update_moving_average()\n\n# images dataset\n\ndef expand_greyscale(t):\n return t.expand(3, -1, -1)\n\nclass ImagesDataset(Dataset):\n def __init__(self, folder, image_size):\n super().__init__()\n self.folder = folder\n self.paths = []\n\n for path in Path(f'{folder}').glob('**/*'):\n _, ext = os.path.splitext(path)\n if ext.lower() in IMAGE_EXTS:\n self.paths.append(path)\n\n print(f'{len(self.paths)} images found')\n\n self.transform = transforms.Compose([\n transforms.Resize(image_size),\n transforms.CenterCrop(image_size),\n transforms.ToTensor(),\n transforms.Lambda(expand_greyscale)\n ])\n\n def __len__(self):\n return len(self.paths)\n\n def __getitem__(self, index):\n path = self.paths[index]\n img = Image.open(path)\n img = img.convert('RGB')\n return self.transform(img)\n\n# main\n\nif __name__ == '__main__':\n ds = ImagesDataset(args.image_folder, IMAGE_SIZE)\n train_loader = DataLoader(ds, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS, shuffle=True)\n\n model = SelfSupervisedLearner(\n resnet,\n image_size = IMAGE_SIZE,\n hidden_layer = 'avgpool',\n projection_size = 256,\n projection_hidden_size = 4096,\n moving_average_decay = 0.99\n )\n\n trainer = pl.Trainer(gpus=NUM_GPUS, max_epochs=EPOCHS)\n trainer.fit(model, train_loader)\n"
] |
[
[
"torch.utils.data.DataLoader"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
arjunsinghrathore/routing-transformer
|
[
"999c611dddf4aa8d45ad3e5063406b24cd450757"
] |
[
"routing_transformer/reversible.py"
] |
[
"import torch\nimport torch.nn as nn\nfrom operator import itemgetter\nfrom torch.autograd.function import Function\nfrom torch.utils.checkpoint import get_device_states, set_device_states\n\n# for routing arguments into the functions of the reversible layer\n\ndef route_args(router, args, depth):\n routed_args = [(dict(), dict()) for _ in range(depth)]\n matched_keys = [key for key in args.keys() if key in router]\n\n for key in matched_keys:\n val = args[key]\n for depth, ((f_args, g_args), routes) in enumerate(zip(routed_args, router[key])):\n new_f_args, new_g_args = map(lambda route: ({key: val} if route else {}), routes)\n routed_args[depth] = ({**f_args, **new_f_args}, {**g_args, **new_g_args})\n return routed_args\n\ndef layer_drop(layers, prob):\n to_drop = torch.empty(len(layers)).uniform_(0, 1) < prob\n blocks = [block for block, drop in zip(layers, to_drop) if not drop]\n blocks = layers[:1] if len(blocks) == 0 else blocks\n return blocks\n\ndef cast_return(ret, requires_grad = True):\n if type(ret) is not tuple:\n loss = torch.tensor(0., device=ret.device, dtype=ret.dtype, requires_grad=requires_grad)\n return (ret, loss)\n return ret\n\n# following example for saving and setting rng here https://pytorch.org/docs/stable/_modules/torch/utils/checkpoint.html\nclass Deterministic(nn.Module):\n def __init__(self, net):\n super().__init__()\n self.net = net\n self.cpu_state = None\n self.cuda_in_fwd = None\n self.gpu_devices = None\n self.gpu_states = None\n\n def record_rng(self, *args):\n self.cpu_state = torch.get_rng_state()\n if torch.cuda._initialized:\n self.cuda_in_fwd = True\n self.gpu_devices, self.gpu_states = get_device_states(*args)\n\n def forward(self, *args, record_rng = False, set_rng = False, **kwargs):\n if record_rng:\n self.record_rng(*args)\n\n if not set_rng:\n return self.net(*args, **kwargs)\n\n rng_devices = []\n if self.cuda_in_fwd:\n rng_devices = self.gpu_devices\n\n with torch.random.fork_rng(devices=rng_devices, enabled=True):\n torch.set_rng_state(self.cpu_state)\n if self.cuda_in_fwd:\n set_device_states(self.gpu_devices, self.gpu_states)\n return self.net(*args, **kwargs)\n\n# heavily inspired by https://github.com/RobinBruegger/RevTorch/blob/master/revtorch/revtorch.py\n# once multi-GPU is confirmed working, refactor and send PR back to source\nclass ReversibleBlock(nn.Module):\n def __init__(self, f, g):\n super().__init__()\n self.f = Deterministic(f)\n self.g = Deterministic(g)\n\n def forward(self, x, f_args = {}, g_args = {}):\n x1, x2 = torch.chunk(x, 2, dim=2)\n y1, y2 = None, None\n\n f_args['_reverse'] = g_args['_reverse'] = False\n\n with torch.no_grad():\n f_out, f_loss = cast_return(self.f(x2, record_rng=self.training, **f_args), requires_grad = False)\n y1 = x1 + f_out\n\n g_out, g_loss = cast_return(self.g(y1, record_rng=self.training, **g_args), requires_grad = False)\n y2 = x2 + g_out\n\n return torch.cat([y1, y2], dim=2), f_loss, g_loss\n\n def backward_pass(self, y, dy, dl_f, dl_g, f_args = {}, g_args = {}):\n y1, y2 = torch.chunk(y, 2, dim=2)\n del y\n\n dy1, dy2 = torch.chunk(dy, 2, dim=2)\n del dy\n\n f_args['_reverse'] = g_args['_reverse'] = True\n\n with torch.enable_grad():\n y1.requires_grad = True\n gy1, g_loss = cast_return(self.g(y1, set_rng=True, **g_args))\n torch.autograd.backward((gy1, g_loss), (dy2, dl_g))\n\n with torch.no_grad():\n x2 = y2 - gy1\n del y2, gy1\n\n dx1 = dy1 + y1.grad\n del dy1\n y1.grad = None\n\n with torch.enable_grad():\n x2.requires_grad = True\n fx2, f_loss = cast_return(self.f(x2, set_rng=True, **f_args))\n torch.autograd.backward((fx2, f_loss), (dx1, dl_f), retain_graph=True)\n\n with torch.no_grad():\n x1 = y1 - fx2\n del y1, fx2\n\n dx2 = dy2 + x2.grad\n del dy2\n x2.grad = None\n\n x = torch.cat([x1, x2.detach()], dim=2)\n dx = torch.cat([dx1, dx2], dim=2)\n\n return x, dx\n\nclass _ReversibleFunction(Function):\n @staticmethod\n def forward(ctx, x, blocks, args):\n ctx.args = args\n\n f_aux_loss = []\n g_aux_loss = []\n\n for block, kwarg in zip(blocks, args):\n x, f_loss, g_loss = block(x, **kwarg)\n f_aux_loss.append(f_loss)\n g_aux_loss.append(g_loss)\n\n ctx.y = x.detach()\n ctx.blocks = blocks\n return x, torch.stack(f_aux_loss), torch.stack(g_aux_loss)\n\n @staticmethod\n def backward(ctx, dy, dl_f, dl_g):\n y = ctx.y\n args = ctx.args\n for block, kwargs, ind in zip(ctx.blocks[::-1], args[::-1], range(len(ctx.blocks))[::-1]):\n y, dy = block.backward_pass(y, dy, dl_f[ind], dl_g[ind], **kwargs)\n return dy, None, None\n\nclass SequentialSequence(nn.Module):\n def __init__(self, layers, args_route = {}, layer_dropout = 0.):\n super().__init__()\n assert all(len(route) == len(layers) for route in args_route.values()), 'each argument route map must have the same depth as the number of sequential layers'\n self.layers = layers\n self.args_route = args_route\n self.layer_dropout = layer_dropout\n\n def forward(self, x, **kwargs):\n args = route_args(self.args_route, kwargs, len(self.layers))\n layers_and_args = list(zip(self.layers, args))\n\n if self.training and self.layer_dropout > 0:\n layers_and_args = layer_drop(layers_and_args, self.layer_dropout)\n\n aux_loss = torch.zeros(1, device=x.device, dtype=x.dtype)\n\n for (f, g), (f_args, g_args) in layers_and_args:\n res, loss = cast_return(f(x, **f_args))\n aux_loss += loss\n x = x + res\n\n res, loss = cast_return(g(x, **g_args))\n aux_loss += loss\n x = x + res\n return x, aux_loss\n\nclass ReversibleSequence(nn.Module):\n def __init__(self, blocks, args_route = {}, layer_dropout = 0.):\n super().__init__()\n self.args_route = args_route\n self.layer_dropout = layer_dropout\n self.blocks = nn.ModuleList([ReversibleBlock(f, g) for f, g in blocks])\n\n def forward(self, x, **kwargs):\n x = torch.cat([x, x], dim=-1)\n\n blocks = self.blocks\n args = route_args(self.args_route, kwargs, len(blocks))\n args = list(map(lambda x: {'f_args': x[0], 'g_args': x[1]}, args))\n\n layers_and_args = list(zip(blocks, args))\n\n if self.training and self.layer_dropout > 0:\n layers_and_args = layer_drop(layers_and_args, self.layer_dropout)\n blocks, args = map(lambda ind: list(map(itemgetter(ind), layers_and_args)), (0, 1))\n\n out, f_loss, g_loss = _ReversibleFunction.apply(x, blocks, args)\n out = torch.stack(out.chunk(2, dim=-1)).mean(dim=0)\n aux_loss = f_loss.sum() + g_loss.sum()\n return out, aux_loss\n"
] |
[
[
"torch.set_rng_state",
"torch.enable_grad",
"torch.zeros",
"torch.cat",
"torch.random.fork_rng",
"torch.autograd.backward",
"torch.utils.checkpoint.set_device_states",
"torch.tensor",
"torch.get_rng_state",
"torch.utils.checkpoint.get_device_states",
"torch.no_grad",
"torch.chunk",
"torch.stack"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AlexRogalskiy/DevArtifacts
|
[
"931aabb8cbf27656151c54856eb2ea7d1153203a"
] |
[
"master/Impractical_Python_Projects-master/Impractical_Python_Projects-master/Chapter_16/benford.py"
] |
[
"\"\"\"Check conformance of numerical data to Benford's Law.\"\"\"\nimport sys\nimport math\nfrom collections import defaultdict\nimport matplotlib.pyplot as plt\n\n# Benford's Law percentages for leading digits 1-9\nBENFORD = [30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 5.1, 4.6]\n\ndef load_data(filename):\n \"\"\"Open a text file & return a list of strings.\"\"\"\n with open(filename) as f:\n return f.read().strip().split('\\n')\n \ndef count_first_digits(data_list):\n \"\"\"Count 1st digits in list of numbers; return counts & frequency.\"\"\"\n first_digits = defaultdict(int) # default value of int is 0\n for sample in data_list:\n if sample == '':\n continue\n try:\n int(sample)\n except ValueError as e:\n print(e, file=sys.stderr)\n print(\"Samples must be integers. Exiting.\", file=sys.stderr)\n sys.exit(1)\n first_digits[sample[0]] += 1 \n data_count = [v for (k, v) in sorted(first_digits.items())]\n total_count = sum(data_count)\n data_pct = [(i / total_count) * 100 for i in data_count]\n return data_count, data_pct, total_count\n\ndef get_expected_counts(total_count):\n \"\"\"Return list of expected Benford's Law counts for total sample count.\"\"\"\n return [round(p * total_count / 100) for p in BENFORD]\n\ndef chi_square_test(data_count, expected_counts):\n \"\"\"Return boolean on chi-square test (8 degrees of freedom & P-val=0.05).\"\"\"\n chi_square_stat = 0 # chi square test statistic\n for data, expected in zip(data_count, expected_counts):\n chi_square = math.pow(data - expected, 2)\n chi_square_stat += chi_square / expected\n print(\"\\nChi-squared Test Statistic = {:.3f}\".format(chi_square_stat))\n print(\"Critical value at a P-value of 0.05 is 15.51.\") \n return chi_square_stat < 15.51\n\ndef bar_chart(data_pct):\n \"\"\"Make bar chart of observed vs expected 1st digit frequency in percent.\"\"\"\n fig, ax = plt.subplots()\n\n index = [i + 1 for i in range(len(data_pct))] # 1st digits for x-axis\n\n # text for labels, title and ticks\n fig.canvas.set_window_title('Percentage First Digits')\n ax.set_title('Data vs. Benford Values', fontsize=15)\n ax.set_ylabel('Frequency (%)', fontsize=16)\n ax.set_xticks(index)\n ax.set_xticklabels(index, fontsize=14)\n\n # build bars \n rects = ax.bar(index, data_pct, width=0.95, color='black', label='Data')\n\n # attach a text label above each bar displaying its height\n for rect in rects:\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width()/2, height,\n '{:0.1f}'.format(height), ha='center', va='bottom', \n fontsize=13)\n\n # plot Benford values as red dots\n ax.scatter(index, BENFORD, s=150, c='red', zorder=2, label='Benford')\n\n # Hide the right and top spines & add legend\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.legend(prop={'size':15}, frameon=False)\n \n plt.show()\n\ndef main():\n \"\"\"Call functions and print stats.\"\"\"\n # load data\n while True:\n filename = input(\"\\nName of file with COUNT data: \")\n try:\n data_list = load_data(filename)\n except IOError as e:\n print(\"{}. Try again.\".format(e), file=sys.stderr)\n else:\n break\n data_count, data_pct, total_count = count_first_digits(data_list)\n expected_counts = get_expected_counts(total_count)\n print(\"\\nobserved counts = {}\".format(data_count))\n print(\"expected counts = {}\".format(expected_counts), \"\\n\")\n \n print(\"First Digit Probabilities:\")\n for i in range(1, 10):\n print(\"{}: observed: {:.3f} expected: {:.3f}\".\n format(i, data_pct[i - 1] / 100, BENFORD[i - 1] / 100))\n\n if chi_square_test(data_count, expected_counts):\n print(\"Observed distribution matches expected distribution.\")\n else:\n print(\"Observed distribution does not match expected.\", file=sys.stderr) \n\n bar_chart(data_pct) \n \nif __name__ == '__main__':\n main()\n"
] |
[
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
NERSC/atlas_dl_benchmark
|
[
"290ed4a5ec19384e1af31b06d15e335bd3df9b27"
] |
[
"slurm_tf_helper/setup_clusters.py"
] |
[
"#*** License Agreement ***\n#\n#High Energy Physics Deep Learning Convolutional Neural Network Benchmark (HEPCNNB) Copyright (c) 2017, The Regents of the University of California, \n#through Lawrence Berkeley National Laboratory (subject to receipt of any required approvals from the U.S. Dept. of Energy). All rights reserved.\n#\n#Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n#(1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n#(2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer \n#in the documentation and/or other materials provided with the distribution.\n#(3) Neither the name of the University of California, Lawrence Berkeley National Laboratory, U.S. Dept. of Energy nor the names \n#of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, \n#BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \n#COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT \n#LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF \n#LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, \n#EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#You are under no obligation whatsoever to provide any bug fixes, patches, or upgrades to the features, \n#functionality or performance of the source code (\"Enhancements\") to anyone; however, \n#if you choose to make your Enhancements available either publicly, or directly to Lawrence Berkeley National Laboratory, \n#without imposing a separate written license agreement for such Enhancements, then you hereby grant the following license: a non-exclusive, \n#royalty-free perpetual license to install, use, modify, prepare derivative works, incorporate into other computer software, \n#distribute, and sublicense such enhancements or derivative works thereof, in binary and source code form.\n#---------------------------------------------------------------\n\nimport tensorflow as tf\n\nimport sys\n\nimport os\n\n\ndef setup_slurm_cluster(num_ps=1):\n all_nodes = get_all_nodes()\n\n port = get_allowed_port()\n \n hostlist = [ (\"%s:%i\" % (node, port)) for node in all_nodes ] \n ps_hosts, worker_hosts = get_parameter_server_and_worker_hosts(hostlist, num_ps=num_ps)\n\n proc_id, num_procs = get_slurm_proc_variables()\n \n num_tasks = num_procs - num_ps\n \n job_name = get_job_name(proc_id, num_ps)\n \n task_index = get_task_index(proc_id, job_name, num_ps)\n \n cluster_spec = make_cluster_spec(worker_hosts, ps_hosts)\n\n server = make_server(cluster_spec, job_name, task_index)\n \n return cluster_spec, server, task_index, num_tasks, job_name\n \n\ndef make_server(cluster_spec, job_name, task_index):\n server = tf.train.Server(cluster_spec,\n job_name=job_name,\n task_index=task_index)\n return server\n \n \ndef make_cluster_spec(worker_hosts, ps_hosts):\n if ps_hosts:\n cluster_spec = tf.train.ClusterSpec({\n \"worker\": worker_hosts,\n \"ps\": ps_hosts})\n else:\n cluster_spec = tf.train.ClusterSpec({\n \"worker\": worker_hosts})\n return cluster_spec\n \n \ndef get_task_index(proc_id, job_name, num_ps):\n \n if job_name == \"ps\":\n task_index = proc_id\n elif job_name == \"worker\":\n #expects a task_index for workers that starts at 0\n task_index = proc_id - num_ps\n return task_index\n \n \ndef get_slurm_proc_variables():\n proc_id = int( os.environ['SLURM_PROCID'] )\n num_procs = int( os.environ['SLURM_NPROCS'] )\n return proc_id, num_procs\n \ndef get_job_name(proc_id, num_ps):\n if proc_id < num_ps:\n job_name = \"ps\"\n else:\n job_name = \"worker\"\n return job_name\n \n \ndef get_parameter_server_and_worker_hosts(hostlist, num_ps=1):\n \"\"\"assumes num_ps nodes used for parameter server (one ps per node)\n and rest of nodes used for workers\"\"\"\n ps_hosts = hostlist[:num_ps]\n worker_hosts = hostlist[num_ps:]\n return ps_hosts, worker_hosts\n \ndef get_allowed_port():\n allowed_port = 22222\n return allowed_port\n\n\ndef get_all_nodes():\n nodelist=expand_nodelist( os.environ['SLURM_NODELIST'])\n return nodelist\n \n\ndef expand_nodelist(node_string):\n if '[' in node_string:\n pref, suff = node_string.split('[')\n\n suff = suff. split(']')[0].split(',')\n nodes =[]\n for s in suff:\n if '-' not in s:\n nodes.append(\"%s%s\" % (pref, s))\n continue\n beg,end = s.split('-')\n num_len=len(beg)\n for id in range(int(beg),int(end) + 1):\n j= \"%s%0\" + str(num_len) + \"d\"\n nodes.append(j % (pref, id))\n else:\n nodes=[node_string]\n\n return nodes\n\nif __name__ == \"__main__\":\n cluster, server, task_index, num_tasks, job_name = setup_slurm_cluster(num_ps=1)\n"
] |
[
[
"tensorflow.train.Server",
"tensorflow.train.ClusterSpec"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
flyslowly/PIEPredict
|
[
"f6d6770858fc50290665fbcc363b7e474712328f"
] |
[
"extract_dataset.py"
] |
[
"\"\"\"\nThe code implementation of the paper:\n\nA. Rasouli, I. Kotseruba, T. Kunic, and J. Tsotsos, \"PIE: A Large-Scale Dataset and Models for Pedestrian Intention Estimation and\nTrajectory Prediction\", ICCV 2019.\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\"\"\"\n\nimport os\nimport sys\nfrom typing_extensions import Self\n\nfrom pie_intent import PIEIntent\nfrom pie_predict import PIEPredict\n\nfrom pie_data import PIE\n\nimport keras.backend as K\nimport tensorflow as tf\n\nfrom prettytable import PrettyTable\n\ndim_ordering = K.image_dim_ordering()\n\ndef print_dict(self, dic):\n \"\"\"\n Prints a dictionary, one key-value pair per line\n :param dic: Dictionary\n \"\"\"\n for k, v in dic.items():\n print('%s: %s' % (str(k), str(v)))\n\n\ndef train_predict(dataset='pie',\n train_test=2, \n intent_model_path='data/pie/intention/context_loc_pretrained'):\n data_opts = {'fstride': 1,\n 'sample_type': 'all',\n 'height_rng': [0, float('inf')],\n 'squarify_ratio': 0,\n 'data_split_type': 'default', # kfold, random, default\n 'seq_type': 'trajectory',\n 'min_track_size': 61,\n 'random_params': {'ratios': None,\n 'val_data': True,\n 'regen_data': True},\n 'kfold_params': {'num_folds': 5, 'fold': 1}}\n\n t = PIEPredict()\n pie_path = os.environ.copy()['PIE_PATH']\n\n if dataset == 'pie':\n imdb = PIE(data_path=pie_path)\n\n traj_model_opts = {'normalize_bbox': True,\n 'track_overlap': 0.5,\n 'observe_length': 15,\n 'predict_length': 45,\n 'enc_input_type': ['bbox'],\n 'dec_input_type': ['intention_prob', 'obd_speed'],\n 'prediction_type': ['bbox'] \n }\n\n speed_model_opts = {'normalize_bbox': True,\n 'track_overlap': 0.5,\n 'observe_length': 15,\n 'predict_length': 45,\n 'enc_input_type': ['obd_speed'], \n 'dec_input_type': [],\n 'prediction_type': ['obd_speed'] \n }\n\n traj_model_path = 'data/pie/trajectory/loc_intent_speed_pretrained'\n speed_model_path = 'data/pie/speed/speed_pretrained'\n\n if train_test < 2:\n beh_seq_val = imdb.generate_data_trajectory_sequence('val', **data_opts)\n beh_seq_train = imdb.generate_data_trajectory_sequence('train', **data_opts)\n # traj_model_path = t.train(beh_seq_train, beh_seq_val, **traj_model_opts)\n # speed_model_path = t.train(beh_seq_train, beh_seq_val, **speed_model_opts)\n\n if train_test > 0:\n beh_seq_test = imdb.generate_data_trajectory_sequence('test', **data_opts)\n\n # perf_final = t.test_final(beh_seq_test,\n # traj_model_path=traj_model_path, \n # speed_model_path=speed_model_path,\n # intent_model_path=intent_model_path)\n\n # t = PrettyTable(['MSE', 'C_MSE'])\n # t.title = 'Trajectory prediction model (loc + PIE_intent + PIE_speed)'\n # t.add_row([perf_final['mse-45'], perf_final['c-mse-45']])\n \n # print(t)\n \n # print(beh_seq_train['center'])\n # print_dict(beh_seq_train)\n # print_dict(beh_seq_val)\n # print_dict(beh_seq_test)\n\n#train models with data up to critical point\n#only for PIE\n#train_test = 0 (train only), 1 (train-test), 2 (test only)\ndef train_intent(train_test=1):\n\n data_opts = {'fstride': 1,\n 'sample_type': 'all', \n 'height_rng': [0, float('inf')],\n 'squarify_ratio': 0,\n 'data_split_type': 'default', # kfold, random, default\n 'seq_type': 'intention', # crossing , intention\n 'min_track_size': 0, # discard tracks that are shorter\n 'max_size_observe': 15, # number of observation frames\n 'max_size_predict': 5, # number of prediction frames\n 'seq_overlap_rate': 0.5, # how much consecutive sequences overlap\n 'balance': True, # balance the training and testing samples\n 'crop_type': 'context', # crop 2x size of bbox around the pedestrian\n 'crop_mode': 'pad_resize', # pad with 0s and resize to VGG input\n 'encoder_input_type': [],\n 'decoder_input_type': ['bbox'],\n 'output_type': ['intention_binary']\n }\n\n\n t = PIEIntent(num_hidden_units=128,\n regularizer_val=0.001,\n lstm_dropout=0.4,\n lstm_recurrent_dropout=0.2,\n convlstm_num_filters=64,\n convlstm_kernel_size=2)\n\n saved_files_path = ''\n\n imdb = PIE(data_path=os.environ.copy()['PIE_PATH'])\n\n pretrained_model_path = 'data/pie/intention/context_loc_pretrained'\n\n if train_test < 2: # Train\n beh_seq_val = imdb.generate_data_trajectory_sequence('val', **data_opts)\n beh_seq_val = imdb.balance_samples_count(beh_seq_val, label_type='intention_binary')\n\n beh_seq_train = imdb.generate_data_trajectory_sequence('train', **data_opts)\n beh_seq_train = imdb.balance_samples_count(beh_seq_train, label_type='intention_binary')\n\n saved_files_path = t.train(data_train=beh_seq_train,\n data_val=beh_seq_val,\n epochs=400,\n loss=['binary_crossentropy'],\n metrics=['accuracy'],\n batch_size=128,\n optimizer_type='rmsprop',\n data_opts=data_opts)\n\n print(data_opts['seq_overlap_rate'])\n\n if train_test > 0: # Test\n if saved_files_path == '':\n saved_files_path = pretrained_model_path\n beh_seq_test = imdb.generate_data_trajectory_sequence('test', **data_opts)\n acc, f1 = t.test_chunk(beh_seq_test, data_opts, saved_files_path, False)\n \n t = PrettyTable(['Acc', 'F1'])\n t.title = 'Intention model (local_context + bbox)'\n t.add_row([acc, f1])\n \n print(t)\n\n K.clear_session()\n tf.reset_default_graph()\n return saved_files_path\n\ndef main(dataset='pie', train_test=2):\n\n # intent_model_path = train_intent(train_test=train_test)\n # train_predict(dataset=dataset, train_test=train_test, intent_model_path=intent_model_path)\n train_predict(dataset=dataset, train_test=train_test)\n\n\nif __name__ == '__main__':\n try:\n train_test = int(sys.argv[1])\n main(train_test=train_test)\n except ValueError:\n raise ValueError('Usage: python train_test.py <train_test>\\n'\n 'train_test: 0 - train only, 1 - train and test, 2 - test only\\n')\n"
] |
[
[
"tensorflow.reset_default_graph"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
vene/seqlearn
|
[
"e429de64499be5e763b5d10a8e305002a50fa746"
] |
[
"seqlearn/datasets/tests/test_conll.py"
] |
[
"from nose.tools import assert_equal, assert_less, assert_true\nfrom numpy.testing import assert_array_equal\n\nfrom StringIO import StringIO\n\nimport scipy.sparse as sp\n\nfrom seqlearn.datasets import load_conll\n\n\nTEST_FILE = \"\"\"\n\nThe Det\ncat N\nis V\non Pre\nthe Det\n mat N\n. Punc\n\n\nReally Adv\n. Punc\n\n\"\"\"\n\n\ndef features(words, i):\n assert_true(isinstance(i, int))\n assert_less(-1, i)\n assert_less(i, len(words))\n\n yield words[i].lower()\n\n\ndef test_load_conll():\n n_nonempty = sum(1 for ln in TEST_FILE.splitlines() if ln.strip())\n\n X, y, lengths = load_conll(StringIO(TEST_FILE), features)\n assert_true(sp.isspmatrix(X))\n assert_equal(X.shape[0], n_nonempty)\n assert_equal(list(y),\n [\"Det\", \"N\", \"V\", \"Pre\", \"Det\", \"N\", \"Punc\",\n \"Adv\", \"Punc\"])\n assert_array_equal(lengths, [7, 2])\n\n\nTEST_SPLIT = \"\"\"\n foo ham O\n bar spam B\n baz eggs I\n\n\"\"\"\n\n\ndef features_split(words, i):\n assert_true(isinstance(i, int))\n assert_less(-1, i)\n assert_less(i, len(words))\n\n x1, x2 = words[i]\n yield x1\n yield x2\n\n\ndef test_load_conll_split():\n X, y, _ = load_conll(StringIO(TEST_SPLIT), features_split, split=True)\n assert_equal(list(y), list(\"OBI\"))\n"
] |
[
[
"numpy.testing.assert_array_equal",
"scipy.sparse.isspmatrix"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
Jimmy2027/MoPoE-MIMIC
|
[
"d167719b0dc7ba002b7421eb82a83e47d2437795",
"d167719b0dc7ba002b7421eb82a83e47d2437795"
] |
[
"mimic/evaluation/divergence_measures/mm_div.py",
"mimic/networks/ConvNetworksTextMimic.py"
] |
[
"import torch\n\nfrom mimic.evaluation.divergence_measures.kl_div import calc_entropy_gauss\nfrom mimic.evaluation.divergence_measures.kl_div import calc_kl_divergence\nfrom mimic.evaluation.divergence_measures.kl_div import calc_kl_divergence_lb_gauss_mixture\nfrom mimic.evaluation.divergence_measures.kl_div import calc_kl_divergence_ub_gauss_mixture\nfrom mimic.utils.utils import reweight_weights\n\n\ndef poe(mu, logvar, eps=1e-8):\n var = torch.exp(logvar) + eps\n # precision of i-th Gaussian expert at point x\n T = 1. / var\n pd_mu = torch.sum(mu * T, dim=0) / torch.sum(T, dim=0)\n pd_var = 1. / torch.sum(T, dim=0)\n pd_logvar = torch.log(pd_var)\n return pd_mu, pd_logvar\n\n\ndef alpha_poe(alpha, mu, logvar, eps=1e-8):\n var = torch.exp(logvar) + eps\n # precision of i-th Gaussian expert at point x\n if var.dim() == 3:\n alpha_expanded = alpha.unsqueeze(-1).unsqueeze(-1)\n elif var.dim() == 4:\n alpha_expanded = alpha.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)\n\n T = 1 / var\n pd_var = 1. / torch.sum(alpha_expanded * T, dim=0)\n pd_mu = pd_var * torch.sum(alpha_expanded * mu * T, dim=0)\n pd_logvar = torch.log(pd_var)\n return pd_mu, pd_logvar\n\n\ndef calc_alphaJSD_modalities_mixture(m1_mu, m1_logvar, m2_mu, m2_logvar, flags):\n klds = torch.zeros(2)\n entropies_mixture = torch.zeros(2)\n w_modalities = torch.Tensor(flags.alpha_modalities[1:])\n if flags.cuda:\n w_modalities = w_modalities.cuda()\n klds = klds.cuda()\n entropies_mixture = entropies_mixture.cuda()\n w_modalities = reweight_weights(w_modalities)\n\n mus = [m1_mu, m2_mu]\n logvars = [m1_logvar, m2_logvar]\n for k in range(len(mus)):\n ent = calc_entropy_gauss(flags, logvars[k], norm_value=flags.batch_size)\n # print('entropy: ' + str(ent))\n # print('lb: ' )\n kld_lb = calc_kl_divergence_lb_gauss_mixture(flags, k, mus[k], logvars[k], mus, logvars,\n norm_value=flags.batch_size)\n print('kld_lb: ' + str(kld_lb))\n # print('ub: ')\n kld_ub = calc_kl_divergence_ub_gauss_mixture(flags, k, mus[k], logvars[k], mus, logvars, ent,\n norm_value=flags.batch_size)\n print('kld_ub: ' + str(kld_ub))\n # kld_mean = (kld_lb+kld_ub)/2\n entropies_mixture[k] = ent.clone()\n klds[k] = 0.5 * (kld_lb + kld_ub)\n # klds[k] = kld_ub\n summed_klds = (w_modalities * klds).sum()\n # print('summed klds: ' + str(summed_klds))\n return summed_klds, klds, entropies_mixture\n\n\ndef calc_alphaJSD_modalities(flags, mus, logvars, weights, normalization=None):\n num_mods = mus.shape[0]\n num_samples = mus.shape[1]\n alpha_mu, alpha_logvar = alpha_poe(weights, mus, logvars)\n if normalization is not None:\n klds = torch.zeros(num_mods)\n else:\n klds = torch.zeros(num_mods, num_samples)\n klds = klds.to(flags.device)\n\n for k in range(0, num_mods):\n kld = calc_kl_divergence(mus[k, :, :], logvars[k, :, :], alpha_mu,\n alpha_logvar, norm_value=normalization)\n if normalization is not None:\n klds[k] = kld\n else:\n klds[k, :] = kld\n if normalization is None:\n weights = weights.unsqueeze(1).repeat(1, num_samples)\n group_div = (weights * klds).sum(dim=0)\n return group_div, klds, [alpha_mu, alpha_logvar]\n\n\ndef calc_group_divergence_moe(flags, mus, logvars, weights, normalization=None):\n num_mods = mus.shape[0]\n # num_samples is the batch size\n num_samples = mus.shape[1]\n if normalization is not None:\n klds = torch.zeros(num_mods)\n else:\n klds = torch.zeros(num_mods, num_samples)\n klds = klds.to(flags.device)\n weights = weights.to(flags.device)\n for k in range(num_mods):\n kld_ind = calc_kl_divergence(mus[k, :, :], logvars[k, :, :],\n norm_value=normalization)\n if normalization is not None:\n klds[k] = kld_ind\n else:\n klds[k, :] = kld_ind\n if normalization is None:\n weights = weights.unsqueeze(1).repeat(1, num_samples)\n group_div = (weights * klds).sum(dim=0)\n return group_div, klds\n\n\ndef calc_group_divergence_poe(flags, mus, logvars, norm=None):\n num_mods = mus.shape[0]\n poe_mu, poe_logvar = poe(mus, logvars)\n kld_poe = calc_kl_divergence(poe_mu, poe_logvar, norm_value=norm)\n klds = torch.zeros(num_mods).to(flags.device)\n for k in range(num_mods):\n kld_ind = calc_kl_divergence(mus[k, :, :], logvars[k, :, :],\n norm_value=norm)\n klds[k] = kld_ind\n return kld_poe, klds, [poe_mu, poe_logvar]\n\n\ndef calc_modality_divergence(m1_mu, m1_logvar, m2_mu, m2_logvar, flags):\n if flags.modality_poe:\n return calc_kl_divergence(\n m1_mu, m1_logvar, m2_mu, m2_logvar, norm_value=flags.batch_size\n ).sum()\n\n uniform_mu = torch.zeros(m1_mu.shape)\n uniform_logvar = torch.zeros(m1_logvar.shape)\n klds = torch.zeros(3, 3)\n klds_modonly = torch.zeros(2, 2)\n if flags.cuda:\n klds = klds.cuda()\n klds_modonly = klds_modonly.cuda()\n uniform_mu = uniform_mu.cuda()\n uniform_logvar = uniform_logvar.cuda()\n\n mus = [uniform_mu, m1_mu, m2_mu]\n logvars = [uniform_logvar, m1_logvar, m2_logvar]\n for i in range(1, len(mus)): # CAREFUL: index starts from one, not zero\n for j in range(len(mus)):\n kld = calc_kl_divergence(mus[i], logvars[i], mus[j], logvars[j], norm_value=flags.batch_size)\n klds[i, j] = kld\n if i >= 1 and j >= 1:\n klds_modonly[i - 1, j - 1] = kld\n klds = klds.sum() / (len(mus) * (len(mus) - 1))\n klds_modonly = klds_modonly.sum() / ((len(mus) - 1) * (len(mus) - 1))\n return [klds, klds_modonly]\n",
"import torch\nimport torch.nn as nn\n\nfrom mimic.networks.FeatureCompressor import LinearFeatureCompressor\nfrom mimic.networks.char_encoding import DataGeneratorText as DataGeneratorText_CharEnc\nfrom mimic.networks.char_encoding import FeatureExtractorText as FeatureExtractorText_CharEnc\nfrom mimic.networks.word_encoding import DataGeneratorText as DataGeneratorText_WordEnc\nfrom mimic.networks.word_encoding.mmvae_text_enc import FeatureExtractorText as FeatureExtractorText_WordEnc\n\n\nclass EncoderText(nn.Module):\n def __init__(self, flags, style_dim):\n super(EncoderText, self).__init__()\n self.args = flags\n if flags.text_encoding == 'char':\n self.feature_extractor = FeatureExtractorText_CharEnc(flags)\n elif flags.text_encoding == 'word':\n self.feature_extractor = FeatureExtractorText_WordEnc(flags)\n self.feature_compressor = LinearFeatureCompressor(5 * flags.DIM_text,\n style_dim,\n flags.class_dim)\n\n def forward(self, x_text):\n # d_model must be divisible by nhead\n # text_in = nn.functional.one_hot(x_text.to(torch.int64), num_classes=self.args.vocab_size)\n # encoder_layer = nn.TransformerEncoderLayer(d_model=x_text.shape[-1], nhead=8)\n # transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=8)\n # h_text = transformer_encoder(text_in)\n # todo is this better?\n h_text = self.feature_extractor(x_text)\n if self.feature_compressor.style_mu and self.feature_compressor.style_logvar:\n mu_style, logvar_style, mu_content, logvar_content = self.feature_compressor(h_text)\n return mu_content, logvar_content, mu_style, logvar_style\n else:\n mu_content, logvar_content = self.feature_compressor(h_text)\n return mu_content, logvar_content\n\n\nclass DecoderText(nn.Module):\n def __init__(self, flags, style_dim):\n super(DecoderText, self).__init__()\n self.flags = flags\n self.feature_generator = nn.Linear(style_dim + flags.class_dim,\n 5 * flags.DIM_text, bias=True)\n if flags.text_encoding == 'char':\n self.text_generator = DataGeneratorText_CharEnc(flags)\n elif flags.text_encoding == 'word':\n self.text_generator = DataGeneratorText_WordEnc(flags)\n # self.text_generator = Dec(flags)\n\n def forward(self, z_style, z_content):\n if self.flags.factorized_representation:\n z = torch.cat((z_style, z_content), dim=1).squeeze(-1)\n # z.shape = [100, 64]\n else:\n z = z_content\n text_feat_hat = self.feature_generator(z)\n text_feat_hat = text_feat_hat.unsqueeze(-1)\n # predict in batches to spare GPU memory\n if text_feat_hat.shape[0] > self.flags.batch_size:\n dl = torch.utils.data.DataLoader(text_feat_hat, batch_size=self.flags.batch_size)\n text_hat = torch.Tensor().to(self.flags.device)\n for batch in dl:\n text_hat = torch.cat(tensors=(text_hat, self.text_generator(batch)))\n else:\n text_hat = self.text_generator(text_feat_hat)\n text_hat = text_hat.transpose(-2, -1)\n return [text_hat]\n"
] |
[
[
"torch.Tensor",
"torch.zeros",
"torch.sum",
"torch.exp",
"torch.log"
],
[
"torch.nn.Linear",
"torch.utils.data.DataLoader",
"torch.Tensor",
"torch.cat"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
hbrunie/tvm_ttile
|
[
"35de098ef637b501b96a8a4455d8deae052e0268"
] |
[
"python/tvm/relay/frontend/tensorflow2.py"
] |
[
"# 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# pylint: disable=invalid-name, unused-argument, too-many-lines, len-as-condition, broad-except\n\"\"\"Tensorflow2.x graph to relay converter.\n\nIf model is constructed using tf2.x API, then use this converter:\n from tvm.relay.frontend.tensorflow2 import from_tensorflow\nOtherwise use the tf1.x converter:\n from tvm.relay.frontend.tensorflow import from_tensorflow\n\n\"\"\"\n\nimport numpy as np\nfrom tensorflow.python.framework import function_def_to_graph, tensor_util, dtypes\n\nimport tvm\nfrom tvm.relay.transform import InferType\nfrom tvm.relay.prelude import Prelude\nfrom tvm.ir import IRModule\nfrom .. import expr as _expr\nfrom .. import analysis\nfrom .. import function as _function\nfrom ..loops import while_loop as _while_loop\nfrom .common import infer_type as _infer_type\n\nfrom .tensorflow_ops import _convert_map as _convert_map_common\nfrom .tensorflow_ops import _need_prelude_for_shape_inference\n\nfrom ..ty import Any\n\n__all__ = [\"from_tensorflow\"]\n\n\ndef _infer_type_with_prelude(val, prelude):\n body = _infer_type(val, prelude.mod)\n return body.checked_type\n\n\ndef set_span(sym, node_name):\n \"\"\"set span of symbol\"\"\"\n\n span = tvm.relay.Span(tvm.relay.SourceName(node_name), 0, 0, 0, 0)\n if isinstance(sym, _expr.Call):\n sym = _expr.Call(sym.op, sym.args, sym.attrs, sym.type_args, span)\n elif isinstance(sym, _expr.TupleWrapper):\n tuple_value = sym.tuple_value\n if isinstance(tuple_value, _expr.Call):\n tuple_value = _expr.Call(\n tuple_value.op, tuple_value.args, tuple_value.attrs, tuple_value.type_args, span\n )\n sym = _expr.TupleWrapper(tuple_value, sym.size)\n return sym\n\n\ndef convert_const_node(node, shape):\n \"\"\"convert tf const node into relay const or var\"\"\"\n\n # get the value of the constant\n tensor_value = node.attr[\"value\"].tensor\n np_array = tensor_util.MakeNdarray(tensor_value)\n\n if np_array.dtype == np.dtype(object):\n if shape and node.name in shape:\n var_shape = shape[node.name]\n else:\n var_shape = tensor_util.TensorShapeProtoToList(tensor_value.tensor_shape)\n param = None\n sym = [_expr.var(node.name, shape=var_shape, dtype=\"uint8\")]\n return sym, param\n\n if len(np_array.shape) == 0:\n param = None\n sym = [tvm.relay.const(np_array, np_array.dtype)]\n else:\n param = tvm.nd.array(np_array)\n sym = [_expr.var(node.name, shape=param.shape, dtype=param.dtype)]\n\n return sym, param\n\n\ndef get_attr(buf):\n \"\"\"convert value of a node attribute. node attribute is part of a node in a graph.\n\n Parameters\n ----------\n buf: attrvalue protobuf. <class 'tensorflow.core.framework.attr_value_pb2.AttrValue'>\n\n Returns\n -------\n The value of the attr, as a Python object.\n\n Raises:\n -------\n ValueError: If this op does not have an attr with the given `name`.\n \"\"\"\n\n fields = [\"s\", \"i\", \"f\", \"b\", \"type\", \"shape\", \"tensor\", \"func\"]\n\n ret = []\n\n if not buf.WhichOneof(\"value\"):\n return ret\n\n if buf.HasField(\"list\"):\n for f in fields:\n if getattr(buf.list, f):\n if f == \"type\":\n ret += [dtypes.as_dtype(x) for x in list(getattr(buf.list, f))]\n else:\n ret += list(getattr(buf.list, f))\n else:\n for f in fields:\n if buf.HasField(f):\n if f == \"type\":\n ret = dtypes.as_dtype(getattr(buf, f))\n else:\n ret = getattr(buf, f)\n return ret\n\n\ndef parse_attr(attr_proto):\n \"\"\"Convert node attributes (a serialized map of key-value pairs) in a node to a dict\n\n Parameters\n ----------\n attr_proto: <class 'google.protobuf.pyext._message.MessageMapContainer'>\n\n Returns\n -------\n Dict {string: python object}\n\n \"\"\"\n attrs = {}\n for key, value in attr_proto.items():\n attrs[key] = get_attr(value)\n\n return attrs\n\n\ndef convert_placeholder(shape, node, in_type=None):\n \"\"\"convert tf placeholder into relay var.\n\n Example\n --------\n a tf placeholder with name \"x\" is converted to [Var(x, ty=TensorType([], float32))]\n \"\"\"\n\n if shape and node.name in shape:\n input_shape = list(shape[node.name])\n else:\n input_shape = tensor_util.TensorShapeProtoToList(node.attr[\"shape\"].shape)\n for idx, dim in enumerate(input_shape):\n if dim < 0:\n input_shape[idx] = Any()\n attr = parse_attr(node.attr)\n if in_type is not None:\n sym = [_expr.var(node.name, type_annotation=in_type)]\n else:\n sym = [_expr.var(node.name, shape=input_shape, dtype=attr[\"dtype\"].name)]\n return input_shape, sym\n\n\nclass RelayModule:\n \"\"\"states related to the entire relay module (multiple functions)\n after converted from tf graphdef\"\"\"\n\n def __init__(self):\n self.mod = IRModule({})\n self.params = {}\n self.prelude = Prelude(self.mod)\n\n\nclass GraphProto:\n \"\"\"Capturing states when converting a tf graph to a single relay function.\"\"\"\n\n def __init__(self, module):\n self._module = module\n self._prelude = self._module.prelude\n self._params = {}\n self._nodes = {}\n self._input_shapes = {}\n self._output_shapes = {}\n self._tf_node_map = {}\n self._gdef_lib = {}\n\n def from_tensorflow(\n self, graph, layout=\"NHWC\", shape=None, outputs=None, input_types=None, gdef_lib=None\n ):\n \"\"\"Wrapper to _get_relay_func which converts Tensorflow graph to Relay function\n which is used as main function for the Relay module\n \"\"\"\n if input_types is None:\n input_types = {}\n\n if gdef_lib is None:\n gdef_lib = {}\n\n self._gdef_lib = gdef_lib\n func = self._get_relay_func(\n graph, layout=layout, shape=shape, outputs=outputs, input_types=input_types\n )\n return func, self._params\n\n def _get_relay_func(self, graph, layout=\"NHWC\", shape=None, outputs=None, input_types=None):\n if input_types is None:\n input_types = {}\n\n self._layout = layout\n for node in graph.node:\n name = node.name\n self._tf_node_map[name] = node\n if node.op == \"Placeholder\":\n in_type = None\n if node.name in input_types:\n in_type = input_types[node.name]\n self._input_shapes[name], self._nodes[name] = convert_placeholder(\n shape, node, in_type\n )\n elif node.op == \"Const\":\n sym, param = convert_const_node(node, shape)\n self._nodes[node.name] = sym\n if param:\n self._params[node.name] = param\n for node in graph.node:\n self._backtrack_construct(graph, node.name)\n\n return self._func(graph, outputs)\n\n def _func(self, graph, outputs):\n out = []\n if outputs is None:\n last_node = graph.node[-1]\n op = self._nodes[last_node.name.split(\":\")[0]]\n if last_node.op == \"Exit\":\n out = [op[0].tuple_value]\n else:\n out = op\n else:\n for out_name in outputs:\n if \":\" in out_name:\n out_name = out_name.split(\":\")\n out_name, out_num = out_name[0], out_name[-1]\n out_num = int(out_num)\n out.append(self._nodes[out_name][out_num])\n else:\n out.append(self._nodes[out_name][0])\n\n if isinstance(out, _expr.TupleWrapper):\n out = out.astuple()\n else:\n out = out[0] if len(out) == 1 else _expr.Tuple(out)\n\n fvars = analysis.free_vars(out)\n func = _function.Function(fvars, out)\n final_params = {}\n for fv in fvars:\n if fv.name_hint in self._params:\n final_params[fv.name_hint] = self._params[fv.name_hint]\n self._params = final_params\n return func\n\n def _convert_operator(self, graph, op_name, node_name, inputs, attrs):\n \"\"\"Convert from Tensorflow operator to relay operator.\n The converter must specify conversions explicitly for incompatible name, and\n apply handlers to operator attributes.\n\n Parameters\n ----------\n graph: <class 'tensorflow.core.framework.graph_pb2.GraphDef'>\n TF2 frozen graph def\n op_name : str\n Operator name, such as Conv2D, AvgPool\n node_name: str\n Name of the node in TF2 graph, such as Identity:0\n inputs : list of relay.op\n List of input symbols.\n attrs : dict\n Dict of operator attributes\n\n Returns\n -------\n sym : relay.op\n Converted relay operator\n \"\"\"\n if op_name in [\"PartitionedCall\", \"StatefulPartitionedCall\"]:\n sym = _partition_call_operator(\n self._module,\n graph,\n inputs,\n attrs,\n self._prelude,\n gdef_lib=self._gdef_lib,\n )\n elif op_name in [\"StatelessIf\", \"If\"]:\n sym = _convert_if(\n self._module, graph, inputs, attrs, self._prelude, gdef_lib=self._gdef_lib\n )\n elif op_name in [\"StatelessWhile\", \"While\"]:\n sym = _convert_loop(\n self._module,\n graph,\n inputs,\n attrs,\n node_name,\n self._tf_node_map,\n self._prelude,\n gdef_lib=self._gdef_lib,\n )\n elif op_name in _convert_map_common:\n if _need_prelude_for_shape_inference(op_name):\n sym = _convert_map_common[op_name](inputs, attrs, self._params, self._prelude)\n else:\n sym = _convert_map_common[op_name](inputs, attrs, self._params, self._module.mod)\n else:\n raise NotImplementedError(\"Operator {} not implemented.\".format(op_name))\n\n sym = set_span(sym, node_name)\n return sym\n\n def _backtrack_construct(self, graph, node_name):\n \"\"\"Convert a specific tensorflow node to relay expression.\n\n If any of its ancestor node is not converted yet, backtrack as\n far as input node and covert all nodes on the path. resurion is used here.\n\n This is required when parsing control flow nodes, since the parsing\n order may not follow the original graph def.\n\n to discover input node, current tf node's input is iterated:\n\n tensorflow/core/framework/node_def.proto\n message NodeDef {\n repeated string input = 3;\n }\n\n a node has many inputs (other nodes). each input has the following format:\n data input is \"node:src_output\". node is the string name.\n control input is \"^node\".\n\n Parameters\n ----------\n graph : <class 'tensorflow.core.framework.graph_pb2.GraphDef'>\n TF2 frozen graph def\n\n node_name : str\n node name\n\n Returns\n -------\n op : relay.Expr\n Converted relay expression.\n\n Examples\n --------\n tf expression \"x+1\" is converted to relay expression:\n CallNode(Op(add), [Var(x, ty=TensorType([], float32)), Constant(1.0)], (nullptr), [])\n\n \"\"\"\n\n input_op_name = node_name.split(\":\")[0].split(\"^\")[-1]\n if input_op_name not in self._nodes:\n node = self._tf_node_map[input_op_name]\n attr = parse_attr(node.attr)\n if \"_output_shapes\" in attr:\n self._output_shapes[node.name] = [\n tensor_util.TensorShapeProtoToList(tshape) for tshape in attr[\"_output_shapes\"]\n ]\n else:\n self._output_shapes[node.name] = [None]\n\n attr[\"_output_shapes\"] = self._output_shapes[input_op_name]\n attr[\"_node_name\"] = node.name\n attr[\"_target_layout\"] = self._layout\n inputs = [self._backtrack_construct(graph, iname) for iname in node.input]\n op = self._convert_operator(graph, node.op, node.name, inputs, attr)\n\n if isinstance(op, np.ndarray):\n self._params[node.name] = tvm.nd.array(op)\n op = [\n _expr.var(\n node.name,\n shape=self._params[node.name].shape,\n dtype=self._params[node.name].dtype,\n )\n ]\n elif isinstance(op, (_expr.Expr, _expr.TupleGetItem)):\n op = [op]\n self._nodes[input_op_name] = op\n\n out = self._nodes[input_op_name]\n if isinstance(out, _expr.TupleWrapper):\n tn = node_name.split(\":\")\n tensor_slot = int(tn[1]) if len(tn) > 1 else 0\n return out[tensor_slot]\n\n return out[0]\n\n\ndef _partition_call_operator(module, graph, inputs, attr, prelude, gdef_lib):\n \"\"\"convert tf PartitionedCall node to a relay function call\"\"\"\n node_func_name = attr.get(\"f\").name\n return _convert_function(\n module, graph, inputs, attr, node_func_name, prelude, gdef_lib=gdef_lib\n )\n\n\ndef _convert_if(module, graph, inputs, attr, prelude, gdef_lib):\n \"\"\"Convert tf If/StatelessIf to Relay If\"\"\"\n cond_expr = inputs[0]\n branch_names = [attr.get(x).name for x in [\"then_branch\", \"else_branch\"]]\n then_fn, else_fn = [\n _convert_function(module, graph, inputs[1:], attr, name, prelude, gdef_lib=gdef_lib)\n for name in branch_names\n ]\n out = _expr.If(cond_expr, then_fn, else_fn)\n return out\n\n\ndef _convert_loop(module, graph, inputs, attr, node_name, nodes, prelude, gdef_lib):\n \"\"\"convert tf while_loop to Relay loop\"\"\"\n input_size = len(inputs)\n cond_fn_name, body_fn_name = [attr.get(x).name for x in [\"cond\", \"body\"]]\n\n def convert_vars(loop_inputs, input_signature):\n \"\"\"convert inputs to relay vars to be used as loop variables\n Loop inputs are packed as:\n [iteration_number, max_iterations, loop_variables...]\n \"\"\"\n new_vars = []\n for i, v in enumerate(loop_inputs):\n if isinstance(v, _expr.Constant):\n vtype = _infer_type(v).checked_type.dtype\n new_vars.append(_expr.var(input_signature[i].name, shape=(), dtype=vtype))\n else:\n vtype = _infer_type_with_prelude(v, prelude)\n new_vars.append(_expr.var(input_signature[i].name, type_annotation=vtype))\n return new_vars\n\n while_func = next(\n (f for f in graph.library.function if f.signature.name == attr[\"body\"].name),\n None,\n )\n loop_inputs = convert_vars(inputs, while_func.signature.input_arg)\n\n def cond_fn(*loop_inputs):\n return _convert_function(\n module, graph, loop_inputs, attr, cond_fn_name, prelude, gdef_lib=gdef_lib\n )\n\n # Define the loop body, in this function we need to unpack loop inputs,\n # convert the loop subgraph, and pack outputs for the next iteration.\n def body_fn(*loop_inputs):\n # Increment loop iteration counter\n loop_count = loop_inputs[0] + _expr.const(1, dtype=\"int32\")\n max_count = loop_inputs[1]\n fn = _convert_function(\n module, graph, loop_inputs, attr, body_fn_name, prelude, gdef_lib=gdef_lib\n )\n\n # Repack loop variables\n out = [loop_count, max_count] + [_expr.TupleGetItem(fn, i) for i in range(2, input_size)]\n return out\n\n loop = _while_loop(cond_fn, loop_inputs, body_fn)\n outputs = loop(*inputs)\n outputs = _expr.TupleWrapper(\n _expr.Tuple([_expr.TupleGetItem(outputs, i) for i in range(input_size)]), input_size\n )\n return outputs\n\n\ndef _convert_function(\n module, graph, inputs, attr, node_func_name, prelude, gdef_lib, in_shapes=None\n):\n \"\"\"Convert given tf node to a relay function call\n\n Parameters\n ----------\n module : IRModule\n where converted function is stored\n\n graph: <class 'tensorflow.core.framework.graph_pb2.GraphDef'>\n top level tf graphdef\n\n inputs : List[tvm.relay.Expr]\n List of input symbols. Parameters for the function.\n\n attrs : Dict[tvm.Attrs]\n Dict of operator attributes.\n\n node_func_name : str\n Name of tf2 node to be converted\n\n Returns\n -------\n op : tvm.relay.Expr\n <class 'tvm.relay.expr.Call'>\n\n Examples\n --------\n a tf function \"x+1\", is implemented as a subgraph in the library section of the graph.\n this subgraph is converted to a relay function such as\n fn (%x: float32) {\n add(%x, 1f) /* Identity */\n }\n\n the subgraph has a function name such as __inference_add_95\n the tf function call operator is returned as relay expression, such as:\n free_var %x: float32;\n @func___inference_add_95(%x)\n\n \"\"\"\n func = next(\n (f for f in graph.library.function if f.signature.name == node_func_name),\n None,\n )\n if func is None:\n raise Exception(\"Function not found - {}\".format(node_func_name))\n devices = set(node.device for node in func.node_def)\n if len(devices) > 1:\n raise Exception(\n \"node_def in function {} contains > 1 types of devices {}\".format(\n node_func_name, devices\n )\n )\n\n subgraph = gdef_lib[node_func_name]\n # preserve library functions in subgraphs to make them available to nested functions\n for fn in graph.library.function:\n subgraph.library.function.add().CopyFrom(fn)\n\n # Computing subgraph's input shape and type dictionaries\n input_expr_dict = {}\n input_types = {}\n for f_arg, input_ in zip(func.signature.input_arg, inputs):\n input_expr_dict[f_arg.name] = input_\n input_types[f_arg.name] = _infer_type_with_prelude(input_, prelude)\n\n func_name = \"func_{}\".format(func.signature.name)\n try:\n global_func = module.mod[func_name]\n sub_func = global_func\n sub_params = module.params\n except ValueError:\n # Construct relay nodes from the subgraph\n g1 = GraphProto(module)\n output_sig = [func.ret[f.name] for f in func.signature.output_arg]\n # TODO: unify prelude and main IRModules\n sub_func, sub_params = g1.from_tensorflow(\n subgraph, outputs=output_sig, input_types=input_types, gdef_lib=gdef_lib\n )\n module.params.update(sub_params)\n func_expr = _function.Function(sub_func.params, sub_func.body)\n global_func = tvm.relay.GlobalVar(func_name)\n module.mod[global_func] = func_expr\n module.mod = InferType()(module.mod)\n prelude.mod = module.mod\n\n param_exprs = []\n for param_expr in sub_func.params:\n # sub_params is subset of sub_func.params\n param_name = param_expr.vid.name_hint\n if param_name in input_expr_dict.keys():\n param_exprs.append(input_expr_dict[param_name])\n elif param_name in sub_params.keys():\n param_exprs.append(param_expr)\n else:\n raise Exception(\"Input parameter {} not found\".format(param_name))\n\n sb = tvm.relay.scope_builder.ScopeBuilder()\n loop_ret = global_func(*param_exprs)\n sb.ret(loop_ret)\n ret = sb.get()\n return ret\n\n\ndef from_tensorflow(graph_def, layout=\"NHWC\", shape=None, outputs=None):\n \"\"\"convert tensorflow2.x graph into relay function.\n\n Parameters\n ----------\n graph_def : must be frozen graph (no variables allowed).\n Placeholders are assumed to be inputs to the graph.\n\n tensorflow/core/framework/graph.proto\n message GraphDef {\n repeated NodeDef node = 1;\n FunctionDefLibrary library = 2;\n }\n tensorflow/core/framework/function.proto\n message FunctionDef {\n repeated NodeDef node_def = 3;\n }\n\n layout : str\n The layout for the model.\n\n shape : List[str, List[int]]\n Input to the model. It is a key and shape vector mapping. Applies to placeholders.\n\n outputs : List[str]\n The list of output nodes. The last node is treated as the output if not\n specified.\n\n Returns\n -------\n mod : tvm.IRModule\n The module that optimizations will be performed on.\n\n params : dict of str to tvm.nd.NDArray\n Dict of converted parameters stored in tvm.nd.NDArray format.\n\n Examples\n --------\n \"x+1\" tf module where x has a shape of (2,2) is converted as follows:\n\n mod : tvm.IRModule\n def @func___inference_add_95(%x: Tensor[(2, 2), float32], %add/y: Tensor[(2, 2), float32])\n -> Tensor[(2, 2), float32] {\n add(%x, %add/y) /* Identity */ /* ty=Tensor[(2, 2), float32] */\n }\n\n def @main(%x1: Tensor[(2, 2), float32], %add/y1: Tensor[(2, 2), float32]) {\n @func___inference_add_95(%x1, %add/y1) /* Identity */\n }\n\n params : dict of str to tvm.nd.NDArray\n {'add/y': <tvm.nd.NDArray shape=(2, 2), cpu(0)>\n\n \"\"\"\n\n # Subgraph graph_defs are cached here to avoid a TF error when parsing after prelude init\n graph_def_library = {}\n for func in graph_def.library.function:\n inshape = func.attr[\"_input_shapes\"].list.shape\n graph_def_library[func.signature.name], _ = function_def_to_graph.function_def_to_graph_def(\n func, inshape\n )\n module = RelayModule()\n g = GraphProto(module)\n func, params = g.from_tensorflow(graph_def, layout, shape, outputs, gdef_lib=graph_def_library)\n module.mod[\"main\"] = func\n module.params.update(params)\n return module.mod, module.params\n"
] |
[
[
"tensorflow.python.framework.tensor_util.MakeNdarray",
"numpy.dtype",
"tensorflow.python.framework.dtypes.as_dtype",
"tensorflow.python.framework.function_def_to_graph.function_def_to_graph_def",
"tensorflow.python.framework.tensor_util.TensorShapeProtoToList"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"2.9",
"2.5",
"2.8",
"2.10"
]
}
] |
kuielab/mdx-net
|
[
"bbd46dbf2ceb26c3fbfbe412b5159bce2366c9c0"
] |
[
"src/datamodules/musdb_datamodule.py"
] |
[
"import os\nfrom os.path import exists, join\nfrom pathlib import Path\nfrom typing import Optional, Tuple\n\nfrom pytorch_lightning import LightningDataModule\nfrom torch.utils.data import ConcatDataset, DataLoader, Dataset, random_split\n\nfrom src.datamodules.datasets.musdb import MusdbTrainDataset, MusdbValidDataset\n\n\nclass MusdbDataModule(LightningDataModule):\n \"\"\"\n LightningDataModule for Musdb18-HQ dataset.\n A DataModule implements 5 key methods:\n - prepare_data (things to do on 1 GPU/TPU, not on every GPU/TPU in distributed mode)\n - setup (things to do on every accelerator in distributed mode)\n - train_dataloader (the training dataloader)\n - val_dataloader (the validation dataloader(s))\n - test_dataloader (the test dataloader(s))\n This allows you to share a full dataset without explaining how to download,\n split, transform and process the data\n Read the docs:\n https://pytorch-lightning.readthedocs.io/en/latest/extensions/datamodules.html\n \"\"\"\n\n def __init__(\n self,\n data_dir: str,\n aug_params,\n target_name: str,\n overlap: int,\n hop_length: int,\n dim_t: int,\n sample_rate: int,\n batch_size: int,\n num_workers: int,\n pin_memory: bool,\n external_datasets,\n **kwargs,\n ):\n super().__init__()\n\n self.data_dir = Path(data_dir)\n self.target_name = target_name\n self.aug_params = aug_params\n self.external_datasets = external_datasets\n\n self.batch_size = batch_size\n self.num_workers = num_workers\n self.pin_memory = pin_memory\n\n # audio-related\n self.hop_length = hop_length\n self.sample_rate = sample_rate\n\n # derived\n self.chunk_size = hop_length * (dim_t - 1)\n self.overlap = overlap\n\n self.data_train: Optional[Dataset] = None\n self.data_val: Optional[Dataset] = None\n self.data_test: Optional[Dataset] = None\n\n trainset_path = self.data_dir.joinpath('train')\n validset_path = self.data_dir.joinpath('valid')\n\n # create validation split\n if not exists(validset_path):\n from shutil import move\n os.mkdir(validset_path)\n for track in kwargs['validation_set']:\n if trainset_path.joinpath(track).exists():\n move(trainset_path.joinpath(track), validset_path.joinpath(track))\n else:\n valid_files = os.listdir(validset_path)\n assert set(valid_files) == set(kwargs['validation_set'])\n\n def setup(self, stage: Optional[str] = None):\n \"\"\"Load data. Set variables: self.data_train, self.data_val, self.data_test.\"\"\"\n self.data_train = MusdbTrainDataset(self.data_dir,\n self.chunk_size,\n self.target_name,\n self.aug_params,\n self.external_datasets)\n\n self.data_val = MusdbValidDataset(self.data_dir,\n self.chunk_size,\n self.target_name,\n self.overlap,\n self.batch_size)\n\n def train_dataloader(self):\n return DataLoader(\n dataset=self.data_train,\n batch_size=self.batch_size,\n num_workers=self.num_workers,\n pin_memory=self.pin_memory,\n shuffle=True,\n )\n\n def val_dataloader(self):\n return DataLoader(\n dataset=self.data_val,\n batch_size=1,\n num_workers=self.num_workers,\n pin_memory=self.pin_memory,\n shuffle=False,\n )"
] |
[
[
"torch.utils.data.DataLoader"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
hengwei-chan/rmsd-to-calculate-structural-difference-between-2-cmps
|
[
"55eebc390458307c548b45adfeb84d9f194c4344"
] |
[
"tests/test_kabsch_weighted.py"
] |
[
"import pathlib\n\nimport numpy as np\nfrom context import RESOURCE_PATH\n\nimport rmsd\n\n\ndef test_kabash_fit_pdb():\n\n filename_p = pathlib.PurePath(RESOURCE_PATH, \"ci2_1r+t.pdb\")\n filename_q = pathlib.PurePath(RESOURCE_PATH, \"ci2_1.pdb\")\n\n p_atoms, p_coord = rmsd.get_coordinates_pdb(filename_p)\n q_atoms, q_coord = rmsd.get_coordinates_pdb(filename_q)\n\n new_p_coord = rmsd.kabsch_fit(p_coord, q_coord)\n\n np.testing.assert_array_almost_equal(q_coord[0], new_p_coord[0], decimal=2)\n\n\ndef test_kabash_weighted_fit_pdb():\n\n filename_1 = pathlib.PurePath(RESOURCE_PATH, \"ci2_12.pdb\")\n filename_2 = pathlib.PurePath(RESOURCE_PATH, \"ci2_2.pdb\")\n\n p_atoms, p_coord = rmsd.get_coordinates_pdb(filename_1)\n q_atoms, q_coord = rmsd.get_coordinates_pdb(filename_2)\n\n weights = np.zeros(len(p_coord))\n residue13_start = 200\n residue24_start = 383\n\n weights[residue13_start:residue24_start] = 1.0\n\n new_p_coord = rmsd.kabsch_fit(p_coord, q_coord, weights)\n\n np.testing.assert_array_almost_equal(q_coord[300], new_p_coord[300], decimal=2)\n"
] |
[
[
"numpy.testing.assert_array_almost_equal"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
fjcu-ee-islab/Sideoutput_U2
|
[
"dcec844e5fcb428771142d9d78ca85a4e3c4f694"
] |
[
"eval_other.py"
] |
[
"#!/usr/bin/env python3\r\n# *****************************************************************************\r\n# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\r\n#\r\n# Redistribution and use in source and binary forms, with or without\r\n# modification, are permitted provided that the following conditions are met:\r\n# * Redistributions of source code must retain the above copyright\r\n# notice, this list of conditions and the following disclaimer.\r\n# * Redistributions in binary form must reproduce the above copyright\r\n# notice, this list of conditions and the following disclaimer in the\r\n# documentation and/or other materials provided with the distribution.\r\n# * Neither the name of the NVIDIA CORPORATION nor the\r\n# names of its contributors may be used to endorse or promote products\r\n# derived from this software without specific prior written permission.\r\n#\r\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n# DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY\r\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n#\r\n# *****************************************************************************\r\nimport os\r\nimport sys\r\nimport shutil\r\nimport natsort\r\nimport numpy as np\r\nfrom glob import glob\r\nfrom imageio import imsave\r\nfrom skimage.metrics import peak_signal_noise_ratio as compare_psnr\r\nfrom skimage.metrics import structural_similarity as compare_ssim\r\nfrom tqdm import tqdm\r\ntqdm.monitor_interval = 0\r\n\r\nimport torch\r\nimport torch.backends.cudnn\r\nimport torch.nn.parallel\r\nimport torch.optim\r\nimport torch.utils.data\r\n\r\nfrom parser import parser\r\nimport datasets\r\nimport models\r\nimport utils\r\n\r\n\"\"\"\r\nReda, Fitsum A., et al. \"Unsupervised Video Interpolation Using Cycle Consistency.\"\r\n arXiv preprint arXiv:1906.05928 (2019).\r\n \r\nJiang, Huaizu, et al. \"Super slomo: High quality estimation of multiple\r\n intermediate frames for video interpolation.\" arXiv pre-print arXiv:1712.00080 (2017).\r\n\"\"\"\r\n\r\n\r\ndef main():\r\n with utils.TimerBlock(\"\\nParsing Arguments\") as block:\r\n args = parser.parse_args()\r\n\r\n args.rank = int(os.getenv('RANK', 1))\r\n\r\n block.log(\"Creating save directory: {}\".format(args.save))\r\n args.save_root = os.path.join(args.save, args.name)\r\n if args.write_images or args.write_video:\r\n os.makedirs(args.save_root, exist_ok=True)\r\n assert os.path.exists(args.save_root)\r\n else:\r\n os.makedirs(args.save, exist_ok=True)\r\n assert os.path.exists(args.save)\r\n\r\n os.makedirs(args.torch_home, exist_ok=True)\r\n os.environ['TORCH_HOME'] = args.torch_home\r\n\r\n args.gpus = torch.cuda.device_count() if args.gpus < 0 else args.gpus\r\n block.log('Number of gpus: {} | {}'.format(args.gpus, list(range(args.gpus))))\r\n\r\n args.network_class = utils.module_to_dict(models)[args.model]\r\n args.dataset_class = utils.module_to_dict(datasets)[args.dataset]\r\n block.log('save_root: {}'.format(args.save_root))\r\n block.log('val_file: {}'.format(args.val_file))\r\n\r\n with utils.TimerBlock(\"Building {} Dataset\".format(args.dataset)) as block:\r\n vkwargs = {'batch_size': args.gpus * args.val_batch_size,\r\n 'num_workers': args.gpus * args.workers,\r\n 'pin_memory': True, 'drop_last': True}\r\n step_size = args.val_step_size if args.val_step_size > 0 else (args.num_interp + 1)\r\n val_dataset = args.dataset_class(args=args, root=args.val_file, num_interp=args.num_interp,\r\n sample_rate=args.val_sample_rate, step_size=step_size)\r\n\r\n val_loader = torch.utils.data.DataLoader(val_dataset, shuffle=False,\r\n **vkwargs)\r\n\r\n args.folder_list = natsort.natsorted(\r\n [os.path.basename(f) for f in sorted(glob(os.path.join(args.val_file, '*')))])\r\n\r\n block.log('Number of Validation Images: {}:({} mini-batches)'.format(len(val_loader.dataset), len(val_loader)))\r\n\r\n with utils.TimerBlock(\"Building {} Model\".format(args.model)) as block:\r\n model = args.network_class(args)\r\n\r\n block.log('Number of parameters: {val:,}'.format(val=\r\n sum([p.data.nelement() if p.requires_grad else 0 for p in model.parameters()])))\r\n\r\n block.log('Initializing CUDA')\r\n assert torch.cuda.is_available(), 'Code supported for GPUs only at the moment'\r\n model = model.cuda()\r\n model = torch.nn.DataParallel(model, device_ids=list(range(args.gpus)))\r\n torch.manual_seed(args.seed)\r\n\r\n block.log(\"Attempting to Load checkpoint '{}'\".format(args.resume))\r\n if args.resume and os.path.isfile(args.resume):\r\n checkpoint = torch.load(args.resume)\r\n\r\n # Partial initialization\r\n input_dict = checkpoint['state_dict']\r\n curr_dict = model.module.state_dict()\r\n state_dict = input_dict.copy()\r\n for key in input_dict:\r\n if key not in curr_dict:\r\n continue\r\n if curr_dict[key].shape != input_dict[key].shape:\r\n state_dict.pop(key)\r\n print(\"key {} skipped because of size mismatch.\".format(key))\r\n model.module.load_state_dict(state_dict, strict=False)\r\n\r\n epoch = checkpoint['epoch']\r\n block.log(\"Successfully loaded checkpoint (at epoch {})\".format(epoch))\r\n elif args.resume:\r\n block.log(\"No checkpoint found at '{}'.\\nAborted.\".format(args.resume))\r\n sys.exit(0)\r\n else:\r\n block.log(\"Random initialization, checkpoint not provided.\")\r\n\r\n with utils.TimerBlock(\"Inference started \") as block:\r\n evaluate(args, val_loader, model, args.num_interp, epoch, block)\r\n\r\n\r\ndef evaluate(args, val_loader, model, num_interp, epoch, block):\r\n in_height, in_width = val_loader.dataset[0]['ishape']\r\n pred_flag, pred_values = utils.get_pred_flag(in_height, in_width)\r\n\r\n if not args.apply_vidflag:\r\n pred_flag = 0 * pred_flag + 1\r\n pred_values = 0 * pred_values\r\n\r\n if args.rank == 0 and args.write_video:\r\n video_file = os.path.join(args.save_root, '__epoch_%03d.mp4' % epoch)\r\n _pipe = utils.create_pipe(video_file, in_width, in_height, frame_rate=args.video_fps)\r\n\r\n model.eval()\r\n\r\n loss_values = utils.AverageMeter()\r\n avg_metrics = np.zeros((0, 3), dtype=float)\r\n num_batches = len(val_loader) if args.val_n_batches < 0 else args.val_n_batches\r\n\r\n with torch.no_grad():\r\n for i, batch in enumerate(tqdm(val_loader, total=num_batches)):\r\n\r\n inputs = [b.cuda() for b in batch['image']]\r\n\r\n input_images = [inputs[0], inputs[len(inputs) // 2], inputs[-1]]\r\n inputs_dict = {'image': input_images}\r\n\r\n target_images = inputs[1:-1]\r\n tar_indices = batch['tindex'].cuda()\r\n\r\n # compute loss at mid-way\r\n tar_indices[:] = (num_interp + 1) // 2\r\n loss, outputs, _ = model(inputs_dict, tar_indices)\r\n loss_values.update(loss['tot'].data.item(), outputs.size(0))\r\n\r\n # compute output for each intermediate timepoint\r\n output_image = inputs[0]\r\n for tarIndex in range(1, num_interp + 1):\r\n tar_indices[:] = tarIndex\r\n _, outputs, _ = model(inputs_dict, tar_indices)\r\n output_image = torch.cat((output_image, outputs), dim=1)\r\n output_image = torch.split(output_image, 3, dim=1)[1:]\r\n\r\n batch_size, _, _, _ = inputs[0].shape\r\n input_filenames = batch['input_files'][1:-1]\r\n in_height, in_width = batch['ishape']\r\n\r\n\r\n\r\n for b in range(batch_size):\r\n first_target = (input_images[0][b].data.cpu().numpy().transpose(1, 2, 0)).astype(np.uint8)\r\n first_target = first_target[:in_height, :in_width, :]\r\n second_target = (input_images[-1][b].data.cpu().numpy().transpose(1, 2, 0)).astype(np.uint8)\r\n second_target = second_target[:in_height, :in_width, :]\r\n\r\n gt_image = first_target\r\n for index in range(num_interp):\r\n pred_image = (output_image[index][b].data.cpu().numpy().transpose(1, 2, 0)).astype(np.uint8)\r\n pred_image = pred_image[:in_height, :in_width, :]\r\n\r\n # if ground-truth not loaded, treat low FPS frames as targets\r\n if index < len(target_images):\r\n gt_image = (target_images[index][b].data.cpu().numpy().transpose(1, 2, 0)).astype(np.uint8)\r\n gt_filename = '/'.join(input_filenames[index][b].split(os.sep)[-2:])\r\n gt_image = gt_image[:in_height, :in_width, :]\r\n\r\n\r\n #print('-------------------')\r\n #print(gt_filename)\r\n file_name = gt_filename.split('/')[0]\r\n #print(file_name)\r\n\r\n # calculate metrics using skimage\r\n psnr = compare_psnr(pred_image, gt_image)\r\n ssim = compare_ssim(pred_image, gt_image, multichannel=True, gaussian_weights=True)\r\n err = pred_image.astype(np.float32) - gt_image.astype(np.float32)\r\n ie = np.mean(np.sqrt(np.sum(err * err, axis=2)))\r\n\r\n avg_metrics = np.vstack((avg_metrics, np.array([psnr, ssim, ie])))\r\n\r\n\r\n # write_images\r\n if args.write_images:\r\n tmp_filename = os.path.join(args.save_root, \"%s/%02d_%s.png\" % (file_name, (index + 1), args.post_fix))\r\n os.makedirs(os.path.dirname(tmp_filename), exist_ok=True)\r\n imsave(tmp_filename, pred_image)\r\n\r\n # write video\r\n if args.rank == 0 and args.write_video:\r\n if index == 0:\r\n _pipe.stdin.write(first_target.tobytes())\r\n try:\r\n _pipe.stdin.write((pred_image * pred_flag + pred_values).tobytes())\r\n except AttributeError:\r\n raise AttributeError(\"Error in ffmpeg video creation. Inconsistent image size.\")\r\n if args.write_images:\r\n tmp_filename = os.path.join(args.save_root, \"%s/%02d_%s.png\" % (file_name, 0, \"ground_truth\"))\r\n os.makedirs(os.path.dirname(tmp_filename), exist_ok=True)\r\n imsave(tmp_filename, first_target)\r\n tmp_filename = os.path.join(args.save_root, \"%s/%02d_%s.png\" % (file_name, num_interp+1, \"ground_truth\"))\r\n imsave(tmp_filename, second_target)\r\n if (i + 1) >= num_batches:\r\n break\r\n\r\n if args.write_video:\r\n _pipe.stdin.close()\r\n _pipe.wait()\r\n\r\n \"\"\"\r\n Print final accuracy statistics. If intermediate ground truth frames are not available from the input sequence, \r\n the first low FPS frame is treated as a ground-truth frame for all intermediately predicted frames, \r\n as the quantities should not be trusted, in this case.\r\n \"\"\"\r\n #for i in range(num_interp):\r\n # result2print = 'interm {:02d} PSNR: {:.2f}, SSIM: {:.3f}, IE: {:.2f}'.format(i+1,\r\n # np.nanmean(avg_metrics[i::num_interp], axis=0)[0],\r\n # np.nanmean(avg_metrics[i::num_interp], axis=0)[1],\r\n # np.nanmean(avg_metrics[i::num_interp], axis=0)[2])\r\n # block.log(result2print)\r\n\r\n avg_metrics = np.nanmean(avg_metrics, axis=0)\r\n #result2print = 'Overall PSNR: {:.2f}, SSIM: {:.3f}, IE: {:.2f}'.format(avg_metrics[0], avg_metrics[1],avg_metrics[2])\r\n v_psnr, v_ssim, v_ie = avg_metrics[0], avg_metrics[1], avg_metrics[2]\r\n #block.log(result2print)\r\n\r\n # re-name video with psnr\r\n if args.rank == 0 and args.write_video:\r\n shutil.move(os.path.join(args.save_root, '__epoch_%03d.mp4' % epoch),\r\n os.path.join(args.save_root, '__epoch_%03d_psnr_%1.2f.mp4' % (epoch, avg_metrics[0])))\r\n\r\n # Move back the model to train mode.\r\n model.train()\r\n\r\n torch.cuda.empty_cache()\r\n\r\n return v_psnr, v_ssim, v_ie, loss_values.val\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n"
] |
[
[
"torch.load",
"torch.cat",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"torch.cuda.empty_cache",
"torch.no_grad",
"numpy.nanmean",
"torch.cuda.is_available",
"torch.split",
"torch.cuda.device_count",
"numpy.array",
"numpy.zeros",
"numpy.sum"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
qq456cvb/KeypointNet
|
[
"814a9320d0bd53df47c2a655da55377f714351f2"
] |
[
"benchmark_scripts/models/pointnet.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.utils.data\nfrom torch.autograd import Variable\nimport numpy as np\nimport torch.nn.functional as F\n\n\nclass STN3d(nn.Module):\n def __init__(self):\n super(STN3d, self).__init__()\n self.conv1 = torch.nn.Conv1d(3, 64, 1)\n self.conv2 = torch.nn.Conv1d(64, 128, 1)\n self.conv3 = torch.nn.Conv1d(128, 1024, 1)\n self.fc1 = nn.Linear(1024, 512)\n self.fc2 = nn.Linear(512, 256)\n self.fc3 = nn.Linear(256, 9)\n self.relu = nn.ReLU()\n\n self.bn1 = nn.BatchNorm1d(64)\n self.bn2 = nn.BatchNorm1d(128)\n self.bn3 = nn.BatchNorm1d(1024)\n self.bn4 = nn.BatchNorm1d(512)\n self.bn5 = nn.BatchNorm1d(256)\n\n\n def forward(self, x):\n batchsize = x.size()[0]\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 = torch.max(x, 2, keepdim=True)[0]\n x = x.view(-1, 1024)\n\n x = F.relu(self.bn4(self.fc1(x)))\n x = F.relu(self.bn5(self.fc2(x)))\n x = self.fc3(x)\n\n iden = Variable(torch.from_numpy(np.array([1,0,0,0,1,0,0,0,1]).astype(np.float32))).view(1,9).repeat(batchsize,1)\n if x.is_cuda:\n iden = iden.cuda()\n x = x + iden\n x = x.view(-1, 3, 3)\n return x\n\n\nclass STNkd(nn.Module):\n def __init__(self, k=64):\n super(STNkd, self).__init__()\n self.conv1 = torch.nn.Conv1d(k, 64, 1)\n self.conv2 = torch.nn.Conv1d(64, 128, 1)\n self.conv3 = torch.nn.Conv1d(128, 1024, 1)\n self.fc1 = nn.Linear(1024, 512)\n self.fc2 = nn.Linear(512, 256)\n self.fc3 = nn.Linear(256, k*k)\n self.relu = nn.ReLU()\n\n self.bn1 = nn.BatchNorm1d(64)\n self.bn2 = nn.BatchNorm1d(128)\n self.bn3 = nn.BatchNorm1d(1024)\n self.bn4 = nn.BatchNorm1d(512)\n self.bn5 = nn.BatchNorm1d(256)\n\n self.k = k\n\n def forward(self, x):\n batchsize = x.size()[0]\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 = torch.max(x, 2, keepdim=True)[0]\n x = x.view(-1, 1024)\n\n x = F.relu(self.bn4(self.fc1(x)))\n x = F.relu(self.bn5(self.fc2(x)))\n x = self.fc3(x)\n\n iden = Variable(torch.from_numpy(np.eye(self.k).flatten().astype(np.float32))).view(1,self.k*self.k).repeat(batchsize,1)\n if x.is_cuda:\n iden = iden.cuda()\n x = x + iden\n x = x.view(-1, self.k, self.k)\n return x\n\n\nclass PointNetfeat(nn.Module):\n def __init__(self, global_feat = True, feature_transform = False):\n super(PointNetfeat, self).__init__()\n self.stn = STN3d()\n self.conv1 = torch.nn.Conv1d(3, 64, 1)\n self.conv2 = torch.nn.Conv1d(64, 128, 1)\n self.conv3 = torch.nn.Conv1d(128, 1024, 1)\n self.bn1 = nn.BatchNorm1d(64)\n self.bn2 = nn.BatchNorm1d(128)\n self.bn3 = nn.BatchNorm1d(1024)\n self.global_feat = global_feat\n self.feature_transform = feature_transform\n if self.feature_transform:\n self.fstn = STNkd(k=64)\n\n def forward(self, x):\n n_pts = x.size()[2]\n trans = self.stn(x)\n x = x.transpose(2, 1)\n x = torch.bmm(x, trans)\n x = x.transpose(2, 1)\n x = F.relu(self.bn1(self.conv1(x)))\n\n if self.feature_transform:\n trans_feat = self.fstn(x)\n x = x.transpose(2,1)\n x = torch.bmm(x, trans_feat)\n x = x.transpose(2,1)\n else:\n trans_feat = None\n\n pointfeat = x\n x = F.relu(self.bn2(self.conv2(x)))\n x = self.bn3(self.conv3(x))\n x = torch.max(x, 2, keepdim=True)[0]\n x = x.view(-1, 1024)\n if self.global_feat:\n return x, trans, trans_feat\n else:\n x = x.view(-1, 1024, 1).repeat(1, 1, n_pts)\n return torch.cat([x, pointfeat], 1), trans, trans_feat\n\n\nclass PointNetCls(nn.Module):\n def __init__(self, k=2, feature_transform=False, cfg=None):\n super(PointNetCls, self).__init__()\n self.cfg = cfg\n self.feature_transform = feature_transform\n self.feat = PointNetfeat(global_feat=True, feature_transform=feature_transform)\n self.fc1 = nn.Linear(1024, 512)\n self.fc2 = nn.Linear(512, 256)\n self.fc3 = nn.Linear(256, k)\n self.dropout = nn.Dropout(p=0.3)\n self.bn1 = nn.BatchNorm1d(512)\n self.bn2 = nn.BatchNorm1d(256)\n self.relu = nn.ReLU()\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n x, trans, trans_feat = self.feat(x)\n x = F.relu(self.bn1(self.fc1(x)))\n x = F.relu(self.bn2(self.dropout(self.fc2(x))))\n x = self.fc3(x).reshape(-1, int(self.cfg['num_cls']), 3)\n # return F.log_softmax(x, dim=1), trans, trans_feat\n return x\n\n\nclass PointNetDenseCls(nn.Module):\n def __init__(self, cfg):\n super(PointNetDenseCls, self).__init__()\n assert cfg.network.name == 'pointnet'\n self.k = cfg.num_classes\n self.feature_transform = cfg.network.feature_transform\n self.feat = PointNetfeat(global_feat=False, feature_transform=cfg.network.feature_transform)\n self.conv1 = torch.nn.Conv1d(1088, 512, 1)\n self.conv2 = torch.nn.Conv1d(512, 256, 1)\n self.conv3 = torch.nn.Conv1d(256, 128, 1)\n self.conv4 = torch.nn.Conv1d(128, self.k, 1)\n self.bn1 = nn.BatchNorm1d(512)\n self.bn2 = nn.BatchNorm1d(256)\n self.bn3 = nn.BatchNorm1d(128)\n\n def forward(self, x):\n batchsize = x.size()[0]\n n_pts = x.size()[2]\n x, trans, trans_feat = self.feat(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 embedding = x.clone().transpose(2,1)\n x = self.conv4(x)\n x = x.transpose(2, 1)\n # x = F.softmax(x.reshape(-1, self.k), dim=1)\n x = x.reshape(batchsize, n_pts, self.k)\n return x #, embedding, trans, trans_feat\n\n\ndef feature_transform_reguliarzer(trans):\n d = trans.size()[1]\n batchsize = trans.size()[0]\n I = torch.eye(d)[None, :, :]\n if trans.is_cuda:\n I = I.cuda()\n loss = torch.mean(torch.norm(torch.bmm(trans, trans.transpose(2,1) - I), dim=(1,2)))\n return loss\n\nSaliencyModel = PointNetDenseCls\nCorrespondenceModel = PointNetDenseCls\n\n\nif __name__ == '__main__':\n sim_data = Variable(torch.rand(32,3,2500))\n trans = STN3d()\n out = trans(sim_data)\n print('stn', out.size())\n # print('loss', feature_transform_reguliarzer(out))\n #\n # sim_data_64d = Variable(torch.rand(32, 64, 2500))\n # trans = STNkd(k=64)\n # out = trans(sim_data_64d)\n # print('stn64d', out.size())\n # print('loss', feature_transform_reguliarzer(out))\n \n pointfeat = PointNetfeat(global_feat=True)\n out, _, _ = pointfeat(sim_data)\n print('global feat', out.size())\n\n pointfeat = PointNetfeat(global_feat=False)\n out, _, _ = pointfeat(sim_data)\n print('point feat', out.size())\n\n cls = PointNetCls(k = 5)\n out, _, _ = cls(sim_data)\n print('class', out.size())\n\n seg = PointNetDenseCls(k = 3)\n out, _, _ = seg(sim_data)\n print('seg', out.size())\n"
] |
[
[
"torch.nn.BatchNorm1d",
"torch.nn.Dropout",
"torch.max",
"torch.cat",
"numpy.eye",
"torch.eye",
"torch.nn.Sigmoid",
"torch.nn.Linear",
"torch.bmm",
"torch.rand",
"torch.nn.Conv1d",
"torch.nn.ReLU",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
andresdelarosa1887/Public-Projects
|
[
"db8d8e0c0f5f0f7326346462fcdfe21ce8142a12"
] |
[
"OCDS API- Dominican Republic/04_tagInformation.py"
] |
[
"import pandas as pd\nimport numpy as np\nimport datetime as dt\nimport concurrent.futures\nimport threading\nfrom unidecode import unidecode\n\n\n\ndef mapeo_procesos_final(): \n contratos= get_mapeo_contratosPT()\n procesos= get_mapeo_procesosPT()\n data_fortag= pd.merge(procesos, contratos, left_on='id', right_on='id', how='left') \n \n only_tender = [\"unsuccessful\", \"active\", \"cancelled\", \"planned\", \"complete\"]\n proceso_tender_award_contrato = [\"active\", \"cancelled\", \"complete\", \"planned\", \"unsuccessful\"]\n contrato_tender_award_contrato = [\"active\", \"cancelled\", \"pending\", \"terminated\" ]\n \n data_fortag['tag'] = data_fortag\\\n .apply(lambda x: \"tender\" \n if (x['tender/status'] in (only_tender) and pd.isna(x['contracts/0/id']))\n else (\"tender;award;contract\" \n if (x['tender/status']in (proceso_tender_award_contrato) \n and x['contracts/0/status'] in (contrato_tender_award_contrato)) \n else \"nill\"), axis=1)\n \n \n data_fortag['ocid'] = 'ocds-6550wx-' + data_fortag['tender/id']\n \n data_for_tag= data_fortag[[\n 'ocid',\n 'id', \n 'tag']]\n \n data_for_tag.drop_duplicates()\n \n mapeo_procesos_final = pd.merge(procesos, data_for_tag, left_on='id', right_on='id', how='left')\n \n mapeo_procesos_final= mapeo_procesos_final[\n ['ocid',\n 'id',\n 'date',\n 'tag',\n 'initiationType',\n 'tender/id',\n 'tender/title',\n 'tender/procurementMethod',\n 'tender/procurementMethodDetails',\n 'tender/status',\n 'tender/mainProcurementCategory',\n 'tender/value/amount',\n 'tender/value/currency',\n 'tender/procuringEntity/id',\n 'tender/procuringEntity/name',\n 'tender/tenderPeriod/startDate',\n 'tender/tenderPeriod/endDate',\n 'tender/awardPeriod/startDate',\n 'tender/awardPeriod/endDate']]\n \n \n return data_for_tag\n\n"
] |
[
[
"pandas.merge",
"pandas.isna"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"0.24",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
ptrckhmmr/ChatBotforCulturalInstitutions
|
[
"c3da1a6d142e306c2e3183ba5609553e15a0e124"
] |
[
"Chatbot_DebuggingVersion/app/__init__.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"This module contains the MindMeld application\"\"\"\nfrom mindmeld import Application\nfrom mindmeld.components import QuestionAnswerer\n\n# suggestions\nfrom fuzzywuzzy import process\n\n# data import\nimport pandas as pd\n\nimport os\napp_path = os.path.dirname(__file__)\n\n# setting up knowledge base for query\nqa = QuestionAnswerer(app_path)\nqa.load_kb('app', 'exhibition', app_path + '/data/exhibition.json')\nqa.load_kb('app', 'artists', app_path + '/data/artists.json')\n#qa.load_kb('app', 'event', app_path + '/data/event.json')\nqa.load_kb('app', 'openinghours', app_path + '/data/openinghours.json')\nqa.load_kb('app', 'jokes', app_path + '/data/jokes.json')\n\n# retrieving all suggestions\nsuggestions = pd.read_csv(app_path + '/data/all_possible_questions.txt',header=None, sep='\\n')\n\n#suggestions_exhibition = pd.read_csv(app_path + '/data/all_possible_questions.txt',header=None, sep='\\n')\n\nsuggestions_exhibition = pd.read_csv(app_path + '/data/all_exhibition_questions.txt',header=None, sep='\\n')\n\napp = Application(__name__)\n\n__all__ = ['app']\n\n### Methods used within dialoque states###\n\ndef string_current_exhibitions(exhibition):\n \"\"\"\n This function returns a combined string from a list of strings.\n\n Input:\n exhibition: list of at maximum 50 exhibitions from knowledge base\n\n Returns:\n String with exhibitions.\n \"\"\"\n\n\n from datetime import datetime\n\n now = datetime.now()\n heute = now.strftime(\"%Y-%m-%d\")\n\n ausstellung_offen = ''\n\n for item in exhibition:\n if (item['ende_tag'] > heute):\n ausstellung_offen = ausstellung_offen + item['titel_de'] + ', '\n\n return ausstellung_offen\n\n\ndef draw_ten_artists_from_current_exhibition(exhibition):\n \"\"\"\n This function obtains 10 entries from a list.\n\n Input:\n exhibition: list of exhibitions\n\n Returns:\n String with artists.\n \"\"\"\n\n from datetime import datetime\n now = datetime.now()\n heute = now.strftime(\"%Y-%m-%d\")\n\n s = qa.build_search(index='exhibition')\n ausstellung_offen = []\n artists_ausstellungen_offen = ''\n\n for item in exhibition:\n if (item['ende_tag'] > heute):\n ausstellung_offen.append(item['titel_de'])\n\n for item in ausstellung_offen:\n tmpt = s.query(titel_de=item).execute(size=1)\n artists_ausstellungen_offen = artists_ausstellungen_offen + tmpt[0]['person_freie_rolle'] + ', '\n artists_ausstellungen_offen = artists_ausstellungen_offen + tmpt[0]['person_feste_rolle'] + ', '\n\n import re\n artists_ausstellungen_offen = re.sub(\"\\(.*?\\)\", \"\", artists_ausstellungen_offen)\n artists_ausstellungen_offen = re.sub(\"not available, \", \"\", artists_ausstellungen_offen)\n\n artists_ausstellungen_offen = artists_ausstellungen_offen.split(',')\n artists_ausstellungen_offen = pd.DataFrame(artists_ausstellungen_offen, columns=['Artists Current Exhibitions'])\n artists_ausstellungen_offen = artists_ausstellungen_offen[\n artists_ausstellungen_offen['Artists Current Exhibitions'] != '']\n artists_ausstellungen_offen = artists_ausstellungen_offen.iloc[:-1, :]\n artists_ausstellungen_offen = artists_ausstellungen_offen.sample(n=10)\n\n artists = ''\n for index, row in artists_ausstellungen_offen.iterrows():\n artists = artists + row['Artists Current Exhibitions'] + ','\n\n artists = re.sub(\" , \", \", \", artists)\n artists = artists[:-1]\n\n return artists\n\n\ndef filter_regular_expressions(beschreibung):\n \"\"\"\n This function replaces certain patterns in a string by using regular expressions.\n\n Input:\n beschreibung: string variable\n\n Returns:\n Modified String.\n \"\"\"\n\n import re\n beschreibung = re.sub(\"<.*?>\", \"\", beschreibung)\n beschreibung = re.sub(\"&.*?;\", \"\", beschreibung)\n\n return beschreibung\n\n\ndef filter_drupal(beschreibung):\n \"\"\"\n This function replaces certain patterns in a string by using regular expressions.\n\n Input:\n beschreibung: string variable\n\n Returns:\n Modified String.\n \"\"\"\n\n import re\n beschreibung = re.sub(\"\\(.*?\\)\", \"\", beschreibung)\n\n return beschreibung\n\n\ndef übermorgen_in_datum():\n \"\"\"\n This function calculates what date the day after tomorrow is.\n\n Returns:\n Date as String.\n \"\"\"\n\n from datetime import datetime\n from datetime import timedelta\n\n now = datetime.now()\n übermorgen = now + timedelta(days=2)\n übermorgen = übermorgen.strftime(\"%Y-%m-%d\")\n\n return übermorgen\n\n\ndef übermorgen_in_wochentag():\n \"\"\"\n This function calculates what week of the day in two days is.\n\n Returns:\n Day as String.\n \"\"\"\n\n from datetime import datetime\n from datetime import timedelta\n\n now = datetime.now()\n übermorgen = now + timedelta(days=2)\n\n wochentag = [\"Montag\", \"Dienstag\", \"Mittwoch\", \"Donnerstag\", \"Freitag\", \"Samstag\", \"Sonntag\"]\n tagnummer = übermorgen.weekday()\n\n return wochentag[tagnummer]\n\n\ndef morgen_in_datum():\n \"\"\"\n This function calculates what date tomorrow is.\n\n Returns:\n Date as String.\n \"\"\"\n\n from datetime import datetime\n from datetime import timedelta\n\n now = datetime.now()\n morgen = now + timedelta(days=1)\n morgen = morgen.strftime(\"%Y-%m-%d\")\n\n return morgen\n\n\ndef morgen_in_wochentag():\n \"\"\"\n This function calculates what week of the day tomorrow is.\n\n Returns:\n Day as String.\n \"\"\"\n\n from datetime import datetime\n from datetime import timedelta\n\n now = datetime.now()\n morgen = now + timedelta(days=1)\n\n wochentag = [\"Montag\", \"Dienstag\", \"Mittwoch\", \"Donnerstag\", \"Freitag\", \"Samstag\", \"Sonntag\"]\n tagnummer = morgen.weekday()\n\n return wochentag[tagnummer]\n\n\ndef heute_in_wochentag():\n \"\"\"\n This function calculates what week of the day today is.\n\n Returns:\n Day as String.\n \"\"\"\n\n from datetime import datetime\n from datetime import timedelta\n\n now = datetime.now()\n heute = now\n\n wochentag = [\"Montag\", \"Dienstag\", \"Mittwoch\", \"Donnerstag\", \"Freitag\", \"Samstag\", \"Sonntag\"]\n tagnummer = heute.weekday()\n\n return wochentag[tagnummer]\n\n\ndef datum_in_wochentag(entry):\n \"\"\"\n This function calculates what week of the day corresponds to a specified date.\n\n Input:\n entry: date\n Returns:\n Day as String or NULL if error occurred.\n \"\"\"\n\n from datetime import datetime\n from datetime import timedelta\n\n year = str(datetime.now().year)\n wochentag = [\"Montag\", \"Dienstag\", \"Mittwoch\", \"Donnerstag\", \"Freitag\", \"Samstag\", \"Sonntag\"]\n if (entry.find('-') != -1):\n if (entry.count('-') == 1):\n datum = entry + '-' + year\n datum = datetime.strptime(datum, \"%d-%m-%Y\")\n tagnummer = datum.weekday()\n\n return wochentag[tagnummer]\n\n if (entry.count('-') == 2):\n year = str(datetime.now().year)\n datum = entry\n try:\n datum = datetime.strptime(datum, \"%d-%m-%Y\")\n tagnummer = datum.weekday()\n\n return wochentag[tagnummer]\n except:\n return 'null'\n\n elif (entry.find('/') != -1):\n if (entry.count('/') == 1):\n datum = entry + '/' + year\n datum = datetime.strptime(datum, \"%d/%m/%Y\")\n tagnummer = datum.weekday()\n\n return wochentag[tagnummer]\n\n elif (entry.count('/') == 2):\n year = str(datetime.now().year)\n datum = entry\n try:\n datum = datetime.strptime(datum, \"%d/%m/%Y\")\n tagnummer = datum.weekday()\n\n return wochentag[tagnummer]\n except:\n return 'null'\n\n\n elif (entry.find('.') != -1):\n if (entry.count('.') == 1):\n datum = entry + '.' + year\n try:\n datum = datetime.strptime(datum, \"%d.%m.%Y\")\n tagnummer = datum.weekday()\n\n return wochentag[tagnummer]\n except:\n return 'null'\n\n if (entry.count('.') == 2):\n if (entry[-1] == '.'):\n datum = entry + year\n datum = datetime.strptime(datum, \"%d.%m.%Y\")\n tagnummer = datum.weekday()\n return wochentag[tagnummer]\n\n else:\n year = str(datetime.now().year)\n datum = entry\n try:\n datum = datetime.strptime(datum, \"%d.%m.%Y\")\n tagnummer = datum.weekday()\n\n return wochentag[tagnummer]\n except:\n return 'null.'\n else:\n return 'null'\n\n\ndef hasNumbers(inputString):\n \"\"\"\n This function checks if a String contains a number\n\n Input:\n inputString: String\n\n Returns:\n Boolean value.\n \"\"\"\n\n import re\n return bool(re.search(r'\\d', inputString))\n\n\nclass Entity_memory:\n \"\"\"\n This class is used to store entities.\n \"\"\"\n\n def __init__(self, name=''):\n self._name = name\n\n # getter method\n\n def get_entity(self):\n \"\"\"\n This function retrieves the entity.\n\n Returns:\n String variable\n \"\"\"\n\n return self._name\n\n # setter method\n\n def set_entity(self, x):\n \"\"\"\n This function sets the entity to a specified input.\n\n Input:\n x: Entity as String var\n\n Returns:\n Nothing.\n\n \"\"\"\n self._name = x\n\nem = Entity_memory()\nem.set_entity('')\n\n\n#### intents from 'basic' domain ####\n\[email protected](intent='greet')\ndef welcome(request, responder):\n \"\"\"\n Saying hello to the user.\n\n Returns:\n Nothing.\n \"\"\"\n em.set_entity('')\n\n # Clear the dialogue frame to start afresh for the next user request.\n #responder.frame = {}\n\n # Respond with a random selection from one of the canned \"goodbye\" responses.\n responder.reply(['Hallo, ich bin dein persönlicher Chatbot! 😍', 'Hey! Freut mich dich kennenzulernen! 😄'])\n\n\n\[email protected](intent='how_are_you')\ndef say_I_am_doing_great(request, responder):\n \"\"\"\n Answering 'how are you'.\n\n Returns:\n Nothing.\n \"\"\"\n\n em.set_entity('')\n\n # Clear the dialogue frame to start afresh for the next user request.\n responder.frame = {}\n\n responder.reply(['Bei mir ist alles besten. Ich hoffe, dass bei dir auch alles klar ist! Wie kann ich dir weiterhelfen?', 'Mir geht es super, vielen Dank. Wie kann ich dir weiterhelfen?',\n 'Bei mir ist alles klar. Danke der Nachfrage! Wie kann ich dir weiterhelfen?'])\n\n\[email protected](intent='exit')\ndef say_goodbye(request, responder):\n \"\"\"\n When the user ends a conversation, clear the dialogue frame and say goodbye.\n\n Returns:\n Nothing.\n \"\"\"\n em.set_entity('')\n\n # Clear the dialogue frame to start afresh for the next user request.\n responder.frame = {}\n\n # Respond with a random selection from one of the canned \"goodbye\" responses.\n responder.reply(['Ciao!', 'Auf Wiedersehen!', 'Adios.', 'Tschüss! Bis zum nächsten Mal!.'])\n\n\n#### intents from 'zkm' domain ####\n\[email protected](intent='zkm_general')\ndef say_zkm_general(request, responder):\n \"\"\"\n Replying with general information about the ZKM.\n\n Returns:\n Nothing.\n \"\"\"\n em.set_entity('')\n\n # Clear the dialogue frame to start afresh for the next user request.\n responder.frame = {}\n\n beschreibung = 'Das ZKM wurde 1989 von der Stadt Karlsruhe und dem Land Baden-Würtemberg gegründet. Gründungsdirektor Heinrich Klotz formte die Mission des ZKMs, die klassischen Künste ins digitale Zeitalter fortzuschreiben. Die einzigartige Kulturinstitution ist seit 1997 in einem ehemaligen, denkmalgeschützten Industriebau, dem sogenannten Hallenbau A untergebracht, der zu seiner Entstehungszeit einer der architektonisch fortschrittlichsten in Deutschland war. Hier findest du weitere Infos dazu: https://zkm.de/de/das-zkm '\n\n # Respond\n responder.reply(beschreibung)\n\n\[email protected](intent='zkm_content')\ndef say_zkm_content(request, responder):\n \"\"\"\n Replying with a short definition of ZKM\n\n Returns:\n Nothing.\n \"\"\"\n em.set_entity('')\n\n # Clear the dialogue frame to start afresh for the next user request.\n responder.frame = {}\n\n beschreibung = 'Es ist ein Haus aller Medien und Gattungen, ein Haus sowohl der raumbasierten Künste wie Malerei, Fotografie und Skulptur als auch der zeitbasierten Künste wie Film, Video, Medienkunst, Musik, Tanz, Theater und Performance.'\n\n # Respond\n responder.reply(beschreibung)\n\[email protected](intent='zkm_cinema')\ndef say_zkm_cinema(request, responder):\n \"\"\"\n Telling the user the ZKM is not a cinema.\n\n Returns:\n Nothing.\n \"\"\"\n em.set_entity('')\n\n # Clear the dialogue frame to start afresh for the next user request.\n responder.frame = {}\n\n beschreibung = 'Anders als viele Menschen denken, ist das ZKM kein Kino. Das Kino, „der Filmpalast am ZKM“ befindet sich neben dem ZKM. Hier findest du das Kinoprogramm: https://www.filmpalast.net. Bei uns im ZKM kannst du allerdings auch sehr viel Spaß haben. Schau doch auch mal bei uns vorbei, wir haben spannende interaktive Ausstellungen und ein sehr nettes Café bei uns. Hier findest du uns: https://zkm.de/de/ueber-das-zkm/kontakte '\n\n # Respond\n responder.reply(beschreibung)\n\n\[email protected](intent='zkm_journey_car')\ndef say_zkm_journey_car(request, responder):\n \"\"\"\n Telling the user how to get to the ZKM by car.\n\n Returns:\n Nothing.\n \"\"\"\n em.set_entity('')\n\n # Clear the dialogue frame to start afresh for the next user request.\n responder.frame = {}\n\n beschreibung = 'Das ZKM ist mit dem Auto sehr gut zu erreichen. Es befindet sich in der Lorenzstraße 19 in Karlsruhe (https://goo.gl/maps/gdmpM8VNrHyNZmFu5). Im Parkhaus des ZKMs stehen etwa 700 kostenpflichtige Parkplätze zur Verfügung. Zu erreichen ist das Parkhaus »ZKM« über die Südendstraße 44 (https://goo.gl/maps/U983qzbWB3dvE6s89). Für Elektroautos stehen zwei Stromladestationen zur Verfügung. Hier findest du weitere Infos zur Anfahrt mit dem Auto: https://zkm.de/de/ausstellungen-veranstaltungen/anfahrt '\n\n # Respond\n responder.reply(beschreibung)\n\n\[email protected](intent='zkm_journey_bus')\ndef say_zkm_journey_bus(request, responder):\n \"\"\"\n Telling the user how to get to the ZKM by car.\n\n Returns:\n Nothing.\n \"\"\"\n em.set_entity('')\n\n # Clear the dialogue frame to start afresh for the next user request.\n responder.frame = {}\n\n beschreibung = 'Das ZKM ist mit öffentlichen Verkehrsmitteln sehr gut zu erreichen. Es befindet sich in der Lorenzstraße 19 in Karlsruhe (https://goo.gl/maps/gdmpM8VNrHyNZmFu5). Die Straßenbahn Haltestelle „ZKM“ ist mit der Linie 2 am besten zu erreichen. Aufgrund von Baumaßnahmen kommt es im Raum Karlsruhe zeitweise zu geänderten Fahrtzeiten. Wir bitten Sie, die aktuelle Verkehrslage auf der Webpräsenz des Karlsruher Verkehrsverbunds (KVV) zu überprüfen. Mit dem Bus, fährt man am besten zur Haltestelle „Lorenzstraße – ZKM“. Hierhin fährt die Buslinie 55. Hier findest du weitere Infos zur Anfahrt mit den öffentlichen Verkehrsmitteln: https://zkm.de/de/ausstellungen-veranstaltungen/anfahrt '\n\n # Respond\n responder.reply(beschreibung)\n\n\[email protected](intent='exhibition_duration')\ndef say_exhibition_duration(request, responder):\n \"\"\"\n Telling the user how long an exhibition will be open.\n\n Returns:\n Nothing.\n \"\"\"\n em.set_entity('')\n\n # Clear the dialogue frame to start afresh for the next user request.\n responder.frame = {}\n\n try:\n\n # Extract id from query\n id = request.entities[0]['value'][0]['id']\n\n exhibtion = qa.get(index='exhibition', id=id)\n\n title = exhibtion[0]['titel_de']\n start = exhibtion[0]['start_tag']\n end = exhibtion[0]['ende_tag']\n\n\n response = 'Die Ausstellung ' + title + ' hat von ' + start + ' bis ' + end + ' geöffnet.'\n\n # Respond\n responder.reply(response)\n\n except:\n\n response = 'Sorry, das habe ich nicht verstanden.'\n\n responder.reply(response)\n\n\n\[email protected](intent='exhibition_description')\ndef say_exhibition_description(request, responder):\n \"\"\"\n Telling the user what an exhibition is about.\n\n Returns:\n Nothing.\n \"\"\"\n em.set_entity('')\n\n # Clear the dialogue frame to start afresh for the next user request.\n responder.frame = {}\n\n try:\n # Extract id from query\n id = request.entities[0]['value'][0]['id']\n\n exhibtion = qa.get(index='exhibition', id=id)\n\n title = exhibtion[0]['titel_de']\n beschreibung = exhibtion[0]['kurzbeschreibung_seo_de']\n\n beschreibung = filter_regular_expressions(beschreibung)\n\n if (beschreibung == 'not available'):\n responder.reply('Leider habe ich keine Informationen zur Ausstellung ' + title + '.')\n else:\n # Respond\n responder.reply(beschreibung)\n\n except:\n query = request.text\n\n recommendation = process.extractOne(query, suggestions_exhibition[0])\n score = recommendation[1]\n suggestion = recommendation[0]\n\n if (score > 90):\n response = 'Sorry, das habe ich nicht verstanden, aber meintest du vielleicht: ' + suggestion\n\n else:\n response = 'Sorry, das habe ich nicht verstanden.'\n\n responder.reply(response)\n\n\[email protected](intent='exhibition_artist')\ndef say_exhibition_artist(request, responder):\n \"\"\"\n Replying with the artists of an exhibition.\n\n Returns:\n Nothing.\n \"\"\"\n em.set_entity('')\n\n # Clear the dialogue frame to start afresh for the next user request.\n responder.frame = {}\n\n try:\n\n # Extract id from query\n id = request.entities[0]['value'][0]['id']\n\n exhibtion = qa.get(index='exhibition', id=id)\n\n title = exhibtion[0]['titel_de']\n beschreibung = exhibtion[0]['person_freie_rolle']\n\n beschreibung = filter_drupal(beschreibung)\n\n if (beschreibung == 'not available'):\n responder.reply('Leider habe ich keine Informationen zur Ausstellung ' + title + '.')\n else:\n # Respond\n responder.reply('Bei der Ausstellung ' + title + ' haben folgende Künstler mitgewirkt: ' + beschreibung)\n\n except:\n\n response = 'Sorry, das habe ich nicht verstanden.'\n\n responder.reply(response)\n\n\n\n\[email protected](intent='artist_information')\ndef say_artist_information(request, responder):\n \"\"\"\n Telling the user about the artist.\n\n Returns:\n Nothing.\n \"\"\"\n # Clear the dialogue frame to start afresh for the next user request.\n responder.frame = {}\n\n\n entity = request.entities\n print(entity)\n\n\n\n if (entity == ()):\n\n\n\n if (em.get_entity() == ''):\n responder.reply('Über welchen Künstler möchstest du mehr wissen?')\n print('Ohne entity IF artist info: Über welchen Künstler möchstest du mehr wissen?')\n else:\n\n name = em.get_entity()\n print('Name try else')\n print(name)\n\n\n try:\n\n s = qa.build_search(index='artists')\n id = s.filter(name=name).execute()[0]['id']\n\n print('Ohne entity ELSE artist info')\n #print(responder.history[0]['request']['intent'])\n #print(responder.history[0]['request']['entities'][0]['text'])\n\n artists = qa.get(index='artists', id=id)\n\n title = artists[0]['name']\n beschreibung = artists[0]['beschreibung_de']\n\n beschreibung = filter_regular_expressions(beschreibung)\n\n if (beschreibung == 'not available'):\n responder.reply('Leider habe ich keine Informationen zu ' + title + '.')\n else:\n # Respond\n responder.reply('Hintergrundinformationen zu ' + title + ' : ' + beschreibung)\n\n except:\n\n response = 'Sorry, das habe ich nicht verstanden.'\n\n responder.reply(response)\n\n\n else:\n\n em.set_entity(entity[0]['text'])\n\n print('Mit entity ELSE artist info')\n print(entity[0]['text'])\n print(em.get_entity())\n\n try:\n\n # Extract id from query\n id = request.entities[0]['value'][0]['id']\n\n artists = qa.get(index='artists', id=id)\n\n title = artists[0]['name']\n beschreibung = artists[0]['beschreibung_de']\n\n beschreibung = filter_regular_expressions(beschreibung)\n\n if (beschreibung == 'not available'):\n responder.reply('Leider habe ich keine Informationen zu ' + title + '.')\n else:\n # Respond\n responder.reply('Hintergrundinformationen zu ' + title + ' : ' + beschreibung)\n\n\n\n\n except:\n\n response = 'Sorry, das habe ich nicht verstanden.'\n\n responder.reply(response)\n\n\[email protected](intent='artist_birthyear')\ndef say_artist_birthyear(request, responder):\n \"\"\"\n Tell the user about the year of birth of an artist.\n\n Returns:\n Nothing.\n \"\"\"\n # Clear the dialogue frame to start afresh for the next user request.\n responder.frame = {}\n\n entity = request.entities\n # name = request.entities[0]['text']\n\n if (entity == ()):\n\n if (em.get_entity() == ''):\n responder.reply('Von welchem Künstler möchstest du das Geburtsjahr wissen?')\n print('Ohne entity IF artist birthyear: Von welchem Künstler möchstest du das Geburtsjahr wissen?')\n else:\n\n name = em.get_entity()\n print('Name try else')\n print(name)\n\n\n try:\n\n s = qa.build_search(index='artists')\n id = s.filter(name=name).execute()[0]['id']\n\n print('Ohne Entity ELSE artist birthyear')\n\n artists = qa.get(index='artists', id=id)\n\n title = artists[0]['name']\n geburtsjahr = artists[0]['born_year']\n\n if (geburtsjahr == 'not available'):\n responder.reply('Leider habe ich keine Informationen über das Geburtsjahr von ' + title + '.')\n else:\n # Respond\n responder.reply(title + ' ist im Jahr ' + geburtsjahr + ' geboren.')\n\n except:\n\n response = 'Sorry, das habe ich nicht verstanden.'\n\n responder.reply(response)\n\n\n\n else:\n\n em.set_entity(entity[0]['text'])\n\n print('Mit Entity ELSE artist birthyear')\n\n try:\n\n # Extract id from query\n id = request.entities[0]['value'][0]['id']\n\n artists = qa.get(index='artists', id=id)\n\n title = artists[0]['name']\n geburtsjahr = artists[0]['born_year']\n\n\n if (geburtsjahr == 'not available'):\n responder.reply('Leider habe ich keine Informationen über das Geburtsjahr von ' + title + '.')\n else:\n # Respond\n responder.reply(title + ' ist im Jahr ' + geburtsjahr + ' geboren.')\n\n except:\n\n response = 'Sorry, das habe ich nicht verstanden.'\n\n responder.reply(response)\n\n\n\[email protected](intent='artist_birthplace')\ndef say_artist_birthplace(request, responder):\n \"\"\"\n Telling the user where an artist was born.\n\n Returns:\n Nothing.\n \"\"\"\n # Clear the dialogue frame to start afresh for the next user request.\n responder.frame = {}\n\n entity = request.entities\n # name = request.entities[0]['text']\n\n if (entity == ()):\n\n if (em.get_entity() == ''):\n responder.reply('Von welchem Künstler möchstest du den Geburtsort wissen?')\n print('Ohne entity IF artist birthyear: Von welchem Künstler möchstest du den Geburtsort wissen?')\n\n else:\n\n name = em.get_entity()\n\n\n try:\n\n s = qa.build_search(index='artists')\n id = s.filter(name=name).execute()[0]['id']\n\n print('Ohne Entity ELSE artist birthplace')\n\n artists = qa.get(index='artists', id=id)\n\n title = artists[0]['name']\n geburtsort = artists[0]['born_city_de']\n\n if (geburtsort == 'not available'):\n responder.reply('Leider habe ich keine Informationen über den Geburtsort von ' + title + '.')\n else:\n # Respond\n responder.reply(title + ' wurde in ' + geburtsort + ' geboren.')\n\n except:\n\n response = 'Sorry, das habe ich nicht verstanden.'\n\n responder.reply(response)\n\n\n else:\n\n em.set_entity(entity[0]['text'])\n\n try:\n\n # Extract id from query\n id = request.entities[0]['value'][0]['id']\n\n print('Mit Entity ELSE artist birthplace')\n artists = qa.get(index='artists', id=id)\n\n title = artists[0]['name']\n geburtsort = artists[0]['born_city_de']\n\n if (geburtsort == 'not available'):\n responder.reply('Leider habe ich keine Informationen über den Geburtsort von ' + title + '.')\n else:\n # Respond\n responder.reply(title + ' wurde in ' + geburtsort + ' geboren.')\n\n\n except:\n\n response = 'Sorry, das habe ich nicht verstanden.'\n\n responder.reply(response)\n\n\n\[email protected](intent='artist_age')\ndef say_artist_age(request, responder):\n \"\"\"\n When the user ends a conversation, clear the dialogue frame and say goodbye.\n \"\"\"\n # Clear the dialogue frame to start afresh for the next user request.\n responder.frame = {}\n\n\n entity = request.entities\n # name = request.entities[0]['text']\n\n if (entity == ()):\n\n\n if (em.get_entity() == ''):\n responder.reply('Von welchem Künstler möchstest du das Alter wissen?')\n print('Ohne entity IF artist birthyear: Von welchem Künstler möchstest du das Alter wissen?')\n\n else:\n\n name = em.get_entity()\n print('Name try else')\n print(name)\n\n\n try:\n\n s = qa.build_search(index='artists')\n id = s.filter(name=name).execute()[0]['id']\n\n artists = qa.get(index='artists', id=id)\n\n title = artists[0]['name']\n geburtjahr = artists[0]['born_year']\n todesjahr = artists[0]['died_year']\n\n from datetime import date\n heute = date.today()\n diesesJahr = heute.year\n\n if (geburtjahr == 'not available'):\n responder.reply('Leider habe ich keine Informationen zum Alter von ' + title + '.')\n else:\n if (todesjahr == 'not available'):\n alter = diesesJahr - int(geburtjahr)\n # Respond\n responder.reply(title + ' ist ' + str(alter) + ' alt.')\n\n else:\n alter = int(todesjahr) - int(geburtjahr)\n # Respond\n responder.reply(\n title + ' ist im Jahre ' + todesjahr + ' im Alter von ' + str(alter) + ' verstorben.')\n\n except:\n\n response = 'Sorry, das habe ich nicht verstanden.'\n\n responder.reply(response)\n\n\n\n\n else:\n em.set_entity(entity[0]['text'])\n\n try:\n\n # Extract id from query\n id = request.entities[0]['value'][0]['id']\n\n artists = qa.get(index='artists', id=id)\n\n title = artists[0]['name']\n geburtjahr = artists[0]['born_year']\n todesjahr = artists[0]['died_year']\n\n from datetime import date\n heute = date.today()\n diesesJahr = heute.year\n\n if (geburtjahr == 'not available'):\n responder.reply('Leider habe ich keine Informationen zum Alter von ' + title + '.')\n else:\n if (todesjahr == 'not available'):\n alter = diesesJahr - int(geburtjahr)\n # Respond\n responder.reply(title + ' ist ' + str(alter) + ' alt.')\n\n else:\n alter = int(todesjahr) - int(geburtjahr)\n # Respond\n responder.reply(title + ' ist im Jahre ' + todesjahr + ' im Alter von ' + str(alter) + ' verstorben.')\n\n except:\n\n response = 'Sorry, das habe ich nicht verstanden.'\n\n responder.reply(response)\n\n\n\[email protected](intent='openinghours')\ndef say_openinghours(request, responder):\n \"\"\"\n Telling the user when the ZKM is open.\n\n Returns:\n Nothing.\n \"\"\"\n em.set_entity('')\n\n text = request.text\n print(text)\n\n entity = request.entities\n\n if (entity == ()):\n responder.params.allowed_intents = ['zkm.openinghours'] #, 'basic.*']\n responder.reply('Von welchem Wochentag möchtest du die Öffnungszeiten wissen?')\n print(entity)\n\n else:\n print(entity)\n print(entity[0]['text'])\n\n\n if (entity[0]['text'] == 'heute'):\n print('HEUTE')\n s = qa.build_search(index='openinghours')\n id = s.filter(tag=heute_in_wochentag()).execute()[0]['id']\n\n openinghours = qa.get(index='openinghours', id=id)\n #day = openinghours[0]['tag']\n start = openinghours[0]['start']\n end = openinghours[0]['ende']\n # Respond\n if (start == \"geschlossen\"):\n response = 'Heute ist das ZKM geschlossen. 😢'\n else:\n response = 'Heute öffnet das ZKM um ' + start + ' Uhr und schließt um ' + end + ' Uhr.'\n\n responder.reply(response)\n\n\n elif (entity[0]['text'] == 'übermorgen'):\n print('ÜBERMORGEN')\n s = qa.build_search(index='openinghours')\n id = s.filter(tag=übermorgen_in_wochentag()).execute()[0]['id']\n\n openinghours = qa.get(index='openinghours', id=id)\n day = openinghours[0]['tag']\n start = openinghours[0]['start']\n end = openinghours[0]['ende']\n # Respond\n if (start == \"geschlossen\"):\n response = \"Am \" + day + ' ist das ZKM geschlossen. 😢'\n else:\n response = 'Am ' + day + ' öffnet das ZKM um ' + start + ' Uhr und schließt um ' + end + ' Uhr.'\n\n responder.reply(response)\n\n\n elif(entity[0]['text'] == 'morgen'):\n print('MORGEN')\n s = qa.build_search(index='openinghours')\n id = s.filter(tag=morgen_in_wochentag()).execute()[0]['id']\n\n openinghours = qa.get(index='openinghours', id=id)\n day = openinghours[0]['tag']\n start = openinghours[0]['start']\n end = openinghours[0]['ende']\n # Respond\n if (start == \"geschlossen\"):\n response = \"Am \" + day + ' ist das ZKM geschlossen. 😢'\n else:\n response = 'Am ' + day + ' öffnet das ZKM um ' + start + ' Uhr und schließt um ' + end + ' Uhr.'\n\n responder.reply(response)\n\n elif (hasNumbers(entity[0]['text'])):\n print('TEXT')\n s = qa.build_search(index='openinghours')\n\n if (datum_in_wochentag(entity[0]['text']) == 'null'):\n responder.params.allowed_intents = ['zkm.openinghours'] # , 'basic.*']\n responder.reply('Könntest du das Datum noch einmal im Zahlenformat eingeben, damit ich dir weiterhelfen kann?')\n else:\n id = s.filter(tag=datum_in_wochentag(entity[0]['text'])).execute()\n id = id[0]['id']\n\n openinghours = qa.get(index='openinghours', id=id)\n day = openinghours[0]['tag']\n start = openinghours[0]['start']\n end = openinghours[0]['ende']\n # Respond\n if (start == \"geschlossen\"):\n response = \"Am \" + day + ' den ' + entity[0]['text'] + ' ist das ZKM geschlossen. 😢'\n else:\n response = 'Am ' + day + ' den ' + entity[0]['text'] + ' öffnet das ZKM um ' + start + ' Uhr und schließt um ' + end + ' Uhr.'\n\n responder.reply(response)\n\n else:\n #Verarbeitung von Wochentagen\n print('Verarbeitung Wochentage')\n id = request.entities[0]['value'][0]['id']\n\n openinghours = qa.get(index='openinghours', id=id)\n day = openinghours[0]['tag']\n start = openinghours[0]['start']\n end = openinghours[0]['ende']\n # Respond\n if (start == \"geschlossen\"):\n response = \"Am \" + day + ' ist das ZKM geschlossen. 😢'\n else:\n response = 'Am ' + day + ' öffnet das ZKM um ' + start + ' Uhr und schließt um ' + end + ' Uhr.'\n\n responder.reply(response)\n\n\[email protected]_flow(domain='zkm', intent='exhibition_current')\ndef say_exhibition_current(request, responder):\n \"\"\"\n Telling the user what exhibitions are open at the moment.\n\n Returns:\n Nothing.\n \"\"\"\n\n em.set_entity('')\n # Clear the dialogue frame to start afresh for the next user request.\n\n text = request.text\n print(text)\n\n if (text == 'ZKM gerade Ausstellungen &+*bnbn?'):\n\n print('ausstellungzkmaktuell')\n exhibition = qa.get(index='exhibition', size=50, _sort='ende_tag', _sort_type='desc')\n\n ausstellung_offen = string_current_exhibitions(exhibition)\n\n #responder.reply('Ich habe Informationen über Ausstellungen des ZKMs, deren Zeitraum und Inhalte sowie die mitwirkenden Künstler für dich. Aktuell sind folgende Ausstellungen im ZKM zu sehen: ' + ausstellung_offen)\n responder.reply(ausstellung_offen)\n\n\n if (text == 'ZKM gerade Ausstellungen &+*bnbn??'):\n\n print('ZKM gerade Ausstellungen &+*bnbn??')\n exhibition = qa.get(index='exhibition', size=50, _sort='ende_tag', _sort_type='desc')\n\n artists = draw_ten_artists_from_current_exhibition(exhibition)\n\n #responder.reply('Ich habe Informationen über das Geburtsjahr, das Alter, den Geburtsort und über den allgemeinen Werdegang der jeweiligen Künstler. Diese zehn Künstler sind beispielsweise aktuell in unseren Ausstellungen zu sehen: ' + artists)\n responder.reply(artists)\n\n\n responder.frame = {}\n\n exhibition = qa.get(index='exhibition', size=50, _sort='ende_tag', _sort_type='desc')\n ausstellung_offen = string_current_exhibitions(exhibition)\n\n # Respond\n responder.reply('Folgende Ausstellungen sind aktuell geöffnet: ' + ausstellung_offen)\n responder.exit_flow()\n\n@say_exhibition_current.handle(default=True)\ndef default_handler(request, responder):\n\n \"\"\"\n Default dialog handler\n\n Returns:\n Nothing.\n \"\"\"\n\n responder.reply('Damit kann ich dir leider nicht weiterhelfen.')\n responder.exit_flow()\n\n@say_exhibition_current.handle(intent='exhibition_current')\ndef say_exhibition_current_in_flow_handler(request, responder):\n\n \"\"\"\n Dialog flow handler for current exhibitions.\n\n Returns:\n Nothing.\n \"\"\"\n\n say_exhibition_current(request, responder)\n\n\n#### intents from 'fun' domain ####\[email protected](intent='jokes')\ndef say_jokes(request, responder):\n \"\"\"\n Telling user jokes.\n\n Returns:\n Nothing.\n \"\"\"\n\n em.set_entity('')\n\n responder.frame = {}\n\n import random\n number = int(random.randint(1, 14))\n\n joke = qa.get(index='jokes', id=number)\n joke = joke[0]['joke']\n\n responder.reply(joke)\n\n\n#### intents from 'unknown' domain ####\n\[email protected](default=True)\[email protected](intent='unsupported')\ndef default(request, responder):\n \"\"\"\n When the user asks an unrelated question, convey the lack of understanding for the requested\n information and suggest an alternative.\n\n Returns:\n Nothing.\n \"\"\"\n em.set_entity('')\n\n query = request.text\n\n score = process.extractOne(query, suggestions[0])[1]\n suggestion = process.extractOne(query, suggestions[0])[0]\n\n if (score > 90):\n response = 'Sorry, das habe ich nicht verstanden, aber meintest du vielleicht: ' + suggestion\n else:\n response = 'Sorry, das habe ich nicht verstanden.'\n\n responder.reply(response)"
] |
[
[
"pandas.read_csv",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
gsajko/QLD_fuel_scraping
|
[
"325351adc958c5e490626cd37672e07ff4b00c47"
] |
[
"daily_scrape.py"
] |
[
"# %%\nimport os\nfrom datetime import datetime\n\nimport pandas as pd\nimport requests\n\n# %%\n# import json\n# auth_path: str = \"config/auth.json\"\n# auth = json.load(open(auth_path))\n# TOKEN = auth[\"token\"]\nTOKEN = os.environ[\"TOKEN\"]\nfileList = os.listdir(\"data/week/\")\nweek_of_year = datetime.now().strftime(\"%y_%V\")\n\n# %%\nif f\"{week_of_year}.csv\" in fileList:\n df = pd.read_csv(f\"data/week/{week_of_year}.csv\")\nelse:\n columns = [\n \"SiteId\",\n \"FuelId\",\n \"CollectionMethod\",\n \"TransactionDateUtc\",\n \"Price\",\n ]\n df = pd.DataFrame(columns=columns)\n\n# %%\nurl = \"https://fppdirectapi-prod.fuelpricesqld.com.au/Price/GetSitesPrices?countryId=21&geoRegionLevel=3&geoRegionId=1\"\n\npayload = {}\nheaders = {\n \"Authorization\": f\"FPDAPI SubscriberToken={TOKEN}\",\n \"Content-Type\": \"application/json\",\n}\n\nresponse = requests.request(\"GET\", url, headers=headers, data=payload)\nif response.status_code == 200:\n print(response)\nelse:\n print(response)\n print(response.reason)\n# %%\ndf_scraped = pd.DataFrame(response.json()[\"SitePrices\"])\n# check what month it is\n# %%\n\n# %%\ndf = df.append(df_scraped, sort=False)\n# %%\ndf.drop_duplicates(inplace=True)\n# %%\ndf.to_csv(f\"data/week/{week_of_year}.csv\", index=False)\n\n# %%\n"
] |
[
[
"pandas.read_csv",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
Husky22/threeML
|
[
"2ef3401e3edf82ceffd85ad0a9ea9e8b2bba3520",
"2ef3401e3edf82ceffd85ad0a9ea9e8b2bba3520"
] |
[
"threeML/minimizer/pagmo_minimizer.py",
"threeML/utils/statistics/likelihood_functions.py"
] |
[
"from __future__ import print_function\nfrom builtins import range\nfrom builtins import object\nimport numpy as np\nimport os\nfrom threeML.minimizer.minimization import GlobalMinimizer\nfrom threeML.io.progress_bar import progress_bar\nfrom threeML.parallel.parallel_client import is_parallel_computation_active\n\nimport pygmo as pg\n\n\nclass PAGMOWrapper(object):\n\n def __init__(self, function, parameters, dim):\n\n self._dim_ = dim\n\n self._objective_function = function\n\n minima = []\n maxima = []\n\n for param, (cur_value, cur_delta, cur_min, cur_max) in parameters.items():\n\n if cur_min is None or cur_max is None:\n\n raise RuntimeError(\"In order to use the PAGMO minimizer, you have to provide a minimum and a \"\n \"maximum for all parameters in the model.\")\n\n minima.append(cur_min)\n maxima.append(cur_max)\n\n self._minima = minima\n self._maxima = maxima\n self._parameters = parameters\n\n def fitness(self, x):\n\n val = self._objective_function(*x)\n\n # Note that we return a tuple with one element only. In PyGMO the objective functions\n # return tuples so that multi-objective optimization is also possible.\n return (val,)\n\n def get_bounds(self):\n\n return (self._minima, self._maxima)\n\n def get_name(self):\n\n return \"JointLikelihood\"\n\n\nclass PAGMOMinimizer(GlobalMinimizer):\n\n valid_setup_keys = ('islands', 'population_size', 'evolution_cycles', 'second_minimization', 'algorithm')\n\n def __init__(self, function, parameters, verbosity=10, setup_dict=None):\n\n super(PAGMOMinimizer, self).__init__(function, parameters, verbosity, setup_dict)\n\n def _setup(self, user_setup_dict):\n\n if user_setup_dict is None:\n\n default_setup = {'islands': 8,\n 'population_size': self._Npar * 20,\n 'evolution_cycles': 1}\n\n self._setup_dict = default_setup\n\n else:\n\n assert 'algorithm' in user_setup_dict, \"You have to provide a pygmo.algorithm instance using \" \\\n \"the algorithm keyword\"\n\n algorithm_instance = user_setup_dict['algorithm']\n\n assert isinstance(algorithm_instance,\n pg.algorithm), \"The algorithm must be an instance of a PyGMO algorithm\"\n\n # We can assume that the setup has been already checked against the setup_keys\n for key in user_setup_dict:\n\n self._setup_dict[key] = user_setup_dict[key]\n\n # This cannot be part of a class, unfortunately, because of how PyGMO serialize objects\n\n def _minimize(self):\n\n # Gather the setup\n islands = self._setup_dict['islands']\n pop_size = self._setup_dict['population_size']\n evolution_cycles = self._setup_dict['evolution_cycles']\n\n # Print some info\n print(\"\\nPAGMO setup:\")\n print(\"------------\")\n print(\"- Number of islands: %i\" % islands)\n print(\"- Population size per island: %i\" % pop_size)\n print(\"- Evolutions cycles per island: %i\\n\" % evolution_cycles)\n\n Npar = len(self._internal_parameters)\n\n if is_parallel_computation_active():\n\n wrapper = PAGMOWrapper(function=self.function, parameters=self._internal_parameters, dim=Npar)\n\n # use the archipelago, which uses the ipyparallel computation\n\n archi = pg.archipelago(udi=pg.ipyparallel_island(), n=islands,\n algo=self._setup_dict['algorithm'], prob=wrapper, pop_size=pop_size)\n archi.wait()\n\n # Display some info\n print(\"\\nSetup before parallel execution:\")\n print(\"--------------------------------\\n\")\n print(archi)\n\n # Evolve populations on islands\n print(\"Evolving... (progress not available for parallel execution)\")\n\n # For some weird reason, ipyparallel looks for _winreg on Linux (where does\n # not exist, being a Windows module). Let's mock it with an empty module'\n mocked = False\n if os.path.exists(\"_winreg.py\") is False:\n\n with open(\"_winreg.py\", \"w+\") as f:\n\n f.write(\"pass\")\n\n mocked = True\n\n archi.evolve()\n\n # Wait for completion (evolve() is async)\n\n archi.wait_check()\n\n # Now remove _winreg.py if needed\n if mocked:\n\n os.remove(\"_winreg.py\")\n\n # Find best and worst islands\n\n fOpts = np.array([x[0] for x in archi.get_champions_f()])\n xOpts = archi.get_champions_x()\n\n else:\n\n # do not use ipyparallel. Evolve populations on islands serially\n\n wrapper = PAGMOWrapper(function=self.function, parameters=self._internal_parameters, dim=Npar)\n\n xOpts = []\n fOpts = np.zeros(islands)\n\n with progress_bar(iterations=islands, title=\"pygmo minimization\") as p:\n\n for island_id in range(islands):\n\n pop = pg.population(prob=wrapper, size=pop_size)\n\n for i in range(evolution_cycles):\n\n pop = self._setup_dict['algorithm'].evolve(pop)\n\n # Gather results\n\n xOpts.append(pop.champion_x)\n fOpts[island_id] = pop.champion_f[0]\n\n p.increase()\n\n # Find best and worst islands\n\n min_idx = fOpts.argmin()\n max_idx = fOpts.argmax()\n\n fOpt = fOpts[min_idx]\n fWorse = fOpts[max_idx]\n xOpt = np.array(xOpts)[min_idx]\n\n # Some information\n print(\"\\nSummary of evolution:\")\n print(\"---------------------\")\n print(\"Best population has minimum %.3f\" % (fOpt))\n print(\"Worst population has minimum %.3f\" % (fWorse))\n print(\"\")\n\n # Transform to numpy.array\n\n best_fit_values = np.array(xOpt)\n\n return best_fit_values, fOpt\n",
"from __future__ import division\nfrom past.utils import old_div\nimport numpy as np\nfrom threeML.plugins.gammaln import logfactorial\nfrom math import log\n\n\ndef regularized_log(vector):\n \"\"\"\n A function which is log(vector) where vector > 0, and zero otherwise.\n\n :param vector:\n :return:\n \"\"\"\n\n return np.where(vector > 0, np.log(vector), 0)\n\n\ndef xlogy(x, y):\n \"\"\"\n A function which is 0 if x is 0, and x * log(y) otherwise. This is to fix the fact that for a machine\n 0 * log(inf) is nan, instead of 0.\n\n :param x:\n :param y:\n :return:\n \"\"\"\n\n return np.where(x > 0, x * np.log(y), 0)\n\n\ndef poisson_log_likelihood_ideal_bkg(observed_counts, expected_bkg_counts, expected_model_counts):\n \"\"\"\n Poisson log-likelihood for the case where the background has no uncertainties:\n\n L = \\sum_{i=0}^{N}~o_i~\\log{(m_i + b_i)} - (m_i + b_i) - \\log{o_i!}\n\n :param observed_counts:\n :param expected_bkg_counts:\n :param expected_model_counts:\n :return: (log_like vector, background vector)\n \"\"\"\n\n # Model predicted counts\n # In this likelihood the background becomes part of the model, which means that\n # the uncertainty in the background is completely neglected\n\n predicted_counts = expected_bkg_counts + expected_model_counts\n\n log_likes = xlogy(observed_counts, predicted_counts) - predicted_counts - logfactorial(observed_counts)\n\n return log_likes, expected_bkg_counts\n\n\ndef poisson_observed_poisson_background_xs(observed_counts, background_counts, exposure_ratio, expected_model_counts):\n \"\"\"\n Profile log-likelihood for the case when the observed counts are Poisson distributed, and the background counts\n are Poisson distributed as well (typical for X-ray analysis with aperture photometry). This has been derived\n by Keith Arnaud (see the Xspec manual, Wstat statistic)\n \"\"\"\n\n # We follow Arnaud et al. (Xspec manual) in the computation, which means that at the end we need to multiply by\n # (-1) as he computes the -log(L), while we need log(L). Also, he multiplies -log(L) by 2 at the end to make it\n # converge to chisq^2. We don't do that to keep it a proper (profile) likelihood.\n\n # Compute the nuisance background parameter\n\n first_term = exposure_ratio * (observed_counts + background_counts) - (1 + exposure_ratio) * expected_model_counts\n second_term = np.sqrt(first_term ** 2 + 4 * exposure_ratio * (exposure_ratio + 1)\n * background_counts * expected_model_counts)\n\n background_nuisance_parameter = old_div((first_term + second_term), (2 * exposure_ratio * (exposure_ratio + 1)))\n\n first_term = expected_model_counts + (1 + exposure_ratio) * background_nuisance_parameter\n\n # we regularize the log so it will not give NaN if expected_model_counts and background_nuisance_parameter are both\n # zero. For any good model this should also mean observed_counts = 0, btw.\n\n second_term = - xlogy(observed_counts, expected_model_counts + exposure_ratio * background_nuisance_parameter)\n\n third_term = - xlogy(background_counts, background_nuisance_parameter)\n\n ppstat = 2 * (first_term + second_term + third_term)\n\n ppstat += 2 * (- observed_counts + xlogy(observed_counts, observed_counts)\n - background_counts + xlogy(background_counts, background_counts))\n\n # assert np.isfinite(ppstat).all()\n\n return ppstat * (-1)\n\n\ndef poisson_observed_poisson_background(observed_counts, background_counts, exposure_ratio, expected_model_counts):\n\n # TODO: check this with simulations\n\n # Just a name change to make writing formulas a little easier\n\n alpha = exposure_ratio\n b = background_counts\n o = observed_counts\n M = expected_model_counts\n\n # Nuisance parameter for Poisson likelihood\n # NOTE: B_mle is zero when b is zero!\n\n sqr = np.sqrt(4 * (alpha + alpha ** 2) * b * M + ((alpha + 1) * M - alpha * (o + b)) ** 2)\n\n B_mle = old_div(1, (2.0 * alpha * (1+alpha))) * (alpha * (o + b) - (alpha+1) * M + sqr)\n\n # Profile likelihood\n\n loglike = xlogy(o, alpha*B_mle + M) + xlogy(b, B_mle) - (alpha+1) * B_mle - M - \\\n logfactorial(b) - logfactorial(o)\n\n return loglike, B_mle * alpha\n\n\ndef poisson_observed_gaussian_background(observed_counts, background_counts, background_error, expected_model_counts):\n\n # This loglike assume Gaussian errors on the background and Poisson uncertainties on the\n # observed counts. It is a profile likelihood.\n\n MB = background_counts + expected_model_counts\n s2 = background_error ** 2 # type: np.ndarray\n\n b = 0.5 * (np.sqrt(MB ** 2 - 2 * s2 * (MB - 2 * observed_counts) + background_error ** 4)\n + background_counts - expected_model_counts - s2) # type: np.ndarray\n\n # Now there are two branches: when the background is 0 we are in the normal situation of a pure\n # Poisson likelihood, while when the background is not zero we use the profile likelihood\n\n # NOTE: bkgErr can be 0 only when also bkgCounts = 0\n # Also it is evident from the expression above that when bkgCounts = 0 and bkgErr=0 also b=0\n\n # Let's do the branch with background > 0 first\n\n idx = background_counts > 0\n\n log_likes = np.empty_like(expected_model_counts)\n\n log_likes[idx] = (old_div(-(b[idx] - background_counts[idx]) ** 2, (2 * s2[idx]))\n + observed_counts[idx] * np.log(b[idx] + expected_model_counts[idx])\n - b[idx] - expected_model_counts[idx] - logfactorial(observed_counts[idx])\n - 0.5 * log(2 * np.pi) - np.log(background_error[idx]))\n\n # Let's do the other branch\n\n nidx = ~idx\n\n # the 1e-100 in the log is to avoid zero divisions\n # This is the Poisson likelihood with no background\n log_likes[nidx] = xlogy(observed_counts[nidx], expected_model_counts[nidx]) - \\\n expected_model_counts[nidx] - logfactorial(observed_counts[nidx])\n\n return log_likes, b\n\n\ndef half_chi2(y, yerr, expectation):\n\n # This is half of a chi2. The reason for the factor of two is that we need this to be the Gaussian likelihood,\n # so that the delta log-like for an error of say 1 sigma is 0.5 and not 1 like it would be for\n # the other likelihood functions. This way we can sum it with other likelihood functions.\n\n return old_div(1/2.0 * (y-expectation)**2, yerr**2)\n"
] |
[
[
"numpy.array",
"numpy.zeros"
],
[
"numpy.empty_like",
"numpy.log",
"numpy.sqrt"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
srt19/manga-ocr
|
[
"1eb03fd542496eeeac07deb2d88a1fa41850cd7b"
] |
[
"manga_ocr_dev/synthetic_data_generator/run_generate.py"
] |
[
"import traceback\nfrom pathlib import Path\n\nimport cv2\nimport fire\nimport pandas as pd\nfrom tqdm.contrib.concurrent import thread_map\n\nfrom manga_ocr_dev.env import FONTS_ROOT, DATA_SYNTHETIC_ROOT\nfrom manga_ocr_dev.synthetic_data_generator.generator import SyntheticDataGenerator\n\ngenerator = SyntheticDataGenerator()\n\n\ndef f(args):\n try:\n i, source, id_, text = args\n filename = f'{id_}.jpg'\n img, text_gt, params = generator.process(text)\n\n cv2.imwrite(str(OUT_DIR / filename), img)\n\n font_path = Path(params['font_path']).relative_to(FONTS_ROOT)\n ret = source, id_, text_gt, params['vertical'], str(font_path)\n return ret\n\n except Exception as e:\n print(traceback.format_exc())\n\n\ndef run(package=0, n_random=1000, n_limit=None, max_workers=16):\n \"\"\"\n :param package: number of data package to generate\n :param n_random: how many samples with random text to generate\n :param n_limit: limit number of generated samples (for debugging)\n :param max_workers: max number of workers\n \"\"\"\n\n package = f'{package:04d}'\n lines = pd.read_csv(DATA_SYNTHETIC_ROOT / f'lines/{package}.csv')\n random_lines = pd.DataFrame({\n 'source': 'random',\n 'id': [f'random_{package}_{i}' for i in range(n_random)],\n 'line': None\n })\n lines = pd.concat([lines, random_lines], ignore_index=True)\n if n_limit:\n lines = lines.sample(n_limit)\n args = [(i, *values) for i, values in enumerate(lines.values)]\n\n global OUT_DIR\n OUT_DIR = DATA_SYNTHETIC_ROOT / 'img' / package\n OUT_DIR.mkdir(parents=True, exist_ok=True)\n\n data = thread_map(f, args, max_workers=max_workers, desc=f'Processing package {package}')\n\n data = pd.DataFrame(data, columns=['source', 'id', 'text', 'vertical', 'font_path'])\n meta_path = DATA_SYNTHETIC_ROOT / f'meta/{package}.csv'\n meta_path.parent.mkdir(parents=True, exist_ok=True)\n data.to_csv(meta_path, index=False)\n\n\nif __name__ == '__main__':\n fire.Fire(run)\n"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.