repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
durham-abric/RoadDetector
|
[
"634b21384000abc5223d63f6030c6976263a204c"
] |
[
"src/skeleton.py"
] |
[
"from skimage.morphology import skeletonize, remove_small_objects, remove_small_holes\r\nfrom skimage import io\r\nimport numpy as np\r\nfrom matplotlib.pylab import plt\r\nimport cv2\r\nfrom other_tools import sknw\r\nimport os\r\nimport pandas as pd\r\nfrom functools import partial\r\nfrom itertools import tee\r\nfrom scipy.spatial.distance import pdist, squareform\r\nfrom scipy import ndimage as ndi\r\nfrom collections import defaultdict, OrderedDict\r\nimport sys\r\n\r\nfrom multiprocessing import Pool\r\n\r\ndef pairwise(iterable):\r\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\r\n a, b = tee(iterable)\r\n next(b, None)\r\n return zip(a, b)\r\n\r\ndef remove_sequential_duplicates(seq):\r\n #todo\r\n res = [seq[0]]\r\n for elem in seq[1:]:\r\n if elem == res[-1]:\r\n continue\r\n res.append(elem)\r\n return res\r\n\r\ndef remove_duplicate_segments(seq):\r\n seq = remove_sequential_duplicates(seq)\r\n segments = set()\r\n split_seg = []\r\n res = []\r\n for idx, (s, e) in enumerate(pairwise(seq)):\r\n if (s, e) not in segments and (e, s) not in segments:\r\n segments.add((s, e))\r\n segments.add((e, s))\r\n else:\r\n split_seg.append(idx+1)\r\n for idx, v in enumerate(split_seg):\r\n if idx == 0:\r\n res.append(seq[:v])\r\n if idx == len(split_seg) - 1:\r\n res.append(seq[v:])\r\n else:\r\n s = seq[split_seg[idx-1]:v]\r\n if len(s) > 1:\r\n res.append(s)\r\n if not len(split_seg):\r\n res.append(seq)\r\n return res\r\n\r\n\r\ndef flatten(l):\r\n return [item for sublist in l for item in sublist]\r\n\r\n\r\ndef get_angle(p0, p1=np.array([0,0]), p2=None):\r\n \"\"\" compute angle (in degrees) for p0p1p2 corner\r\n Inputs:\r\n p0,p1,p2 - points in the form of [x,y]\r\n \"\"\"\r\n if p2 is None:\r\n p2 = p1 + np.array([1, 0])\r\n v0 = np.array(p0) - np.array(p1)\r\n v1 = np.array(p2) - np.array(p1)\r\n\r\n angle = np.math.atan2(np.linalg.det([v0,v1]),np.dot(v0,v1))\r\n return np.degrees(angle)\r\n\r\ndef preprocess(img, thresh):\r\n img = (img > (255 * thresh)).astype(np.bool)\r\n remove_small_objects(img, 300, in_place=True)\r\n remove_small_holes(img, 300, in_place=True)\r\n # img = cv2.dilate(img.astype(np.uint8), np.ones((7, 7)))\r\n return img\r\n\r\ndef graph2lines(G):\r\n node_lines = []\r\n edges = list(G.edges())\r\n if len(edges) < 1:\r\n return []\r\n prev_e = edges[0][1]\r\n current_line = list(edges[0])\r\n added_edges = {edges[0]}\r\n for s, e in edges[1:]:\r\n if (s, e) in added_edges:\r\n continue\r\n if s == prev_e:\r\n current_line.append(e)\r\n else:\r\n node_lines.append(current_line)\r\n current_line = [s, e]\r\n added_edges.add((s, e))\r\n prev_e = e\r\n if current_line:\r\n node_lines.append(current_line)\r\n return node_lines\r\n\r\n\r\ndef visualize(img, G, vertices, fn):\r\n plt.imshow(img)\r\n\r\n # draw edges by pts\r\n for (s, e) in G.edges():\r\n vals = flatten([[v] for v in G[s][e].values()])\r\n for val in vals:\r\n ps = val.get('pts', [])\r\n plt.plot(ps[:, 1], ps[:, 0], 'green')\r\n\r\n # draw node by o\r\n #node, nodes = G.node(), G.nodes\r\n # deg = G.degree\r\n # ps = np.array([node[i]['o'] for i in nodes])\r\n ps = np.array(vertices)\r\n plt.plot(ps[:, 1], ps[:, 0], 'r.')\r\n\r\n # title and show\r\n img_name = fn.split('.')[0] + \".png\"\r\n map_name = fn.split('.')[0] + \"_roads.png\"\r\n io.imsave(img_name, img)\r\n plt.savefig(map_name)\r\n\r\ndef line_points_dist(line1, pts):\r\n return np.cross(line1[1] - line1[0], pts - line1[0]) / np.linalg.norm(line1[1] - line1[0])\r\n\r\ndef remove_small_terminal(G):\r\n deg = G.degree()\r\n terminal_points = [i for i, d in deg if d == 1]\r\n edges = list(G.edges())\r\n for s, e in edges:\r\n if s == e:\r\n sum_len = 0\r\n vals = flatten([[v] for v in G[s][s].values()])\r\n for ix, val in enumerate(vals):\r\n sum_len += len(val['pts'])\r\n if sum_len < 3:\r\n G.remove_edge(s, e)\r\n continue\r\n vals = flatten([[v] for v in G[s][e].values()])\r\n for ix, val in enumerate(vals):\r\n if s in terminal_points and val.get('weight', 0) < 10:\r\n G.remove_node(s)\r\n if e in terminal_points and val.get('weight', 0) < 10:\r\n G.remove_node(e)\r\n return\r\n\r\n\r\nlinestring = \"LINESTRING {}\"\r\ndef make_skeleton(root, fn, debug, threshes, fix_borders):\r\n replicate = 5\r\n clip = 2\r\n rec = replicate + clip\r\n # open and skeletonize\r\n img_path = os.path.join(root, fn)\r\n img = io.imread(img_path)\r\n assert img.shape == (1300, 1300)\r\n if fix_borders:\r\n img = cv2.copyMakeBorder(img, replicate, replicate, replicate, replicate, cv2.BORDER_REPLICATE)\r\n img_copy = None\r\n if debug:\r\n if fix_borders:\r\n img_copy = np.copy(img[replicate:-replicate,replicate:-replicate])\r\n else:\r\n img_copy = np.copy(img)\r\n thresh = threshes[fn[4]]\r\n img = preprocess(img, thresh)\r\n if not np.any(img):\r\n return None, None\r\n ske = skeletonize(img).astype(np.uint16)\r\n if fix_borders:\r\n ske = ske[rec:-rec, rec:-rec]\r\n ske = cv2.copyMakeBorder(ske, clip, clip, clip, clip, cv2.BORDER_CONSTANT, value=0)\r\n return img_copy, ske\r\n\r\n\r\ndef add_small_segments(G, terminal_points, terminal_lines):\r\n node = G.nodes\r\n term = [node[t]['o'] for t in terminal_points]\r\n dists = squareform(pdist(term))\r\n possible = np.argwhere((dists > 0) & (dists < 20))\r\n good_pairs = []\r\n for s, e in possible:\r\n if s > e:\r\n continue\r\n s, e = terminal_points[s], terminal_points[e]\r\n\r\n if G.has_edge(s, e):\r\n continue\r\n good_pairs.append((s, e))\r\n\r\n possible2 = np.argwhere((dists > 20) & (dists < 100))\r\n for s, e in possible2:\r\n if s > e:\r\n continue\r\n s, e = terminal_points[s], terminal_points[e]\r\n if G.has_edge(s, e):\r\n continue\r\n l1 = terminal_lines[s]\r\n l2 = terminal_lines[e]\r\n d = line_points_dist(l1, l2[0])\r\n\r\n if abs(d) > 20:\r\n continue\r\n angle = get_angle(l1[1] - l1[0], np.array((0, 0)), l2[1] - l2[0])\r\n if -20 < angle < 20 or angle < -160 or angle > 160:\r\n good_pairs.append((s, e))\r\n\r\n dists = {}\r\n for s, e in good_pairs:\r\n s_d, e_d = [G.nodes[s]['o'], G.nodes[e]['o']]\r\n dists[(s, e)] = np.linalg.norm(s_d - e_d)\r\n\r\n dists = OrderedDict(sorted(dists.items(), key=lambda x: x[1]))\r\n\r\n wkt = []\r\n added = set()\r\n for s, e in dists.keys():\r\n if s not in added and e not in added:\r\n added.add(s)\r\n added.add(e)\r\n s_d, e_d = G.nodes[s]['o'], G.nodes[e]['o']\r\n line_strings = [\"{1:.1f} {0:.1f}\".format(*c.tolist()) for c in [s_d, e_d]]\r\n line = '(' + \", \".join(line_strings) + ')'\r\n wkt.append(linestring.format(line))\r\n return wkt\r\n\r\n\r\ndef add_direction_change_nodes(pts, s, e, s_coord, e_coord):\r\n if len(pts) > 3:\r\n ps = pts.reshape(pts.shape[0], 1, 2).astype(np.int32)\r\n approx = 2\r\n ps = cv2.approxPolyDP(ps, approx, False)\r\n ps = np.squeeze(ps, 1)\r\n st_dist = np.linalg.norm(ps[0] - s_coord)\r\n en_dist = np.linalg.norm(ps[-1] - s_coord)\r\n if st_dist > en_dist:\r\n s, e = e, s\r\n s_coord, e_coord = e_coord, s_coord\r\n ps[0] = s_coord\r\n ps[-1] = e_coord\r\n else:\r\n ps = np.array([s_coord, e_coord], dtype=np.int32)\r\n return ps\r\n\r\n\r\ndef build_graph(root, fn, debug=True, threshes={'2': .3, '3': .3, '4': .3, '5': .2}, add_small=True, fix_borders=True):\r\n city = os.path.splitext(fn)[0][5:]\r\n img_copy, ske = make_skeleton(root, fn, debug, threshes, fix_borders)\r\n if ske is None:\r\n return city, [linestring.format(\"EMPTY\")]\r\n G = sknw.build_sknw(ske, multi=True)\r\n remove_small_terminal(G)\r\n node_lines = graph2lines(G)\r\n if not node_lines:\r\n return city, [linestring.format(\"EMPTY\")]\r\n node = G.nodes\r\n deg = G.degree()\r\n wkt = []\r\n terminal_points = [i for i, d in deg if d == 1]\r\n\r\n terminal_lines = {}\r\n vertices = []\r\n for w in node_lines:\r\n coord_list = []\r\n additional_paths = []\r\n for s, e in pairwise(w):\r\n vals = flatten([[v] for v in G[s][e].values()])\r\n for ix, val in enumerate(vals):\r\n\r\n s_coord, e_coord = node[s]['o'], node[e]['o']\r\n pts = val.get('pts', [])\r\n if s in terminal_points:\r\n terminal_lines[s] = (s_coord, e_coord)\r\n if e in terminal_points:\r\n terminal_lines[e] = (e_coord, s_coord)\r\n\r\n ps = add_direction_change_nodes(pts, s, e, s_coord, e_coord)\r\n\r\n if len(ps.shape) < 2 or len(ps) < 2:\r\n continue\r\n\r\n if len(ps) == 2 and np.all(ps[0] == ps[1]):\r\n continue\r\n\r\n line_strings = [\"{1:.1f} {0:.1f}\".format(*c.tolist()) for c in ps]\r\n if ix == 0:\r\n coord_list.extend(line_strings)\r\n else:\r\n additional_paths.append(line_strings)\r\n\r\n vertices.append(ps)\r\n\r\n if not len(coord_list):\r\n continue\r\n segments = remove_duplicate_segments(coord_list)\r\n for coord_list in segments:\r\n if len(coord_list) > 1:\r\n line = '(' + \", \".join(coord_list) + ')'\r\n wkt.append(linestring.format(line))\r\n for line_strings in additional_paths:\r\n line = \", \".join(line_strings)\r\n line_rev = \", \".join(reversed(line_strings))\r\n for s in wkt:\r\n if line in s or line_rev in s:\r\n break\r\n else:\r\n wkt.append(linestring.format('(' + line + ')'))\r\n\r\n if add_small and len(terminal_points) > 1:\r\n wkt.extend(add_small_segments(G, terminal_points, terminal_lines))\r\n\r\n if debug:\r\n vertices = flatten(vertices)\r\n visualize(img_copy, G, vertices, fn)\r\n\r\n if not wkt:\r\n return city, [linestring.format(\"EMPTY\")]\r\n return city, wkt\r\n\r\nif __name__ == \"__main__\":\r\n prefix = 'AOI'\r\n results_root = r'/results'\r\n # results_root = r'd:\\tmp\\roads\\albu\\results\\results'\r\n # root = os.path.join(results_root, r'results\\2m_4fold_512_30e_d0.2_g0.2')\r\n root = os.path.join(results_root, r'2m_4fold_512_30e_d0.2_g0.2_test', 'merged')\r\n f = partial(build_graph, root)\r\n l = [v for v in os.listdir(root) if prefix in v]\r\n l = list(sorted(l))\r\n with Pool() as p:\r\n data = p.map(f, l)\r\n all_data = []\r\n for k, v in data:\r\n for val in v:\r\n all_data.append((k, val))\r\n df = pd.DataFrame(all_data, columns=['ImageId', 'WKT_Pix'])\r\n df.to_csv(sys.argv[1] + '.txt', index=False)\r\n"
] |
[
[
"numpy.array",
"numpy.dot",
"numpy.linalg.norm",
"scipy.spatial.distance.pdist",
"numpy.squeeze",
"pandas.DataFrame",
"numpy.copy",
"matplotlib.pylab.plt.savefig",
"numpy.linalg.det",
"numpy.degrees",
"numpy.any",
"matplotlib.pylab.plt.imshow",
"numpy.argwhere",
"numpy.all",
"numpy.cross",
"matplotlib.pylab.plt.plot"
]
] |
mskimm/sparkannoy
|
[
"76f82c5e41fd8ca1d5c186c96437dd8368ead261"
] |
[
"data/dump.py"
] |
[
"import sys\nimport h5py\nimport numpy as np\n\ntrain = h5py.File(sys.argv[1], 'r')['train']\narr = np.array(train, dtype='f4')\n\nwith open('../data/annoy/sample-glove-25-angular.txt', 'w') as f:\n for i, sample in enumerate(arr[:1000]):\n f.write(str(i) + '\\t' + ','.join([str(x) for x in sample]) + '\\n')\n\n# used big-endian for Java\nwith open('train.bin', 'wb') as f:\n np.array(train.shape, dtype='int32').astype('>i4').tofile(f)\n arr.astype('>f4').tofile(f)\n"
] |
[
[
"numpy.array"
]
] |
v-liuwei/USTC2020-
|
[
"0ec4cf48cbd42a3cd71f8ed7c27201beaee19a8e"
] |
[
"Lab1-Logistic_Regression/src/main.py"
] |
[
"import numpy as np\nfrom model import LogisticRegression\n\n\n# load data\nx_train = np.load('./data/LR/train_data.npy')[:, 1:]\ny_train = np.load('./data/LR/train_target.npy')\nx_test = np.load('./data/LR/test_data.npy')[:, 1:]\ny_test = np.load('./data/LR/test_target.npy')\n\n# create an LR model and fit it\nlr = LogisticRegression(learning_rate=1, max_iter=10, fit_bias=True, optimizer='Newton', seed=0)\nlr.fit(x_train, y_train, val_data=(x_test, y_test))\n\n# predict and calculate acc\ntrain_acc = lr.score(x_train, y_train, metric='acc')\ntest_acc = lr.score(x_test, y_test, metric='acc')\nprint(\"train acc = {0}\".format(train_acc))\nprint(\"test acc = {0}\".format(test_acc))\n\n# plot learning curve and decision boundary\nlr.plot_learning_curve()\nlr.plot_boundary(x_train, y_train)\nlr.plot_boundary(x_test, y_test)\n"
] |
[
[
"numpy.load"
]
] |
J535D165/asreview-wordcloud
|
[
"01aba8680f469455ab70dd27965f0507e38fbd7d"
] |
[
"asreviewcontrib/wordcloud/entrypoint.py"
] |
[
"# Copyright 2020 The ASReview 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\nimport argparse\n\nimport matplotlib.pyplot as plt\nfrom wordcloud import STOPWORDS\nfrom wordcloud import WordCloud\n\nfrom asreview.entry_points import BaseEntryPoint\nfrom asreview.data import ASReviewData\n\ntry:\n from asreview.data import load_data\nexcept ImportError:\n\n # backwards compat\n try:\n from pathlib import Path\n from asreview.utils import is_url\n from asreview.datasets import DatasetManager\n from asreview.datasets import DataSetNotFoundError\n\n def load_data(name, *args, **kwargs):\n \"\"\"Load data from file, URL, or plugin.\n\n Parameters\n ----------\n name: str, pathlib.Path\n File path, URL, or alias of extension dataset.\n\n Returns\n -------\n asreview.ASReviewData:\n Inititalized ASReview data object.\n \"\"\"\n\n # check is file or URL\n if Path(name).exists() or is_url(name):\n return ASReviewData.from_file(name, *args, **kwargs)\n\n # check if dataset is plugin dataset\\\n try:\n dataset_path = DatasetManager().find(name).get()\n return ASReviewData.from_file(dataset_path, *args, **kwargs)\n except DataSetNotFoundError:\n pass\n\n # Could not find dataset, return None.\n raise FileNotFoundError(\n f\"File, URL, or dataset does not exist: '{name}'\")\n\n except ImportError:\n # fall back to from_file (without plugin datasets)\n load_data = ASReviewData.from_file\n\n\ndef extend_stopwords(extended_words):\n \"\"\"Add extra stopwords\"\"\"\n # create stopword list\n stopwords = set(STOPWORDS)\n stopwords.update(extended_words)\n\n return list(stopwords)\n\n\ndef word_cloud(words, caption=None, output_fp=None):\n \"\"\"Word cloud for texts.\"\"\"\n\n # create word cloud text\n text = \" \".join(str(word) for word in words)\n\n # generate word cloud images\n wordcloud = WordCloud(\n stopwords=STOPWORDS,\n max_words=100,\n background_color=\"white\"\n ).generate(text)\n\n # render plot\n plt.figure()\n plt.imshow(wordcloud, interpolation=\"bilinear\")\n if caption:\n plt.set_title(caption)\n plt.axis(\"off\")\n\n # save or show\n if output_fp:\n plt.savefig(output_fp, bbox_inches=\"tight\")\n else:\n plt.show()\n\n\nclass WordCloudEntryPoint(BaseEntryPoint):\n description = \"Wordcloud functionality for ASReview datasets.\"\n extension_name = \"asreview-wordcloud\"\n\n def __init__(self):\n from asreviewcontrib.wordcloud.__init__ import __version__\n super(WordCloudEntryPoint, self).__init__()\n\n self.version = __version__\n\n def execute(self, argv):\n parser = _parse_arguments(version=f\"{self.extension_name}: {self.version}\")\n args = parser.parse_args(argv)\n\n # read data in ASReview data object\n asdata = load_data(args.path)\n\n # all texts\n if (args.title and args.abstract) or (not args.title and not args.abstract):\n word_cloud(asdata.title, output_fp=args.output)\n\n # only title\n if args.title:\n word_cloud(asdata.title, output_fp=args.output)\n\n # only abstract\n if args.abstract:\n word_cloud(asdata.abstract, output_fp=args.output)\n\n\ndef _parse_arguments(version=\"Unknown\"):\n parser = argparse.ArgumentParser(prog=\"asreview wordcloud\")\n parser.add_argument(\"path\",\n type=str,\n help=\"The file path of the dataset.\")\n parser.add_argument(\n \"-V\",\n \"--version\",\n action=\"version\",\n version=version,\n )\n parser.add_argument(\n \"--title\",\n action=\"store_true\",\n help=\"Create wordcloud of titles only.\")\n parser.add_argument(\n \"--abstract\",\n action=\"store_true\",\n help=\"Create wordcloud of abstracts only.\")\n parser.add_argument(\n \"-o\",\n \"--output\",\n default=None,\n help=\"Save the wordcloud to a file.\")\n\n return parser\n"
] |
[
[
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.set_title",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.imshow"
]
] |
ukky17/ori_selectivity_CNN
|
[
"2c32d82c1331cb2a8767ed2de68060f1ac8acea5"
] |
[
"utils.py"
] |
[
"import numpy as np\n\nfrom keras.datasets import cifar10\nfrom keras.utils import to_categorical\n\ndef prepare_train_test():\n # load\n (x_train, y_train), (x_test, y_test) = cifar10.load_data()\n x_train = x_train.astype('float32')\n x_test = x_test.astype('float32')\n\n # standardization\n x_train /= 255\n x_test /= 255\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\n y_train_cat = to_categorical(y_train, 10)\n y_test_cat = to_categorical(y_test, 10)\n\n return x_train, x_test, y_train_cat, y_test_cat, x_train_mean\n"
] |
[
[
"numpy.mean"
]
] |
mshicom/Klampt
|
[
"79f983a790a0ac201af484ba64f68ebc21acc6c3"
] |
[
"Python/klampt/io/numpy_convert.py"
] |
[
"\"\"\"Conversions to and from Numpy objects; makes numerical computations much\nmore convenient.\n\"\"\"\n\nimport numpy as np\nfrom klampt.math import so3,se3\nfrom ..model import types\n\nsupportedTypes = set(['Vector3','Point','Matrix3','Rotation','RigidTransform',\n 'Config','Configs','Trajectory',\n 'TriangleMesh','PointCloud','VolumeGrid','Geometry3D' ])\n\"\"\"set of supported types for numpy I/O\"\"\"\n\ndef to_numpy(obj,type='auto'):\n \"\"\"Converts a Klamp't object to a numpy array or multiple numpy arrays.\n\n Supports:\n\n * lists and tuples\n * RigidTransform: returned as 4x4 homogeneous coordinate transform\n * Matrix3, Rotation: returned as 3x3 matrix. Can't be determined\n with 'auto', need to specify type='Matrix3' or 'Rotation'.\n * Configs\n * Trajectory: returns a pair (times,milestones)\n * TriangleMesh: returns a pair (verts,indices)\n * PointCloud: returns a n x (3+k) array, where k is the # of properties\n * VolumeGrid: returns a triple (bmin,bmax,array)\n * Geometry3D: returns a pair (T,geomdata)\n\n If you want to get a transformed point cloud or mesh, you can pass in a\n Geometry3D as the obj, and its geometry data type as the type.\n \"\"\"\n global supportedTypes \n if type == 'auto':\n otype = types.objectToTypes(obj)\n if isinstance(otype,(list,tuple)):\n for t in otype:\n if t in supportedTypes:\n type = t\n break\n if type == 'auto':\n raise ValueError('obj is not a supported type: '+', '.join(otype))\n else:\n type = otype\n if type not in supportedTypes:\n raise ValueError(type+' is not a supported type')\n if type == 'RigidTransform':\n return np.array(se3.homogeneous(obj))\n elif type == 'Rotation' or type == 'Matrix3':\n return np.array(so3.matrix(obj))\n elif type == 'Trajectory':\n return np.array(obj.times),np.array(obj.milestones)\n elif type == 'TriangleMesh':\n from klampt import Geometry3D\n if isinstance(obj,Geometry3D):\n res = to_numpy(obj.getTriangleMesh(),type)\n R = to_numpy(obj.getCurrentTransform()[0],'Matrix3')\n t = to_numpy(obj.getCurrentTransform()[1],'Vector3')\n return (np.dot(R,res[0])+t,res[1])\n return (np.array(obj.vertices).reshape((len(obj.vertices)//3,3)),np.array(obj.indices,dtype=np.int32).reshape((len(obj.indices)//3,3)))\n elif type == 'PointCloud':\n from klampt import Geometry3D\n if isinstance(obj,Geometry3D):\n res = to_numpy(obj.getPointCloud(),type)\n R = to_numpy(obj.getCurrentTransform()[0],'Matrix3')\n t = to_numpy(obj.getCurrentTransform()[1],'Vector3')\n res[:,:3] = np.dot(R,res[:,:3])+t\n return res\n points = np.array(obj.vertices).reshape((obj.numPoints(),3))\n if obj.numProperties() == 0:\n return points\n properties = np.array(obj.properties).reshape((obj.numPoints(),obj.numProperties()))\n return np.hstack((points,properties))\n elif type == 'VolumeGrid':\n bmin = np.array(obj.bbox)[:3]\n bmax = np.array(obj.bbox)[3:]\n values = np.array(obj.values).reshape((obj.dims[0],obj.dims[1],obj.dims[2]))\n return (bmin,bmax,values)\n elif type == 'Geometry3D':\n if obj.type() == 'PointCloud':\n return to_numpy(obj.getCurrentTransform(),'RigidTransform'),to_numpy(obj.getPointCloud(),obj.type())\n elif obj.type() == 'TriangleMesh':\n return to_numpy(obj.getCurrentTransform(),'RigidTransform'),to_numpy(obj.getTriangleMesh(),obj.type())\n elif obj.type() == 'VolumeGrid':\n return to_numpy(obj.getCurrentTransform(),'RigidTransform'),to_numpy(obj.getVolumeGrid(),obj.type())\n elif obj.type() == 'Group':\n arrays = []\n for i in range(obj.numElements()):\n arrays.append(to_numpy(obj.getElement(i),'Geometry3D'))\n return to_numpy(obj.getCurrentTransform(),'RigidTransform'),arrays\n else:\n return np.array(obj)\n\n\ndef from_numpy(obj,type='auto',template=None):\n \"\"\"Converts a numpy array or multiple numpy arrays to a Klamp't object.\n\n Supports:\n\n * lists and tuples\n * RigidTransform: accepts a 4x4 homogeneous coordinate transform\n * Matrix3, Rotation: accepts a 3x3 matrix.\n * Configs\n * Trajectory: accepts a pair (times,milestones)\n * TriangleMesh: accepts a pair (verts,indices)\n * PointCloud: accepts a n x (3+k) array, where k is the # of properties\n * VolumeGrid: accepts a triple (bmin,bmax,array)\n * Geometry3D: accepts a pair (T,geomdata)\n \"\"\"\n global supportedTypes \n if type == 'auto' and template is not None:\n otype = types.objectToTypes(template)\n if isinstance(otype,(list,tuple)):\n for t in otype:\n if t in supportedTypes:\n type = t\n break\n if type == 'auto':\n raise ValueError('obj is not a supported type: '+', '.join(otype))\n else:\n type = otype\n if type == 'auto':\n if isinstance(obj,(tuple,list)):\n if all(isinstance(v,np.ndarray) for v in obj):\n if len(obj)==2:\n if len(obj[0].shape) == 1 and len(obj[1].shape) == 2:\n type = 'Trajectory'\n elif len(obj[0].shape) == 2 and len(obj[1].shape) == 2 and obj[0].shape[1] == 3 and obj[1].shape[1] == 3:\n type = 'TriangleMesh'\n if len(obj)==3:\n if obj[0].shape == (3,) and obj[1].shape == (3,):\n type = 'VolumeGrid'\n if type == 'auto':\n raise ValueError(\"Can't auto-detect type of list of shapes\"+', '.join(str(v.shape) for v in obj))\n else:\n if isinstance(obj[0],np.ndarray) and obj[0].shape == (4,4):\n type = 'Geometry3D'\n else:\n raise ValueError(\"Can't auto-detect type of irregular list\")\n else:\n assert isinstance(obj,np.ndarray),\"Can only convert lists, tuples, and arrays from numpy\"\n if obj.shape == (3,3):\n type = 'Matrix3'\n elif obj.shape == (4,4):\n type = 'RigidTransform'\n elif len(obj.shape) == 1:\n type = 'Config'\n else:\n raise ValueError(\"Can't auto-detect type of matrix of shape \"+str(obj.shape))\n if type not in supportedTypes:\n raise ValueError(type+' is not a supported type')\n if type == 'RigidTransform':\n return se3.from_homogeneous(obj)\n elif type == 'Rotation' or type == 'Matrix3':\n return so3.from_matrix(obj)\n elif type == 'Trajectory':\n assert len(obj)==2,\"Trajectory format is (times,milestones)\"\n times = obj[0].tolist()\n milestones = obj[1].tolist()\n if template is not None:\n return template.constructor()(times,milestones)\n from klampt.model.trajectory import Trajectory\n return Trajectory(times,milestones)\n elif type == 'TriangleMesh':\n from klampt import TriangleMesh\n res = TriangleMesh()\n vflat = obj[0].flatten()\n res.vertices.resize(len(vflat))\n for i,v in enumerate(vflat):\n res.vertices[i] = float(v)\n iflat = obj[1].flatten()\n res.indices.resize(len(iflat))\n for i,v in enumerate(iflat):\n res.indices[i] = int(v)\n return res\n elif type == 'PointCloud':\n from klampt import PointCloud\n assert len(obj.shape) == 2,\"PointCloud array must be a 2D array\"\n assert obj.shape[1] >= 3,\"PointCloud array must have at least 3 values\"\n points = obj[:,:3]\n properties = obj[:,3:]\n res = PointCloud()\n res.setPoints(points.shape[0],points.flatten())\n if template is not None:\n if len(template.propertyNames) != properties.shape[1]:\n raise ValueError(\"Template object doesn't have the same properties as the numpy object\")\n res.propertyNames.resize(len(template.propertyNames))\n for i in range(len(template.propertyNames)):\n res.propertyNames[i] = template.propertyNames[i]\n else:\n for i in range(properties.shape[1]):\n res.propertyNames.append('property %d'%(i+1))\n if len(res.propertyNames) > 0:\n res.properties.resize(len(res.propertyNames)*points.shape[0])\n if obj.shape[1] >= 3:\n res.setProperties(properties.flatten())\n return res\n elif type == 'VolumeGrid':\n from klampt import VolumeGrid\n assert len(obj) == 3,\"VolumeGrid format is (bmin,bmax,values)\"\n assert len(obj[2].shape) == 3,\"VolumeGrid values must be a 3D array\"\n bmin = obj[0]\n bmax = obj[1]\n values = obj[2]\n res = VolumeGrid()\n res.bbox.append(bmin[0])\n res.bbox.append(bmin[1])\n res.bbox.append(bmin[2])\n res.bbox.append(bmax[0])\n res.bbox.append(bmax[1])\n res.bbox.append(bmax[2])\n res.dims.append(values.shape[0])\n res.dims.append(values.shape[1])\n res.dims.append(values.shape[2])\n vflat = values.flatten()\n res.values.resize(len(vflat))\n for i,v in enumerate(vflat):\n res.values[i] = v\n return res\n elif type == 'Group':\n from klampt import Geometry3D\n res = Geometry3D()\n assert isinstance(obj,(list,tuple)),\"Group format is a list or tuple of Geometry3D's\"\n for i in range(len(obj)):\n res.setElement(i,from_numpy(obj[i],'Geometry3D'))\n return res\n elif type == 'Geometry3D':\n from klampt import Geometry3D\n if not isinstance(obj,(list,tuple)) or len(obj) != 2:\n raise ValueError(\"Geometry3D must be a (transform,geometry) tuple\")\n T = from_numpy(obj[0],'RigidTransform')\n geomdata = obj[1]\n subtype = None\n if template is not None:\n subtype = template.type()\n if subtype == 'PointCloud':\n g = Geometry3D(from_numpy(geomdata,subtype,template.getPointCloud()))\n else:\n g = Geometry3D(from_numpy(geomdata,subtype))\n g.setCurrentTransform(*T)\n return g\n subtype = 'Group'\n if all(isinstance(v,np.ndarray) for v in geomdata):\n if len(geomdata)==2:\n if len(geomdata[0].shape) == 1 and len(geomdata[1].shape) == 2:\n subtype = 'Trajectory'\n elif len(geomdata[0].shape) == 2 and len(geomdata[1].shape) == 2 and geomdata[0].shape[1] == 3 and geomdata[1].shape[1] == 3:\n subtype = 'TriangleMesh'\n if len(geomdata)==3:\n if geomdata[0].shape == (3,) and geomdata[1].shape == (3,):\n subtype = 'VolumeGrid'\n g = Geometry3D(from_numpy(obj,subtype))\n g.setCurrentTransform(*T)\n return g\n else:\n return obj.flatten()\n"
] |
[
[
"numpy.hstack",
"numpy.array",
"numpy.dot"
]
] |
evgiz/variational-autoencoder
|
[
"61cec5d97c30580f073722be1ab4a0eae97067db"
] |
[
"util.py"
] |
[
"\"\"\"\nAuthor: Sigve Rokenes\nDate: February, 2019\n\nUtility functions for variational autoencoder\n\n\"\"\"\n\nimport skimage as sk\nfrom skimage import io\nimport tensorflow as tf\nimport numpy as np\n\n\n# ===================================== #\n# #\n# Utility Functions #\n# #\n# ===================================== #\n\ndef print_tensor(tensor, name):\n shape = tensor.get_shape()\n size = 1\n for dim in shape.as_list():\n if dim is not None:\n size *= int(dim)\n print(\"{:8} {:20} {:8}\".format(name, str(shape), str(size)))\n\n\ndef conv(source, filters, strides=2, kernel=3, activation=tf.nn.leaky_relu):\n return tf.layers.conv2d(source, filters, kernel,\n strides=strides, padding=\"same\", activation=activation)\n\n\ndef deconv(source, filters, strides=2, kernel=3, activation=tf.nn.leaky_relu):\n return tf.layers.conv2d_transpose(source, filters, kernel,\n strides=strides, padding=\"same\", activation=activation)\n\n\ndef gray2rgb(img):\n rgb = []\n for row in img:\n n_row = []\n for pix in row:\n if type(pix) is int:\n n_row.append([pix, pix, pix])\n else:\n value = np.mean(pix)\n n_row.append([value, value, value])\n rgb.append(n_row)\n return np.array(rgb)\n\n\ndef save_image(filename, img, resize=None):\n img = np.clip(np.array(img), 0, 1)\n if np.shape(img)[2] == 1:\n img = gray2rgb(img)\n if resize:\n img = sk.transform.resize(img, resize)\n sk.io.imsave(filename, img)\n"
] |
[
[
"numpy.array",
"numpy.mean",
"numpy.shape",
"tensorflow.layers.conv2d",
"tensorflow.layers.conv2d_transpose"
]
] |
Terfno/learn_DL
|
[
"0e1f3049c2c342915e1b7237506029a42539029e"
] |
[
"3/nn.py"
] |
[
"import numpy as np\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\ndef identity_function(x):\n return x\n\ndef init_network():\n network = {}\n\n network['W1'] = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])\n network['b1'] = np.array([0.1, 0.2, 0.3])\n network['W2'] = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]])\n network['b2'] = np.array([0.1, 0.2])\n network['W3'] = np.array([[0.1, 0.3], [0.2, 0.4]])\n network['b3'] = np.array([0.1, 0.2])\n\n return network\n\ndef forward(network, x):\n W1, W2, W3 = network['W1'], network['W2'], network['W3']\n b1, b2, b3 = network['b1'], network['b2'], network['b3']\n\n a1 = np.dot(x, W1) + b1\n z1 = sigmoid(a1)\n a2 = np.dot(z1, W2) + b2\n z2 = sigmoid(a2)\n a3 = np.dot(z2, W3) + b3\n y = identity_function(a3)\n\n return y\n\ndef main():\n network = init_network()\n x = np.array([1.0, 0.5])\n y = forward(network, x)\n print(y)\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.array",
"numpy.dot",
"numpy.exp"
]
] |
SiftScience/transformers
|
[
"fedfc9853c4d50ac06aa07fda5c28dc625f5c045"
] |
[
"transformers/data/processors/utils.py"
] |
[
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport csv\nimport sys\nimport copy\nimport json\nimport pandas as pd\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass InputExample(object):\n \"\"\"\n A single training/test example for simple sequence classification.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n def __init__(self, guid, text_a, text_b=None, label=None):\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n def __repr__(self):\n return str(self.to_json_string())\n\n def to_dict(self):\n \"\"\"Serializes this instance to a Python dictionary.\"\"\"\n output = copy.deepcopy(self.__dict__)\n return output\n\n def to_json_string(self):\n \"\"\"Serializes this instance to a JSON string.\"\"\"\n return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"\n\n\nclass InputFeatures(object):\n \"\"\"\n A single set of features of data.\n\n Args:\n input_ids: Indices of input sequence tokens in the vocabulary.\n attention_mask: Mask to avoid performing attention on padding token indices.\n Mask values selected in ``[0, 1]``:\n Usually ``1`` for tokens that are NOT MASKED, ``0`` for MASKED (padded) tokens.\n token_type_ids: Segment token indices to indicate first and second portions of the inputs.\n label: Label corresponding to the input\n \"\"\"\n\n def __init__(self, input_ids, attention_mask, token_type_ids, label):\n self.input_ids = input_ids\n self.attention_mask = attention_mask\n self.token_type_ids = token_type_ids\n self.label = label\n\n def __repr__(self):\n return str(self.to_json_string())\n\n def to_dict(self):\n \"\"\"Serializes this instance to a Python dictionary.\"\"\"\n output = copy.deepcopy(self.__dict__)\n return output\n\n def to_json_string(self):\n \"\"\"Serializes this instance to a JSON string.\"\"\"\n return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"\n\n\nclass DataProcessor(object):\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\n raise NotImplementedError()\n\n def get_dev_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\n raise NotImplementedError()\n\n def get_labels(self):\n \"\"\"Gets the list of labels for this data set.\"\"\"\n raise NotImplementedError()\n\n @classmethod\n def _read_tsv(cls, input_file, quotechar=None):\n \"\"\"Reads a tab separated value file.\"\"\"\n with open(input_file, \"r\", encoding=\"utf-8-sig\") as f:\n reader = csv.reader(f, delimiter=\"\\t\", quotechar=quotechar)\n lines = []\n for line in reader:\n if sys.version_info[0] == 2:\n line = list(unicode(cell, 'utf-8') for cell in line)\n lines.append(line)\n return lines\n \n @classmethod\n def _read_parquet(cls, input_file):\n \"\"\"Reads a parquet file\"\"\"\n logger.info(f'reading parquet file from {input_file}')\n df = pd.read_parquet(input_file)\n logger.info(f'done reading: {input_file}, rows read so far: {len(df)}')\n return df"
] |
[
[
"pandas.read_parquet"
]
] |
byooooo/dispersant_screening_PAL
|
[
"e25acc82c18db209fbf29046780ca31835f587d0"
] |
[
"work/wandb/run-20200807_173426-1hzb694b/code/work/gp_learning_curves.py"
] |
[
"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nimport os\n\nimport joblib\nimport numpy as np\nimport pandas as pd\nfrom six.moves import range\nfrom sklearn.feature_selection import VarianceThreshold\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nimport wandb\nfrom dispersant_screener.gp import (build_coregionalized_model, build_model, predict, predict_coregionalized)\nfrom dispersant_screener.utils import (add_postfix_to_keys, get_metrics, get_variance_descriptors, plot_parity)\n\nDATADIR = '../data'\nTRAIN_SIZES = [0.01, 0.1, 0.3, 0.5, 0.8]\nREPEAT = 10\n\ndf_full_factorial_feat = pd.read_csv(os.path.join(DATADIR, 'new_features_full_random.csv')).values\na2 = pd.read_csv(os.path.join(DATADIR, 'b1-b21_random_virial_large.csv'))['A2_normalized'].values\ngibbs = pd.read_csv(os.path.join(DATADIR, 'b1-b21_random_deltaG.csv'))['deltaGmin'].values\nrg = pd.read_csv(os.path.join(DATADIR, 'rg_results.csv'))['Rg'].values\ny = np.hstack([rg.reshape(-1, 1), gibbs.reshape(-1, 1)])\nassert len(df_full_factorial_feat) == len(a2) == len(gibbs) == len(y)\n\nMETRICS_COREGIONALIZED = []\nMETRICS_UNCORRELATED = []\n\n\ndef get_initial_split(df_full_factorial_feat, y):\n X_train, X_test, y_train, y_test = train_test_split(df_full_factorial_feat, y, train_size=0.8)\n\n vt = VarianceThreshold(0)\n X_train = vt.fit_transform(X_train)\n X_test = vt.transform(X_test)\n\n feat_scaler = StandardScaler()\n X_train = feat_scaler.fit_transform(X_train)\n X_test = feat_scaler.transform(X_test)\n\n return X_train, y_train, X_test, y_test\n\n\ndef make_new_split(X, y, train_size):\n return train_test_split(X, y, train_size=train_size)\n\n\ndef main():\n X_train_, y_train_, X_test, y_test = get_initial_split(df_full_factorial_feat, y)\n\n for train_size in TRAIN_SIZES:\n for i in range(REPEAT):\n X_train, _, y_train, _ = train_test_split(X_train_, y_train_, train_size=train_size)\n\n # Train coregionalized model\n wandb.init(project='dispersant_screener', tags=['coregionalized', 'matern32'], save_code=True)\n m = build_coregionalized_model(X_train, y_train)\n m.optimize()\n y0, var0 = predict_coregionalized(m, X_test, 0)\n y1, var1 = predict_coregionalized(m, X_test, 1)\n metrics_0 = get_metrics(y0, y_test[:, 0])\n metrics_0 = add_postfix_to_keys(metrics_0, 0)\n\n metrics_1 = get_metrics(y1, y_test[:, 1])\n metrics_1 = add_postfix_to_keys(metrics_0, 1)\n\n variance_0 = get_variance_descriptors(var0)\n variance_1 = get_variance_descriptors(var1)\n variance_0 = add_postfix_to_keys(variance_0, 0)\n variance_1 = add_postfix_to_keys(variance_1, 1)\n\n overall_metrics = metrics_0\n overall_metrics.update(metrics_1)\n overall_metrics.update(variance_0)\n overall_metrics.update(variance_1)\n overall_metrics['train_size'] = len(X_train)\n overall_metrics['coregionalized'] = True\n\n plot_parity(y0, y_test[:, 0], var0, y1, y_test[:, 1], var1,\n 'coregionalized_{}_{}.pdf'.format(len(X_train), i))\n wandb.log(overall_metrics)\n wandb.join()\n\n # Train \"simple models\"\n wandb.init(project='dispersant_screener', tags=['matern32'], save_code=True)\n m0 = build_model(X_train, y_train, 0)\n m0.optimize()\n m1 = build_model(X_train, y_train, 1)\n m1.optimize()\n\n y0, var0 = predict(m0, X_test)\n y1, var1 = predict(m1, X_test)\n metrics_0 = get_metrics(y0, y_test[:, 0])\n metrics_0 = add_postfix_to_keys(metrics_0, 0)\n\n metrics_1 = get_metrics(y1, y_test[:, 1])\n metrics_1 = add_postfix_to_keys(metrics_0, 1)\n\n variance_0 = get_variance_descriptors(var0)\n variance_1 = get_variance_descriptors(var1)\n variance_0 = add_postfix_to_keys(variance_0, 0)\n variance_1 = add_postfix_to_keys(variance_1, 1)\n\n overall_metrics = metrics_0\n overall_metrics.update(metrics_1)\n overall_metrics.update(variance_0)\n overall_metrics.update(variance_1)\n overall_metrics['train_size'] = len(X_train)\n overall_metrics['coregionalized'] = False\n\n plot_parity(y0, y_test[:, 0], var0, y1, y_test[:, 1], var1, 'simple_{}_{}.pdf'.format(len(X_train), i))\n\n wandb.log(overall_metrics)\n wandb.join()\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"sklearn.model_selection.train_test_split",
"sklearn.feature_selection.VarianceThreshold",
"sklearn.preprocessing.StandardScaler"
]
] |
Mario-Kart-Felix/nvae
|
[
"37b954977833198f2946830c68823b094cc00412"
] |
[
"nvae/dataset.py"
] |
[
"import os\nfrom glob import glob\n\nimport cv2\nimport h5py\nimport torch\nfrom torch.utils.data import Dataset\n\n\nclass ImageH5Dataset(Dataset):\n\n def __init__(self, dataset_path, img_dim):\n self.dataset_path = dataset_path\n self.img_dim = (img_dim, img_dim) if type(img_dim) == int else img_dim\n self.live_data = None\n self.images = None\n\n with h5py.File(self.dataset_path, 'r') as file:\n self.dataset_len = len(file[\"image\"])\n\n def __getitem__(self, idx):\n if self.live_data is None:\n self.live_data = h5py.File(self.dataset_path, 'r')\n self.images = self.live_data['image']\n\n image = self.images[idx]\n\n h, w, c = image.shape\n top_h = int((h - w) / 2)\n\n image = image[top_h:top_h + w]\n image = cv2.resize(image, self.img_dim, interpolation=cv2.INTER_LINEAR)\n image = image / 255.\n\n return torch.tensor(image, dtype=torch.float32).permute(2, 0, 1)\n\n def __len__(self):\n return self.dataset_len\n\n\nclass ImageFolderDataset(Dataset):\n\n def __init__(self, image_dir, img_dim):\n self.img_paths = glob(os.path.join(image_dir, \"*.jpg\"))\n self.img_dim = (img_dim, img_dim) if type(img_dim) == int else img_dim\n\n def __getitem__(self, idx):\n image = cv2.imread(self.img_paths[idx])\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n h, w, c = image.shape\n if h > w:\n top_h = int((h - w) / 2)\n image = image[top_h:top_h + w]\n else:\n left_w = int((w - h) / 2)\n image = image[:, left_w:left_w + h]\n image = cv2.resize(image, self.img_dim, interpolation=cv2.INTER_LINEAR)\n image = image / 255.\n\n return torch.tensor(image, dtype=torch.float32).permute(2, 0, 1)\n\n def __len__(self):\n return len(self.img_paths)\n"
] |
[
[
"torch.tensor"
]
] |
shadofren/deeposlandia
|
[
"3dcb511482aff9c62bffd383e92055920c7a7e85"
] |
[
"tests/test_generators.py"
] |
[
"\"\"\"Unit test related to the generator building and feeding\n\"\"\"\n\nimport pytest\n\nimport numpy as np\n\nfrom deeposlandia import generator, utils\n\n\ndef test_feature_detection_labelling_concise():\n \"\"\"Test `feature_detection_labelling` function in `generator` module by considering a concise\n labelling, *i.e.* all labels are represented into the array:\n * as a preliminary verification, check if passing string labels raises an AttributeError\n exception\n * test if output shape is first input shape (batch size) + an additional dimension given by the\n `label_ids` length\n * test if both representation provides the same information (native array on the first hand and\n its one-hot version on the second hand)\n \"\"\"\n a = np.array([[[[10, 10, 200], [10, 10, 200], [10, 10, 200]],\n [[200, 200, 200], [200, 200, 200], [10, 10, 200]],\n [[200, 200, 200], [200, 200, 200], [200, 200, 200]]],\n [[[10, 200, 10], [10, 200, 10], [10, 10, 200]],\n [[200, 10, 10], [10, 200, 10], [10, 10, 200]],\n [[10, 200, 10], [200, 10, 10], [10, 10, 200]]]])\n labels = np.unique(a.reshape(-1, 3), axis=0).tolist()\n wrong_config = [{'id': '0', 'color': [10, 10, 200], 'is_evaluate': True},\n {'id': '1', 'color': [200, 10, 10], 'is_evaluate': True},\n {'id': '2', 'color': [10, 200, 10], 'is_evaluate': True},\n {'id': '3', 'color': [200, 200, 200], 'is_evaluate': True}]\n with pytest.raises(ValueError):\n b = generator.feature_detection_labelling(a, wrong_config)\n config = [{'id': 0, 'color': [10, 10, 200], 'is_evaluate': True},\n {'id': 1, 'color': [200, 10, 10], 'is_evaluate': True},\n {'id': 2, 'color': [10, 200, 10], 'is_evaluate': True},\n {'id': 3, 'color': [200, 200, 200], 'is_evaluate': True}]\n b = generator.feature_detection_labelling(a, config)\n assert b.shape == (a.shape[0], len(labels))\n assert b.tolist() == [[True, False, False, True],\n [True, True, True, False]]\n\n\ndef test_feature_detection_labelling_sparse():\n \"\"\"Test `feature_detection_labelling` function in `generator` module by considering a sparse\n labelling, *i.e.* the array contains unknown values (to mimic the non-evaluated label\n situations):\n * as a preliminary verification, check if passing string labels raises an AttributeError\n exception\n * test if label length is different from the list of values in the array\n * test if output shape is first input shape (batch size) + an additional dimension given by the\n `label_ids` length\n * test if both representation provides the same information (native array on the first hand and\n its one-hot version on the second hand)\n \"\"\"\n a = np.array([[[[10, 10, 200], [10, 10, 200], [10, 10, 200], [200, 10, 10]],\n [[200, 200, 200], [200, 200, 200], [10, 10, 200], [200, 10, 10]],\n [[200, 200, 200], [200, 200, 200], [200, 200, 200], [10, 10, 200]],\n [[200, 200, 200], [200, 200, 200], [200, 200, 200], [10, 10, 200]]],\n [[[200, 10, 10], [200, 10, 10], [10, 200, 10], [200, 10, 10]],\n [[200, 200, 200], [10, 200, 10], [10, 200, 10], [10, 200, 10]],\n [[200, 10, 10], [200, 10, 10], [200, 10, 10], [200, 200, 200]],\n [[200, 10, 10], [200, 10, 10], [10, 200, 10], [200, 200, 200]]]])\n labels = np.unique(a.reshape(-1, 3), axis=0).tolist()[:-1]\n wrong_config = [{'id': '0', 'color': [10, 10, 200], 'is_evaluate': True},\n {'id': '1', 'color': [200, 10, 10], 'is_evaluate': True},\n {'id': '2', 'color': [10, 200, 10], 'is_evaluate': True}]\n with pytest.raises(ValueError):\n b = generator.feature_detection_labelling(a, wrong_config)\n config = [{'id': 0, 'color': [10, 10, 200], 'is_evaluate': True},\n {'id': 1, 'color': [200, 10, 10], 'is_evaluate': True},\n {'id': 2, 'color': [10, 200, 10], 'is_evaluate': True}]\n b = generator.feature_detection_labelling(a, config)\n assert len(labels) != np.amax(a) - np.amin(a) + 1\n assert b.tolist() == [[True, True, False],\n [False, True, True]]\n assert b.shape == (a.shape[0], len(labels))\n\n\ndef test_featdet_mapillary_generator(mapillary_image_size,\n mapillary_sample,\n mapillary_sample_config,\n nb_channels):\n \"\"\"Test the data generator for the Mapillary dataset\n \"\"\"\n BATCH_SIZE = 10\n config = utils.read_config(mapillary_sample_config)\n label_ids = [x['id'] for x in config[\"labels\"]]\n gen = generator.create_generator(\"mapillary\", \"feature_detection\",\n mapillary_sample,\n mapillary_image_size,\n BATCH_SIZE,\n config[\"labels\"])\n item = next(gen)\n assert(len(item)==2)\n im_shape = item[0].shape\n assert im_shape == (BATCH_SIZE, mapillary_image_size, mapillary_image_size, nb_channels)\n label_shape = item[1].shape\n assert label_shape == (BATCH_SIZE, len(label_ids))\n\n\ndef test_featdet_shape_generator(shapes_image_size, shapes_sample, shapes_sample_config, nb_channels):\n \"\"\"Test the data generator for the shape dataset\n \"\"\"\n BATCH_SIZE = 10\n config = utils.read_config(shapes_sample_config)\n label_ids = [x['id'] for x in config[\"labels\"]]\n gen = generator.create_generator(\"shapes\", \"feature_detection\", shapes_sample, shapes_image_size, BATCH_SIZE, config[\"labels\"])\n item = next(gen)\n assert len(item) == 2\n im_shape = item[0].shape\n assert im_shape == (BATCH_SIZE, shapes_image_size, shapes_image_size, nb_channels)\n label_shape = item[1].shape\n assert label_shape == (BATCH_SIZE, len(label_ids))\n\n\ndef test_semantic_segmentation_labelling_concise():\n \"\"\"Test `semantic_segmentation_labelling` function in `generator` module by considering a\n concise labelling, *i.e.* the labels correspond to array values\n * as a preliminary verification, check if passing string labels raises an AttributeError\n exception\n * test if output shape is input shape + an additional dimension given by the\n `label_ids` length\n * test if both representation provides the same information (native array on the\n first hand and its one-hot version on the second hand)\n\n \"\"\"\n a = np.array([[[[200, 10, 10], [200, 10, 10], [200, 200, 200]],\n [[200, 200, 200], [200, 200, 200], [200, 10, 10]],\n [[200, 200, 200], [200, 200, 200], [200, 200, 200]]],\n [[[200, 10, 10], [200, 10, 10], [10, 10, 200]],\n [[10, 200, 10], [10, 200, 10], [10, 10, 200]],\n [[200, 10, 10], [200, 10, 10], [10, 10, 200]]]])\n labels = np.unique(a.reshape(-1, 3), axis=0).tolist()\n wrong_config = [{'id': '0', 'color': [10, 10, 200], 'is_evaluate': True},\n {'id': '1', 'color': [200, 10, 10], 'is_evaluate': True},\n {'id': '2', 'color': [10, 200, 10], 'is_evaluate': True},\n {'id': '3', 'color': [200, 200, 200], 'is_evaluate': True}]\n asum, _ = np.histogram(a.reshape(-1), range=(np.amin(a), np.amax(a)))\n with pytest.raises(ValueError):\n b = generator.semantic_segmentation_labelling(a, wrong_config)\n config = [{'id': 0, 'color': [10, 10, 200], 'is_evaluate': True},\n {'id': 1, 'color': [200, 10, 10], 'is_evaluate': True},\n {'id': 2, 'color': [10, 200, 10], 'is_evaluate': True},\n {'id': 3, 'color': [200, 200, 200], 'is_evaluate': True}]\n b = generator.semantic_segmentation_labelling(a, config)\n assert b.shape == (a.shape[0], a.shape[1], a.shape[2], len(labels))\n assert b.tolist() == [[[[False, True, False, False],\n [False, True, False, False],\n [False, False, False, True]],\n [[False, False, False, True],\n [False, False, False, True],\n [False, True, False, False]],\n [[False, False, False, True],\n [False, False, False, True],\n [False, False, False, True]]],\n [[[False, True, False, False],\n [False, True, False, False],\n [True, False, False, False]],\n [[False, False, True, False],\n [False, False, True, False],\n [True, False, False, False]],\n [[False, True, False, False],\n [False, True, False, False],\n [True, False, False, False]]]]\n\n\ndef test_semantic_segmentation_labelling_sparse():\n \"\"\"Test `semantic_segmentation_labelling` function in `generator` module by considering a\n sparse labelling, *i.e.* the array contains unknown values (to mimic the non-evaluated label\n situations)\n * as a preliminary verification, check if passing string labels raises an AttributeError\n exception\n * test if output shape is input shape + an additional dimension given by the\n `label_ids` length\n * test if both representation provides the same information (native array on the\n first hand and its one-hot version on the second hand)\n\n \"\"\"\n a = np.array([[[[200, 10, 10], [200, 10, 10], [200, 200, 200]],\n [[200, 200, 200], [200, 200, 200], [200, 10, 10]],\n [[200, 200, 200], [100, 100, 100], [200, 200, 200]]],\n [[[200, 10, 10], [200, 10, 10], [10, 10, 200]],\n [[200, 200, 200], [100, 100, 100], [10, 10, 200]],\n [[200, 10, 10], [200, 10, 10], [10, 10, 200]]]])\n asum, _ = np.histogram(a.reshape(-1), range=(np.amin(a), np.amax(a)))\n wrong_config = [{'id': '0', 'color': [10, 10, 200], 'is_evaluate': True},\n {'id': '2', 'color': [10, 200, 10], 'is_evaluate': True},\n {'id': '3', 'color': [200, 200, 200], 'is_evaluate': True}]\n with pytest.raises(ValueError):\n b = generator.semantic_segmentation_labelling(a, wrong_config)\n config = [{'id': 0, 'color': [10, 10, 200], 'is_evaluate': True},\n {'id': 2, 'color': [10, 200, 10], 'is_evaluate': True},\n {'id': 3, 'color': [200, 200, 200], 'is_evaluate': True}]\n labels = [item[\"id\"] for item in config]\n b = generator.semantic_segmentation_labelling(a, config)\n assert len(labels) != np.amax(a) - np.amin(a) + 1\n assert b.shape == (a.shape[0], a.shape[1], a.shape[2], len(labels))\n assert b.tolist() == [[[[False, False, False],\n [False, False, False],\n [False, False, True]],\n [[False, False, True],\n [False, False, True],\n [False, False, False]],\n [[False, False, True],\n [False, False, False],\n [False, False, True]]],\n [[[False, False, False],\n [False, False, False],\n [True, False, False]],\n [[False, False, True],\n [False, False, False],\n [True, False, False]],\n [[False, False, False],\n [False, False, False],\n [True, False, False]]]]\n\n\ndef test_semseg_mapillary_generator(mapillary_image_size,\n mapillary_sample,\n mapillary_sample_config,\n nb_channels):\n \"\"\"Test the data generator for the Mapillary dataset\n \"\"\"\n BATCH_SIZE = 10\n config = utils.read_config(mapillary_sample_config)\n label_ids = [x['id'] for x in config[\"labels\"]]\n gen = generator.create_generator(\"mapillary\", \"semantic_segmentation\",\n mapillary_sample,\n mapillary_image_size,\n BATCH_SIZE, config[\"labels\"])\n item = next(gen)\n assert(len(item)==2)\n im_shape = item[0].shape\n assert im_shape == (BATCH_SIZE, mapillary_image_size, mapillary_image_size, nb_channels)\n label_shape = item[1].shape\n assert label_shape == (BATCH_SIZE, mapillary_image_size, mapillary_image_size, len(label_ids))\n\n\ndef test_semseg_shape_generator(shapes_image_size, shapes_sample, shapes_sample_config, nb_channels):\n \"\"\"Test the data generator for the shape dataset\n \"\"\"\n BATCH_SIZE = 10\n config = utils.read_config(shapes_sample_config)\n label_ids = [x['id'] for x in config[\"labels\"]]\n gen = generator.create_generator(\"shapes\", \"semantic_segmentation\",\n shapes_sample, shapes_image_size,\n BATCH_SIZE, config[\"labels\"])\n item = next(gen)\n assert len(item) == 2\n im_shape = item[0].shape\n assert im_shape == (BATCH_SIZE, shapes_image_size, shapes_image_size, nb_channels)\n label_shape = item[1].shape\n assert label_shape == (BATCH_SIZE, shapes_image_size, shapes_image_size, len(label_ids))\n\n\ndef test_semseg_aerial_generator(aerial_image_size, aerial_sample,\n aerial_sample_config, nb_channels):\n \"\"\"Test the data generator for the AerialImage dataset\n \"\"\"\n BATCH_SIZE = 4\n config = utils.read_config(aerial_sample_config)\n label_ids = [x['id'] for x in config[\"labels\"]]\n gen = generator.create_generator(\"aerial\", \"semantic_segmentation\",\n aerial_sample,\n aerial_image_size,\n BATCH_SIZE, config[\"labels\"])\n item = next(gen)\n assert(len(item)==2)\n im_shape = item[0].shape\n assert im_shape == (BATCH_SIZE, aerial_image_size, aerial_image_size, nb_channels)\n label_shape = item[1].shape\n assert label_shape == (BATCH_SIZE, aerial_image_size, aerial_image_size, len(label_ids))\n\n\ndef test_semseg_tanzania_generator(tanzania_image_size, tanzania_sample,\n tanzania_sample_config, nb_channels):\n \"\"\"Test the data generator for the Open AI Tanzania dataset\n \"\"\"\n BATCH_SIZE = 3\n config = utils.read_config(tanzania_sample_config)\n label_ids = [x['id'] for x in config[\"labels\"]]\n gen = generator.create_generator(\"tanzania\", \"semantic_segmentation\",\n tanzania_sample,\n tanzania_image_size,\n BATCH_SIZE, config[\"labels\"])\n item = next(gen)\n assert(len(item)==2)\n im_shape = item[0].shape\n assert im_shape == (BATCH_SIZE, tanzania_image_size, tanzania_image_size, nb_channels)\n label_shape = item[1].shape\n assert label_shape == (BATCH_SIZE, tanzania_image_size, tanzania_image_size, len(label_ids))\n\n\ndef test_wrong_model_dataset_generator(shapes_sample_config):\n \"\"\"Test a wrong model and wrong dataset\n \"\"\"\n dataset = \"fake\"\n model = \"conquer_the_world\"\n IMAGE_SIZE = 10\n BATCH_SIZE = 10\n datapath = (\"./tests/data/\" + dataset + \"/training\")\n config = utils.read_config(shapes_sample_config)\n\n # wrong dataset name\n with pytest.raises(ValueError) as excinfo:\n generator.create_generator(dataset, 'feature_detection', datapath, IMAGE_SIZE, BATCH_SIZE, config[\"labels\"])\n assert str(excinfo.value) == \"Wrong dataset name {}\".format(dataset)\n\n # wrong model name\n with pytest.raises(ValueError) as excinfo:\n generator.create_generator('shapes', model, datapath, IMAGE_SIZE, BATCH_SIZE, config[\"labels\"])\n assert str(excinfo.value) == \"Wrong model name {}\".format(model)\n"
] |
[
[
"numpy.array",
"numpy.amax",
"numpy.amin"
]
] |
MarcWong/tensorpack
|
[
"b7e411a75ca252fda46fc3cf1887687c875abe23",
"51ab279480dc1e3ffdc07884a9e8149dea9651e9"
] |
[
"examples/OnAVOS/datasets/DAVIS/DAVIS.py",
"examples/CTC-TIMIT/create-lmdb.py"
] |
[
"import glob\nimport tensorflow as tf\nfrom datasets.Dataset import ImageDataset\nfrom datasets.Util.Util import username, unique_list\nfrom datasets.Util.Reader import load_label_default\n\nNUM_CLASSES = 2\nVOID_LABEL = 255 # for translation augmentation\nDAVIS_DEFAULT_PATH = \"/fastwork/\" + username() + \"/mywork/data/DAVIS/\"\nDAVIS2017_DEFAULT_PATH = \"/fastwork/\" + username() + \"/mywork/data/DAVIS2017/\"\nDAVIS_FLOW_DEFAULT_PATH = \"/fastwork/\" + username() + \"/mywork/data/DAVIS_data/\"\nDAVIS_LUCID_DEFAULT_PATH = \"/fastwork/\" + username() + \"/mywork/data/DAVIS_data/lucid/\"\nDAVIS2017_LUCID_DEFAULT_PATH = \"/fastwork/\" + username() + \"/mywork/data/DAVIS2017_data/lucid/\"\nDAVIS_IMAGE_SIZE = (480, 854)\nDAVIS2017_IMAGE_SIZE = (480, None)\n\n\ndef read_image_and_annotation_list(fn, data_dir):\n imgs = []\n ans = []\n with open(fn) as f:\n for l in f:\n sp = l.split()\n an = data_dir + sp[1]\n im = data_dir + sp[0]\n imgs.append(im)\n ans.append(an)\n return imgs, ans\n\n\ndef group_into_sequences(fns):\n seqs = unique_list([fn.split(\"/\")[-2] for fn in fns])\n seq_fns = [[fn for fn in fns if fn.split(\"/\")[-2] == seq] for seq in seqs]\n return seq_fns\n\n\ndef get_input_list_file(subset, trainsplit):\n if subset == \"train\":\n if trainsplit == 0:\n return \"ImageSets/480p/train.txt\"\n elif trainsplit == 1:\n return \"ImageSets/480p/trainsplit_train.txt\"\n elif trainsplit == 2:\n return \"ImageSets/480p/trainsplit2_train.txt\"\n elif trainsplit == 3:\n return \"ImageSets/480p/trainsplit3_train.txt\"\n else:\n assert False, \"invalid trainsplit\"\n else:\n if trainsplit == 0:\n return \"ImageSets/480p/val.txt\"\n elif trainsplit == 1:\n return \"ImageSets/480p/trainsplit_val.txt\"\n elif trainsplit == 2:\n return \"ImageSets/480p/trainsplit2_val.txt\"\n elif trainsplit == 3:\n return \"ImageSets/480p/trainsplit3_val.txt\"\n else:\n assert False, \"invalid trainsplit\"\n\n\nclass DAVISDataset(ImageDataset):\n def __init__(self, config, subset, coord, fraction=1.0):\n super(DAVISDataset, self).__init__(\"davis\", DAVIS_DEFAULT_PATH, NUM_CLASSES, config, subset, coord,\n DAVIS_IMAGE_SIZE, VOID_LABEL, fraction, lambda x: x / 255, ignore_classes=[VOID_LABEL])\n self.trainsplit = config.int(\"trainsplit\", 0)\n\n def read_inputfile_lists(self):\n assert self.subset in (\"train\", \"valid\"), self.subset\n list_file = get_input_list_file(self.subset, self.trainsplit)\n imgs, ans = read_image_and_annotation_list(self.data_dir + list_file, self.data_dir)\n return imgs, ans\n\n\n###### DAVIS 2017 #####\n\ndef postproc_2017_labels(labels):\n return tf.cast(tf.reduce_max(labels, axis=2, keep_dims=True) > 0, tf.uint8)\n\n\ndef get_input_list_file_2017(subset):\n if subset == \"train\":\n return \"ImageSets/2017/train.txt\"\n elif subset == \"valid\":\n return \"ImageSets/2017/val.txt\"\n else:\n assert False, (\"invalid subset\", subset)\n\n\ndef read_image_and_annotation_list_2017(fn, data_dir):\n imgs = []\n ans = []\n with open(fn) as f:\n for seq in f:\n seq = seq.strip()\n base_seq = seq.split(\"__\")[0]\n imgs_seq = sorted(glob.glob(data_dir + \"JPEGImages/480p/\" + base_seq + \"/*.jpg\"))\n ans_seq = [im.replace(\"JPEGImages\", \"Annotations\").replace(\".jpg\", \".png\") for im in imgs_seq]\n if \"__\" in seq:\n ans_seq = [x.replace(base_seq, seq) for x in ans_seq]\n imgs_seq = [x.replace(base_seq, seq) for x in imgs_seq]\n imgs += imgs_seq\n ans += ans_seq\n return imgs, ans\n\n\nclass DAVIS2017Dataset(ImageDataset):\n def __init__(self, config, subset, coord, fraction=1.0):\n super(DAVIS2017Dataset, self).__init__(\"davis2017\", DAVIS2017_DEFAULT_PATH, NUM_CLASSES, config, subset, coord,\n DAVIS2017_IMAGE_SIZE, VOID_LABEL, fraction, postproc_2017_labels,\n lambda x, y: load_label_default(x, y, channels=3))\n\n def read_inputfile_lists(self):\n assert self.subset in (\"train\", \"valid\"), self.subset\n list_file = get_input_list_file_2017(self.subset)\n imgs, ans = read_image_and_annotation_list_2017(self.data_dir + list_file, self.data_dir)\n return imgs, ans\n",
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# File: create-lmdb.py\n# Author: Yuxin Wu <ppwwyyxxc@gmail.com>\nimport os\nimport scipy.io.wavfile as wavfile\nimport string\nimport numpy as np\nimport argparse\n\nfrom tensorpack.dataflow import dftools, DataFlow, LMDBDataPoint\nfrom tensorpack.utils.argtools import memoized\nfrom tensorpack.utils.stats import OnlineMoments\nfrom tensorpack.utils import serialize, fs, logger\nfrom tensorpack.utils.utils import get_tqdm\n\nCHARSET = set(string.ascii_lowercase + ' ')\nPHONEME_LIST = [\n 'aa', 'ae', 'ah', 'ao', 'aw', 'ax', 'ax-h', 'axr', 'ay', 'b', 'bcl', 'ch', 'd', 'dcl', 'dh',\n 'dx', 'eh', 'el', 'em', 'en', 'eng', 'epi', 'er', 'ey', 'f', 'g', 'gcl', 'h#', 'hh', 'hv', 'ih',\n 'ix', 'iy', 'jh', 'k', 'kcl', 'l', 'm', 'n', 'ng', 'nx', 'ow', 'oy', 'p', 'pau', 'pcl', 'q', 'r',\n 's', 'sh', 't', 'tcl', 'th', 'uh', 'uw', 'ux', 'v', 'w', 'y', 'z', 'zh']\n\nPHONEME_DIC = {v: k for k, v in enumerate(PHONEME_LIST)}\nWORD_DIC = {v: k for k, v in enumerate(string.ascii_lowercase + ' ')}\n\n\ndef read_timit_txt(f):\n f = open(f)\n line = f.readlines()[0].strip().split(' ')\n line = line[2:]\n line = ' '.join(line)\n line = line.replace('.', '').lower()\n line = filter(lambda c: c in CHARSET, line)\n f.close()\n ret = []\n for c in line:\n ret.append(WORD_DIC[c])\n return np.asarray(ret)\n\n\ndef read_timit_phoneme(f):\n f = open(f)\n pho = []\n for line in f:\n line = line.strip().split(' ')[-1]\n pho.append(PHONEME_DIC[line])\n f.close()\n return np.asarray(pho)\n\n\n@memoized\ndef get_bob_extractor(fs, win_length_ms=10, win_shift_ms=5,\n n_filters=55, n_ceps=15, f_min=0., f_max=6000,\n delta_win=2, pre_emphasis_coef=0.95, dct_norm=True,\n mel_scale=True):\n ret = bob.ap.Ceps(fs, win_length_ms, win_shift_ms, n_filters, n_ceps, f_min,\n f_max, delta_win, pre_emphasis_coef, mel_scale, dct_norm)\n return ret\n\n\ndef diff_feature(feat, nd=1):\n diff = feat[1:] - feat[:-1]\n feat = feat[1:]\n if nd == 1:\n return np.concatenate((feat, diff), axis=1)\n elif nd == 2:\n d2 = diff[1:] - diff[:-1]\n return np.concatenate((feat[1:], diff[1:], d2), axis=1)\n\n\ndef get_feature(f):\n fs, signal = wavfile.read(f)\n signal = signal.astype('float64')\n feat = get_bob_extractor(fs, n_filters=26, n_ceps=13)(signal)\n feat = diff_feature(feat, nd=2)\n return feat\n\n\nclass RawTIMIT(DataFlow):\n def __init__(self, dirname, label='phoneme'):\n self.dirname = dirname\n assert os.path.isdir(dirname), dirname\n self.filelists = [k for k in fs.recursive_walk(self.dirname)\n if k.endswith('.wav')]\n logger.info(\"Found {} wav files ...\".format(len(self.filelists)))\n assert len(self.filelists), \"Found no '.wav' files!\"\n assert label in ['phoneme', 'letter'], label\n self.label = label\n\n def size(self):\n return len(self.filelists)\n\n def get_data(self):\n for f in self.filelists:\n feat = get_feature(f)\n if self.label == 'phoneme':\n label = read_timit_phoneme(f[:-4] + '.PHN')\n elif self.label == 'letter':\n label = read_timit_txt(f[:-4] + '.TXT')\n yield [feat, label]\n\n\ndef compute_mean_std(db, fname):\n ds = LMDBDataPoint(db, shuffle=False)\n ds.reset_state()\n o = OnlineMoments()\n with get_tqdm(total=ds.size()) as bar:\n for dp in ds.get_data():\n feat = dp[0] # len x dim\n for f in feat:\n o.feed(f)\n bar.update()\n logger.info(\"Writing to {} ...\".format(fname))\n with open(fname, 'wb') as f:\n f.write(serialize.dumps([o.mean, o.std]))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers(title='command', dest='command')\n parser_db = subparsers.add_parser('build', help='build a LMDB database')\n parser_db.add_argument('--dataset',\n help='path to TIMIT TRAIN or TEST directory', required=True)\n parser_db.add_argument('--db', help='output lmdb file', required=True)\n\n parser_stat = subparsers.add_parser('stat', help='compute statistics (mean/std) of dataset')\n parser_stat.add_argument('--db', help='input lmdb file', required=True)\n parser_stat.add_argument('-o', '--output',\n help='output statistics file', default='stats.data')\n\n args = parser.parse_args()\n if args.command == 'build':\n ds = RawTIMIT(args.dataset)\n dftools.dump_dataflow_to_lmdb(ds, args.db)\n elif args.command == 'stat':\n compute_mean_std(args.db, args.output)\n"
] |
[
[
"tensorflow.reduce_max"
],
[
"numpy.concatenate",
"scipy.io.wavfile.read",
"numpy.asarray"
]
] |
cubensys/pysal
|
[
"8d50990f6e6603ba79ae1a887a20a1e3a0734e51",
"8d50990f6e6603ba79ae1a887a20a1e3a0734e51",
"8d50990f6e6603ba79ae1a887a20a1e3a0734e51"
] |
[
"pysal/contrib/glm/utils.py",
"pysal/spreg/tests/test_error_sp.py",
"pysal/spreg/tests/test_ols_sparse.py"
] |
[
"\nfrom __future__ import absolute_import, print_function\nimport numpy as np\nimport warnings\n\n\ndef _bit_length_26(x):\n if x == 0:\n return 0\n elif x == 1:\n return 1\n else:\n return len(bin(x)) - 2\n\n\ntry:\n from scipy.lib._version import NumpyVersion\nexcept ImportError:\n import re\n string_types = basestring \n\n class NumpyVersion():\n \"\"\"Parse and compare numpy version strings.\n Numpy has the following versioning scheme (numbers given are examples; they\n can be >9) in principle):\n - Released version: '1.8.0', '1.8.1', etc.\n - Alpha: '1.8.0a1', '1.8.0a2', etc.\n - Beta: '1.8.0b1', '1.8.0b2', etc.\n - Release candidates: '1.8.0rc1', '1.8.0rc2', etc.\n - Development versions: '1.8.0.dev-f1234afa' (git commit hash appended)\n - Development versions after a1: '1.8.0a1.dev-f1234afa',\n '1.8.0b2.dev-f1234afa',\n '1.8.1rc1.dev-f1234afa', etc.\n - Development versions (no git hash available): '1.8.0.dev-Unknown'\n Comparing needs to be done against a valid version string or other\n `NumpyVersion` instance.\n Parameters\n ----------\n vstring : str\n Numpy version string (``np.__version__``).\n Notes\n -----\n All dev versions of the same (pre-)release compare equal.\n Examples\n --------\n >>> from scipy.lib._version import NumpyVersion\n >>> if NumpyVersion(np.__version__) < '1.7.0':\n ... print('skip')\n skip\n >>> NumpyVersion('1.7') # raises ValueError, add \".0\"\n \"\"\"\n\n def __init__(self, vstring):\n self.vstring = vstring\n ver_main = re.match(r'\\d[.]\\d+[.]\\d+', vstring)\n if not ver_main:\n raise ValueError(\"Not a valid numpy version string\")\n\n self.version = ver_main.group()\n self.major, self.minor, self.bugfix = [int(x) for x in\n self.version.split('.')]\n if len(vstring) == ver_main.end():\n self.pre_release = 'final'\n else:\n alpha = re.match(r'a\\d', vstring[ver_main.end():])\n beta = re.match(r'b\\d', vstring[ver_main.end():])\n rc = re.match(r'rc\\d', vstring[ver_main.end():])\n pre_rel = [m for m in [alpha, beta, rc] if m is not None]\n if pre_rel:\n self.pre_release = pre_rel[0].group()\n else:\n self.pre_release = ''\n\n self.is_devversion = bool(re.search(r'.dev-', vstring))\n\n def _compare_version(self, other):\n \"\"\"Compare major.minor.bugfix\"\"\"\n if self.major == other.major:\n if self.minor == other.minor:\n if self.bugfix == other.bugfix:\n vercmp = 0\n elif self.bugfix > other.bugfix:\n vercmp = 1\n else:\n vercmp = -1\n elif self.minor > other.minor:\n vercmp = 1\n else:\n vercmp = -1\n elif self.major > other.major:\n vercmp = 1\n else:\n vercmp = -1\n\n return vercmp\n\n def _compare_pre_release(self, other):\n \"\"\"Compare alpha/beta/rc/final.\"\"\"\n if self.pre_release == other.pre_release:\n vercmp = 0\n elif self.pre_release == 'final':\n vercmp = 1\n elif other.pre_release == 'final':\n vercmp = -1\n elif self.pre_release > other.pre_release:\n vercmp = 1\n else:\n vercmp = -1\n\n return vercmp\n\n def _compare(self, other):\n if not isinstance(other, (string_types, NumpyVersion)):\n raise ValueError(\"Invalid object to compare with NumpyVersion.\")\n\n if isinstance(other, string_types):\n other = NumpyVersion(other)\n\n vercmp = self._compare_version(other)\n if vercmp == 0:\n # Same x.y.z version, check for alpha/beta/rc\n vercmp = self._compare_pre_release(other)\n if vercmp == 0:\n # Same version and same pre-release, check if dev version\n if self.is_devversion is other.is_devversion:\n vercmp = 0\n elif self.is_devversion:\n vercmp = -1\n else:\n vercmp = 1\n\n return vercmp\n\n def __lt__(self, other):\n return self._compare(other) < 0\n\n def __le__(self, other):\n return self._compare(other) <= 0\n\n def __eq__(self, other):\n return self._compare(other) == 0\n\n def __ne__(self, other):\n return self._compare(other) != 0\n\n def __gt__(self, other):\n return self._compare(other) > 0\n\n def __ge__(self, other):\n return self._compare(other) >= 0\n\n def __repr(self):\n return \"NumpyVersion(%s)\" % self.vstring\n\n\n\nclass ResettableCache(dict):\n \"\"\"\n Dictionary whose elements mey depend one from another.\n If entry `B` depends on entry `A`, changing the values of entry `A` will\n reset the value of entry `B` to a default (None); deleteing entry `A` will\n delete entry `B`. The connections between entries are stored in a\n `_resetdict` private attribute.\n Parameters\n ----------\n reset : dictionary, optional\n An optional dictionary, associated a sequence of entries to any key\n of the object.\n items : var, optional\n An optional dictionary used to initialize the dictionary\n Examples\n --------\n >>> reset = dict(a=('b',), b=('c',))\n >>> cache = resettable_cache(a=0, b=1, c=2, reset=reset)\n >>> assert_equal(cache, dict(a=0, b=1, c=2))\n >>> print(\"Try resetting a\")\n >>> cache['a'] = 1\n >>> assert_equal(cache, dict(a=1, b=None, c=None))\n >>> cache['c'] = 2\n >>> assert_equal(cache, dict(a=1, b=None, c=2))\n >>> cache['b'] = 0\n >>> assert_equal(cache, dict(a=1, b=0, c=None))\n >>> print(\"Try deleting b\")\n >>> del(cache['a'])\n >>> assert_equal(cache, {})\n \"\"\"\n\n def __init__(self, reset=None, **items):\n self._resetdict = reset or {}\n dict.__init__(self, **items)\n\n def __setitem__(self, key, value):\n dict.__setitem__(self, key, value)\n # if hasattr needed for unpickling with protocol=2\n if hasattr(self, '_resetdict'):\n for mustreset in self._resetdict.get(key, []):\n self[mustreset] = None\n\n def __delitem__(self, key):\n dict.__delitem__(self, key)\n for mustreset in self._resetdict.get(key, []):\n del(self[mustreset])\n\n# def __getstate__(self):\n# print('pickling wrapper', self.__dict__)\n# return self.__dict__\n#\n# def __setstate__(self, dict_):\n# print('unpickling wrapper', dict_)\n# self.__dict__.update(dict_)\n\n\nresettable_cache = ResettableCache\n\ndef _next_regular(target):\n \"\"\"\n Find the next regular number greater than or equal to target.\n Regular numbers are composites of the prime factors 2, 3, and 5.\n Also known as 5-smooth numbers or Hamming numbers, these are the optimal\n size for inputs to FFTPACK.\n Target must be a positive integer.\n \"\"\"\n if target <= 6:\n return target\n\n # Quickly check if it's already a power of 2\n if not (target & (target - 1)):\n return target\n\n match = float('inf') # Anything found will be smaller\n p5 = 1\n while p5 < target:\n p35 = p5\n while p35 < target:\n # Ceiling integer division, avoiding conversion to float\n # (quotient = ceil(target / p35))\n quotient = -(-target // p35)\n # Quickly find next power of 2 >= quotient\n try:\n p2 = 2 ** ((quotient - 1).bit_length())\n except AttributeError:\n # Fallback for Python <2.7\n p2 = 2 ** _bit_length_26(quotient - 1)\n\n N = p2 * p35\n if N == target:\n return N\n elif N < match:\n match = N\n p35 *= 3\n if p35 == target:\n return p35\n if p35 < match:\n match = p35\n p5 *= 5\n if p5 == target:\n return p5\n if p5 < match:\n match = p5\n return match\nif NumpyVersion(np.__version__) >= '1.7.1':\n np_matrix_rank = np.linalg.matrix_rank\nelse:\n def np_matrix_rank(M, tol=None):\n \"\"\"\n Return matrix rank of array using SVD method\n Rank of the array is the number of SVD singular values of the array that are\n greater than `tol`.\n Parameters\n ----------\n M : {(M,), (M, N)} array_like\n array of <=2 dimensions\n tol : {None, float}, optional\n threshold below which SVD values are considered zero. If `tol` is\n None, and ``S`` is an array with singular values for `M`, and\n ``eps`` is the epsilon value for datatype of ``S``, then `tol` is\n set to ``S.max() * max(M.shape) * eps``.\n Notes\n -----\n The default threshold to detect rank deficiency is a test on the magnitude\n of the singular values of `M`. By default, we identify singular values less\n than ``S.max() * max(M.shape) * eps`` as indicating rank deficiency (with\n the symbols defined above). This is the algorithm MATLAB uses [1]. It also\n appears in *Numerical recipes* in the discussion of SVD solutions for linear\n least squares [2].\n This default threshold is designed to detect rank deficiency accounting for\n the numerical errors of the SVD computation. Imagine that there is a column\n in `M` that is an exact (in floating point) linear combination of other\n columns in `M`. Computing the SVD on `M` will not produce a singular value\n exactly equal to 0 in general: any difference of the smallest SVD value from\n 0 will be caused by numerical imprecision in the calculation of the SVD.\n Our threshold for small SVD values takes this numerical imprecision into\n account, and the default threshold will detect such numerical rank\n deficiency. The threshold may declare a matrix `M` rank deficient even if\n the linear combination of some columns of `M` is not exactly equal to\n another column of `M` but only numerically very close to another column of\n `M`.\n We chose our default threshold because it is in wide use. Other thresholds\n are possible. For example, elsewhere in the 2007 edition of *Numerical\n recipes* there is an alternative threshold of ``S.max() *\n np.finfo(M.dtype).eps / 2. * np.sqrt(m + n + 1.)``. The authors describe\n this threshold as being based on \"expected roundoff error\" (p 71).\n The thresholds above deal with floating point roundoff error in the\n calculation of the SVD. However, you may have more information about the\n sources of error in `M` that would make you consider other tolerance values\n to detect *effective* rank deficiency. The most useful measure of the\n tolerance depends on the operations you intend to use on your matrix. For\n example, if your data come from uncertain measurements with uncertainties\n greater than floating point epsilon, choosing a tolerance near that\n uncertainty may be preferable. The tolerance may be absolute if the\n uncertainties are absolute rather than relative.\n References\n ----------\n .. [1] MATLAB reference documention, \"Rank\"\n http://www.mathworks.com/help/techdoc/ref/rank.html\n .. [2] W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery,\n \"Numerical Recipes (3rd edition)\", Cambridge University Press, 2007,\n page 795.\n Examples\n --------\n >>> from numpy.linalg import matrix_rank\n >>> matrix_rank(np.eye(4)) # Full rank matrix\n 4\n >>> I=np.eye(4); I[-1,-1] = 0. # rank deficient matrix\n >>> matrix_rank(I)\n 3\n >>> matrix_rank(np.ones((4,))) # 1 dimension - rank 1 unless all 0\n 1\n >>> matrix_rank(np.zeros((4,)))\n 0\n \"\"\"\n M = np.asarray(M)\n if M.ndim > 2:\n raise TypeError('array should have 2 or fewer dimensions')\n if M.ndim < 2:\n return int(not all(M == 0))\n S = np.linalg.svd(M, compute_uv=False)\n if tol is None:\n tol = S.max() * max(M.shape) * np.finfo(S.dtype).eps\n return np.sum(S > tol)\n\n\n\nclass CacheWriteWarning(UserWarning):\n pass\n\nclass CachedAttribute(object):\n\n def __init__(self, func, cachename=None, resetlist=None):\n self.fget = func\n self.name = func.__name__\n self.cachename = cachename or '_cache'\n self.resetlist = resetlist or ()\n\n def __get__(self, obj, type=None):\n if obj is None:\n return self.fget\n # Get the cache or set a default one if needed\n _cachename = self.cachename\n _cache = getattr(obj, _cachename, None)\n if _cache is None:\n setattr(obj, _cachename, resettable_cache())\n _cache = getattr(obj, _cachename)\n # Get the name of the attribute to set and cache\n name = self.name\n _cachedval = _cache.get(name, None)\n # print(\"[_cachedval=%s]\" % _cachedval)\n if _cachedval is None:\n # Call the \"fget\" function\n _cachedval = self.fget(obj)\n # Set the attribute in obj\n # print(\"Setting %s in cache to %s\" % (name, _cachedval))\n try:\n _cache[name] = _cachedval\n except KeyError:\n setattr(_cache, name, _cachedval)\n # Update the reset list if needed (and possible)\n resetlist = self.resetlist\n if resetlist is not ():\n try:\n _cache._resetdict[name] = self.resetlist\n except AttributeError:\n pass\n # else:\n # print(\"Reading %s from cache (%s)\" % (name, _cachedval))\n return _cachedval\n\n def __set__(self, obj, value):\n errmsg = \"The attribute '%s' cannot be overwritten\" % self.name\n warnings.warn(errmsg, CacheWriteWarning)\n\n\nclass _cache_readonly(object):\n \"\"\"\n Decorator for CachedAttribute\n \"\"\"\n\n def __init__(self, cachename=None, resetlist=None):\n self.func = None\n self.cachename = cachename\n self.resetlist = resetlist or None\n\n def __call__(self, func):\n return CachedAttribute(func,\n cachename=self.cachename,\n resetlist=self.resetlist)\ncache_readonly = _cache_readonly()\n\n\n",
"import unittest\nimport scipy\nimport pysal\nimport numpy as np\nfrom pysal.spreg import error_sp as SP\nfrom pysal.common import RTOL\n\nclass TestBaseGMError(unittest.TestCase):\n def setUp(self):\n db=pysal.open(pysal.examples.get_path(\"columbus.dbf\"),\"r\")\n y = np.array(db.by_col(\"HOVAL\"))\n self.y = np.reshape(y, (49,1))\n X = []\n X.append(db.by_col(\"INC\"))\n X.append(db.by_col(\"CRIME\"))\n self.X = np.array(X).T\n self.X = np.hstack((np.ones(self.y.shape),self.X))\n self.w = pysal.rook_from_shapefile(pysal.examples.get_path(\"columbus.shp\"))\n self.w.transform = 'r'\n\n def test_model(self):\n reg = SP.BaseGM_Error(self.y, self.X, self.w.sparse)\n betas = np.array([[ 47.94371455], [ 0.70598088], [ -0.55571746], [ 0.37230161]])\n np.testing.assert_allclose(reg.betas,betas,RTOL)\n u = np.array([ 27.4739775])\n np.testing.assert_allclose(reg.u[0],u,RTOL)\n predy = np.array([ 52.9930255])\n np.testing.assert_allclose(reg.predy[0],predy,RTOL)\n n = 49\n np.testing.assert_allclose(reg.n,n,RTOL)\n k = 3\n np.testing.assert_allclose(reg.k,k,RTOL)\n y = np.array([ 80.467003])\n np.testing.assert_allclose(reg.y[0],y,RTOL)\n x = np.array([ 1. , 19.531 , 15.72598])\n np.testing.assert_allclose(reg.x[0],x,RTOL)\n e = np.array([ 31.89620319])\n np.testing.assert_allclose(reg.e_filtered[0],e,RTOL)\n predy = np.array([ 52.9930255])\n np.testing.assert_allclose(reg.predy[0],predy,RTOL)\n my = 38.43622446938776\n np.testing.assert_allclose(reg.mean_y,my,RTOL)\n sy = 18.466069465206047\n np.testing.assert_allclose(reg.std_y,sy,RTOL)\n vm = np.array([[ 1.51884943e+02, -5.37622793e+00, -1.86970286e+00], [ -5.37622793e+00, 2.48972661e-01, 5.26564244e-02], [ -1.86970286e+00, 5.26564244e-02, 3.18930650e-02]])\n np.testing.assert_allclose(reg.vm,vm,RTOL)\n sig2 = 191.73716465732355\n np.testing.assert_allclose(reg.sig2,sig2,RTOL)\n\nclass TestGMError(unittest.TestCase):\n def setUp(self):\n db=pysal.open(pysal.examples.get_path(\"columbus.dbf\"),\"r\")\n y = np.array(db.by_col(\"HOVAL\"))\n self.y = np.reshape(y, (49,1))\n X = []\n X.append(db.by_col(\"INC\"))\n X.append(db.by_col(\"CRIME\"))\n self.X = np.array(X).T\n self.w = pysal.rook_from_shapefile(pysal.examples.get_path(\"columbus.shp\"))\n self.w.transform = 'r'\n\n def test_model(self):\n reg = SP.GM_Error(self.y, self.X, self.w)\n betas = np.array([[ 47.94371455], [ 0.70598088], [ -0.55571746], [ 0.37230161]])\n np.testing.assert_allclose(reg.betas,betas,RTOL)\n u = np.array([ 27.4739775])\n np.testing.assert_allclose(reg.u[0],u,RTOL)\n predy = np.array([ 52.9930255])\n np.testing.assert_allclose(reg.predy[0],predy,RTOL)\n n = 49\n np.testing.assert_allclose(reg.n,n,RTOL)\n k = 3\n np.testing.assert_allclose(reg.k,k,RTOL)\n y = np.array([ 80.467003])\n np.testing.assert_allclose(reg.y[0],y,RTOL)\n x = np.array([ 1. , 19.531 , 15.72598])\n np.testing.assert_allclose(reg.x[0],x,RTOL)\n e = np.array([ 31.89620319])\n np.testing.assert_allclose(reg.e_filtered[0],e,RTOL)\n predy = np.array([ 52.9930255])\n np.testing.assert_allclose(reg.predy[0],predy,RTOL)\n my = 38.43622446938776\n np.testing.assert_allclose(reg.mean_y,my,RTOL)\n sy = 18.466069465206047\n np.testing.assert_allclose(reg.std_y,sy,RTOL)\n vm = np.array([[ 1.51884943e+02, -5.37622793e+00, -1.86970286e+00], [ -5.37622793e+00, 2.48972661e-01, 5.26564244e-02], [ -1.86970286e+00, 5.26564244e-02, 3.18930650e-02]])\n np.testing.assert_allclose(reg.vm,vm,RTOL)\n sig2 = 191.73716465732355\n np.testing.assert_allclose(reg.sig2,sig2,RTOL)\n pr2 = 0.3495097406012179\n np.testing.assert_allclose(reg.pr2,pr2)\n std_err = np.array([ 12.32416094, 0.4989716 , 0.1785863 ])\n np.testing.assert_allclose(reg.std_err,std_err,RTOL)\n z_stat = np.array([[ 3.89022140e+00, 1.00152805e-04], [ 1.41487186e+00, 1.57106070e-01], [ -3.11175868e+00, 1.85976455e-03]])\n np.testing.assert_allclose(reg.z_stat,z_stat,RTOL)\n\n@unittest.skipIf(int(scipy.__version__.split(\".\")[1]) < 11,\n\"Maximum Likelihood requires SciPy version 11 or newer.\")\nclass TestBaseGMEndogError(unittest.TestCase):\n def setUp(self):\n db=pysal.open(pysal.examples.get_path(\"columbus.dbf\"),\"r\")\n y = np.array(db.by_col(\"HOVAL\"))\n self.y = np.reshape(y, (49,1))\n X = []\n X.append(db.by_col(\"INC\"))\n self.X = np.array(X).T\n self.X = np.hstack((np.ones(self.y.shape),self.X))\n yd = []\n yd.append(db.by_col(\"CRIME\"))\n self.yd = np.array(yd).T\n q = []\n q.append(db.by_col(\"DISCBD\"))\n self.q = np.array(q).T\n self.w = pysal.rook_from_shapefile(pysal.examples.get_path(\"columbus.shp\"))\n self.w.transform = 'r'\n\n def test_model(self):\n reg = SP.BaseGM_Endog_Error(self.y, self.X, self.yd, self.q, self.w.sparse)\n betas = np.array([[ 55.36095292], [ 0.46411479], [ -0.66883535], [ 0.38989939]])\n #raising a warning causes a failure...\n print('Running reduced precision test in L120 of test_error_sp.py')\n np.testing.assert_allclose(reg.betas,betas,RTOL+.0001)\n u = np.array([ 26.55951566])\n np.testing.assert_allclose(reg.u[0],u,RTOL)\n e = np.array([ 31.23925425])\n np.testing.assert_allclose(reg.e_filtered[0],e,RTOL)\n predy = np.array([ 53.9074875])\n np.testing.assert_allclose(reg.predy[0],predy,RTOL)\n n = 49\n np.testing.assert_allclose(reg.n,n,RTOL)\n k = 3\n np.testing.assert_allclose(reg.k,k,RTOL)\n y = np.array([ 80.467003])\n np.testing.assert_allclose(reg.y[0],y,RTOL)\n x = np.array([ 1. , 19.531])\n np.testing.assert_allclose(reg.x[0],x,RTOL)\n yend = np.array([ 15.72598])\n np.testing.assert_allclose(reg.yend[0],yend,RTOL)\n z = np.array([ 1. , 19.531 , 15.72598])\n np.testing.assert_allclose(reg.z[0],z,RTOL)\n my = 38.43622446938776\n np.testing.assert_allclose(reg.mean_y,my,RTOL)\n #std_y\n sy = 18.466069465206047\n np.testing.assert_allclose(reg.std_y,sy,RTOL)\n #vm\n vm = np.array([[ 5.29158422e+02, -1.57833675e+01, -8.38021080e+00],\n [ -1.57833675e+01, 5.40235041e-01, 2.31120327e-01],\n [ -8.38021080e+00, 2.31120327e-01, 1.44977385e-01]])\n np.testing.assert_allclose(reg.vm,vm,RTOL)\n sig2 = 192.50022721929574\n np.testing.assert_allclose(reg.sig2,sig2,RTOL)\n\n@unittest.skipIf(int(scipy.__version__.split(\".\")[1]) < 11,\n\"Maximum Likelihood requires SciPy version 11 or newer.\")\nclass TestGMEndogError(unittest.TestCase):\n def setUp(self):\n db=pysal.open(pysal.examples.get_path(\"columbus.dbf\"),\"r\")\n y = np.array(db.by_col(\"HOVAL\"))\n self.y = np.reshape(y, (49,1))\n X = []\n X.append(db.by_col(\"INC\"))\n self.X = np.array(X).T\n yd = []\n yd.append(db.by_col(\"CRIME\"))\n self.yd = np.array(yd).T\n q = []\n q.append(db.by_col(\"DISCBD\"))\n self.q = np.array(q).T\n self.w = pysal.rook_from_shapefile(pysal.examples.get_path(\"columbus.shp\"))\n self.w.transform = 'r'\n\n def test_model(self):\n reg = SP.GM_Endog_Error(self.y, self.X, self.yd, self.q, self.w)\n betas = np.array([[ 55.36095292], [ 0.46411479], [ -0.66883535], [ 0.38989939]])\n print('Running reduced precision test in L175 of test_error_sp.py')\n np.testing.assert_allclose(reg.betas,betas,RTOL +.0001)\n u = np.array([ 26.55951566])\n np.testing.assert_allclose(reg.u[0],u,RTOL)\n e = np.array([ 31.23925425])\n np.testing.assert_allclose(reg.e_filtered[0],e,RTOL)\n predy = np.array([ 53.9074875])\n np.testing.assert_allclose(reg.predy[0],predy,RTOL)\n n = 49\n np.testing.assert_allclose(reg.n,n,RTOL)\n k = 3\n np.testing.assert_allclose(reg.k,k,RTOL)\n y = np.array([ 80.467003])\n np.testing.assert_allclose(reg.y[0],y,RTOL)\n x = np.array([ 1. , 19.531])\n np.testing.assert_allclose(reg.x[0],x,RTOL)\n yend = np.array([ 15.72598])\n np.testing.assert_allclose(reg.yend[0],yend,RTOL)\n z = np.array([ 1. , 19.531 , 15.72598])\n np.testing.assert_allclose(reg.z[0],z,RTOL)\n my = 38.43622446938776\n np.testing.assert_allclose(reg.mean_y,my,RTOL)\n sy = 18.466069465206047\n np.testing.assert_allclose(reg.std_y,sy,RTOL)\n vm = np.array([[ 5.29158422e+02, -1.57833675e+01, -8.38021080e+00],\n [ -1.57833675e+01, 5.40235041e-01, 2.31120327e-01],\n [ -8.38021080e+00, 2.31120327e-01, 1.44977385e-01]])\n np.testing.assert_allclose(reg.vm,vm,RTOL)\n pr2 = 0.346472557570858\n np.testing.assert_allclose(reg.pr2,pr2,RTOL)\n sig2 = 192.50022721929574\n np.testing.assert_allclose(reg.sig2,sig2,RTOL)\n std_err = np.array([ 23.003401 , 0.73500657, 0.38075777])\n np.testing.assert_allclose(reg.std_err,std_err,RTOL)\n z_stat = np.array([[ 2.40664208, 0.01609994], [ 0.63144305, 0.52775088], [-1.75659016, 0.07898769]])\n np.testing.assert_allclose(reg.z_stat,z_stat,RTOL)\n\n@unittest.skipIf(int(scipy.__version__.split(\".\")[1]) < 11,\n\"Maximum Likelihood requires SciPy version 11 or newer.\")\nclass TestBaseGMCombo(unittest.TestCase):\n def setUp(self):\n db=pysal.open(pysal.examples.get_path(\"columbus.dbf\"),\"r\")\n y = np.array(db.by_col(\"HOVAL\"))\n self.y = np.reshape(y, (49,1))\n X = []\n X.append(db.by_col(\"INC\"))\n X.append(db.by_col(\"CRIME\"))\n self.X = np.array(X).T\n self.w = pysal.rook_from_shapefile(pysal.examples.get_path(\"columbus.shp\"))\n self.w.transform = 'r'\n\n def test_model(self):\n # Only spatial lag\n yd2, q2 = pysal.spreg.utils.set_endog(self.y, self.X, self.w, None, None, 1, True)\n self.X = np.hstack((np.ones(self.y.shape),self.X))\n reg = SP.BaseGM_Combo(self.y, self.X, yend=yd2, q=q2, w=self.w.sparse)\n betas = np.array([[ 57.61123461],[ 0.73441314], [ -0.59459416], [ -0.21762921], [ 0.54732051]])\n np.testing.assert_allclose(reg.betas,betas,RTOL)\n u = np.array([ 25.57932637])\n np.testing.assert_allclose(reg.u[0],u,RTOL)\n e_filtered = np.array([ 31.65374945])\n np.testing.assert_allclose(reg.e_filtered[0],e_filtered,RTOL)\n predy = np.array([ 54.88767663])\n np.testing.assert_allclose(reg.predy[0],predy,RTOL)\n n = 49\n np.testing.assert_allclose(reg.n,n,RTOL)\n k = 4\n np.testing.assert_allclose(reg.k,k,RTOL)\n y = np.array([ 80.467003])\n np.testing.assert_allclose(reg.y[0],y,RTOL)\n x = np.array([ 1. , 19.531 , 15.72598])\n np.testing.assert_allclose(reg.x[0],x,RTOL)\n yend = np.array([ 35.4585005])\n np.testing.assert_allclose(reg.yend[0],yend,RTOL)\n z = np.array([ 1. , 19.531 , 15.72598 , 35.4585005])\n np.testing.assert_allclose(reg.z[0],z,RTOL)\n my = 38.43622446938776\n np.testing.assert_allclose(reg.mean_y,my,RTOL)\n sy = 18.466069465206047\n np.testing.assert_allclose(reg.std_y,sy,RTOL)\n vm = np.array([ 5.22438365e+02, 2.38012873e-01, 3.20924172e-02,\n 2.15753599e-01])\n np.testing.assert_allclose(np.diag(reg.vm),vm,RTOL)\n sig2 = 181.78650186468832\n np.testing.assert_allclose(reg.sig2,sig2,RTOL)\n\n@unittest.skipIf(int(scipy.__version__.split(\".\")[1]) < 11,\n\"Maximum Likelihood requires SciPy version 11 or newer.\")\nclass TestGMCombo(unittest.TestCase):\n def setUp(self):\n db=pysal.open(pysal.examples.get_path(\"columbus.dbf\"),\"r\")\n y = np.array(db.by_col(\"HOVAL\"))\n self.y = np.reshape(y, (49,1))\n X = []\n X.append(db.by_col(\"INC\"))\n X.append(db.by_col(\"CRIME\"))\n self.X = np.array(X).T\n self.w = pysal.rook_from_shapefile(pysal.examples.get_path(\"columbus.shp\"))\n self.w.transform = 'r'\n def test_model(self):\n # Only spatial lag\n reg = SP.GM_Combo(self.y, self.X, w=self.w)\n e_reduced = np.array([ 28.18617481])\n np.testing.assert_allclose(reg.e_pred[0],e_reduced,RTOL)\n predy_e = np.array([ 52.28082782])\n np.testing.assert_allclose(reg.predy_e[0],predy_e,RTOL)\n betas = np.array([[ 57.61123515],[ 0.73441313], [ -0.59459416], [ -0.21762921], [ 0.54732051]])\n np.testing.assert_allclose(reg.betas,betas,RTOL)\n u = np.array([ 25.57932637])\n np.testing.assert_allclose(reg.u[0],u,RTOL)\n e_filtered = np.array([ 31.65374945])\n np.testing.assert_allclose(reg.e_filtered[0],e_filtered,RTOL)\n predy = np.array([ 54.88767685])\n np.testing.assert_allclose(reg.predy[0],predy,RTOL)\n n = 49\n np.testing.assert_allclose(reg.n,n,RTOL)\n k = 4\n np.testing.assert_allclose(reg.k,k,RTOL)\n y = np.array([ 80.467003])\n np.testing.assert_allclose(reg.y[0],y,RTOL)\n x = np.array([ 1. , 19.531 , 15.72598])\n np.testing.assert_allclose(reg.x[0],x,RTOL)\n yend = np.array([ 35.4585005])\n np.testing.assert_allclose(reg.yend[0],yend,RTOL)\n z = np.array([ 1. , 19.531 , 15.72598 , 35.4585005])\n np.testing.assert_allclose(reg.z[0],z,RTOL)\n my = 38.43622446938776\n np.testing.assert_allclose(reg.mean_y,my)\n sy = 18.466069465206047\n np.testing.assert_allclose(reg.std_y,sy)\n vm = np.array([ 5.22438333e+02, 2.38012875e-01, 3.20924173e-02,\n 2.15753579e-01])\n np.testing.assert_allclose(np.diag(reg.vm),vm,RTOL)\n sig2 = 181.78650186468832\n np.testing.assert_allclose(reg.sig2,sig2,RTOL)\n pr2 = 0.3018280166937799\n np.testing.assert_allclose(reg.pr2,pr2,RTOL)\n pr2_e = 0.3561355586759414\n np.testing.assert_allclose(reg.pr2_e,pr2_e,RTOL)\n std_err = np.array([ 22.85692222, 0.48786559, 0.17914356, 0.46449318])\n np.testing.assert_allclose(reg.std_err,std_err,RTOL)\n z_stat = np.array([[ 2.52051597e+00, 1.17182922e-02], [ 1.50535954e+00, 1.32231664e-01], [ -3.31909311e+00, 9.03103123e-04], [ -4.68530506e-01, 6.39405261e-01]])\n np.testing.assert_allclose(reg.z_stat,z_stat,RTOL)\n\nif __name__ == '__main__':\n unittest.main()\n",
"import unittest\nimport numpy as np\nimport pysal\nimport pysal.spreg as EC\nfrom scipy import sparse\nfrom pysal.common import RTOL\n\nPEGP = pysal.examples.get_path\n\nclass TestBaseOLS(unittest.TestCase):\n def setUp(self):\n db = pysal.open(PEGP('columbus.dbf'),'r')\n y = np.array(db.by_col(\"HOVAL\"))\n self.y = np.reshape(y, (49,1))\n X = []\n X.append(db.by_col(\"INC\"))\n X.append(db.by_col(\"CRIME\"))\n self.X = np.array(X).T\n self.w = pysal.weights.rook_from_shapefile(PEGP(\"columbus.shp\"))\n\n def test_ols(self):\n self.X = np.hstack((np.ones(self.y.shape),self.X))\n self.X = sparse.csr_matrix(self.X)\n ols = EC.ols.BaseOLS(self.y,self.X)\n np.testing.assert_allclose(ols.betas, np.array([[\n 46.42818268], [ 0.62898397], [ -0.48488854]]))\n vm = np.array([[ 1.74022453e+02, -6.52060364e+00, -2.15109867e+00],\n [ -6.52060364e+00, 2.87200008e-01, 6.80956787e-02],\n [ -2.15109867e+00, 6.80956787e-02, 3.33693910e-02]])\n np.testing.assert_allclose(ols.vm, vm,RTOL)\n\n def test_OLS(self):\n self.X = sparse.csr_matrix(self.X)\n ols = EC.OLS(self.y, self.X, self.w, spat_diag=True, moran=True, \\\n name_y='home value', name_x=['income','crime'], \\\n name_ds='columbus', nonspat_diag=True, white_test=True)\n \n np.testing.assert_allclose(ols.aic, \\\n 408.73548964604873 ,RTOL)\n np.testing.assert_allclose(ols.ar2, \\\n 0.32123239427957662 ,RTOL)\n np.testing.assert_allclose(ols.betas, \\\n np.array([[ 46.42818268], [ 0.62898397], \\\n [ -0.48488854]]),RTOL) \n bp = np.array([2, 5.7667905131212587, 0.05594449410070558])\n ols_bp = np.array([ols.breusch_pagan['df'], ols.breusch_pagan['bp'], ols.breusch_pagan['pvalue']])\n np.testing.assert_allclose(bp, ols_bp,RTOL)\n np.testing.assert_allclose(ols.f_stat, \\\n (12.358198885356581, 5.0636903313953024e-05),RTOL)\n jb = np.array([2, 39.706155069114878, 2.387360356860208e-09])\n ols_jb = np.array([ols.jarque_bera['df'], ols.jarque_bera['jb'], ols.jarque_bera['pvalue']])\n np.testing.assert_allclose(ols_jb,jb,RTOL)\n white = np.array([5, 2.90606708, 0.71446484])\n ols_white = np.array([ols.white['df'], ols.white['wh'], ols.white['pvalue']])\n np.testing.assert_allclose(ols_white,white,RTOL)\n np.testing.assert_equal(ols.k, 3)\n kb = {'df': 2, 'kb': 2.2700383871478675, 'pvalue': 0.32141595215434604}\n for key in kb:\n np.testing.assert_allclose(ols.koenker_bassett[key], kb[key],RTOL)\n np.testing.assert_allclose(ols.lm_error, \\\n (4.1508117035117893, 0.041614570655392716),RTOL)\n np.testing.assert_allclose(ols.lm_lag, \\\n (0.98279980617162233, 0.32150855529063727),RTOL)\n np.testing.assert_allclose(ols.lm_sarma, \\\n (4.3222725729143736, 0.11519415308749938),RTOL)\n np.testing.assert_allclose(ols.logll, \\\n -201.3677448230244 ,RTOL)\n np.testing.assert_allclose(ols.mean_y, \\\n 38.436224469387746,RTOL)\n np.testing.assert_allclose(ols.moran_res[0], \\\n 0.20373540938,RTOL)\n np.testing.assert_allclose(ols.moran_res[1], \\\n 2.59180452208,RTOL)\n np.testing.assert_allclose(ols.moran_res[2], \\\n 0.00954740031251,RTOL)\n np.testing.assert_allclose(ols.mulColli, \\\n 12.537554873824675 ,RTOL)\n np.testing.assert_equal(ols.n, 49)\n np.testing.assert_equal(ols.name_ds, 'columbus')\n np.testing.assert_equal(ols.name_gwk, None)\n np.testing.assert_equal(ols.name_w, 'unknown')\n np.testing.assert_equal(ols.name_x, ['CONSTANT', 'income', 'crime'])\n np.testing.assert_equal(ols.name_y, 'home value')\n np.testing.assert_allclose(ols.predy[3], np.array([\n 33.53969014]),RTOL)\n np.testing.assert_allclose(ols.r2, \\\n 0.34951437785126105 ,RTOL)\n np.testing.assert_allclose(ols.rlm_error, \\\n (3.3394727667427513, 0.067636278225568919),RTOL)\n np.testing.assert_allclose(ols.rlm_lag, \\\n (0.17146086940258459, 0.67881673703455414),RTOL)\n np.testing.assert_equal(ols.robust, 'unadjusted')\n np.testing.assert_allclose(ols.schwarz, \\\n 414.41095054038061,RTOL)\n np.testing.assert_allclose(ols.sig2, \\\n 231.4568494392652,RTOL)\n np.testing.assert_allclose(ols.sig2ML, \\\n 217.28602192257551,RTOL)\n np.testing.assert_allclose(ols.sig2n, \\\n 217.28602192257551,RTOL)\n \n np.testing.assert_allclose(ols.t_stat[2][0], \\\n -2.65440864272,RTOL)\n np.testing.assert_allclose(ols.t_stat[2][1], \\\n 0.0108745049098,RTOL)\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"numpy.asarray",
"numpy.sum",
"numpy.finfo",
"scipy.lib._version.NumpyVersion",
"numpy.linalg.svd"
],
[
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.reshape",
"numpy.ones",
"scipy.__version__.split",
"numpy.diag"
],
[
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.reshape",
"numpy.testing.assert_equal",
"numpy.ones",
"scipy.sparse.csr_matrix"
]
] |
YuhangSong/pytorch-a2c-ppo-acktr
|
[
"a018fd9ef640a60cef75f01f9e95ecff383b6a81"
] |
[
"model.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom running_stat import ObsNorm\nfrom distributions import Categorical, DiagGaussian\n\n\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1 or classname.find('Linear') != -1:\n nn.init.orthogonal(m.weight.data)\n if m.bias is not None:\n m.bias.data.fill_(0)\n\n\nclass FFPolicy(nn.Module):\n def __init__(self):\n super(FFPolicy, self).__init__()\n\n def forward(self, x):\n raise NotImplementedError\n\n def act(self, inputs, deterministic=False):\n value, x = self(inputs)\n action = self.dist.sample(x, deterministic=deterministic)\n return value, action\n\n def evaluate_actions(self, inputs, actions):\n value, x = self(inputs)\n action_log_probs, dist_entropy = self.dist.evaluate_actions(x, actions)\n return value, action_log_probs, dist_entropy\n\n\nclass CNNPolicy(FFPolicy):\n def __init__(self, num_inputs, action_space):\n super(CNNPolicy, self).__init__()\n self.conv1 = nn.Conv2d(num_inputs, 32, 8, stride=4)\n self.conv2 = nn.Conv2d(32, 64, 4, stride=2)\n self.conv3 = nn.Conv2d(64, 32, 3, stride=1)\n\n self.linear1 = nn.Linear(32 * 7 * 7, 512)\n\n self.critic_linear = nn.Linear(512, 1)\n\n if action_space.__class__.__name__ == \"Discrete\":\n num_outputs = action_space.n\n self.dist = Categorical(512, num_outputs)\n elif action_space.__class__.__name__ == \"Box\":\n num_outputs = action_space.shape[0]\n self.dist = DiagGaussian(512, num_outputs)\n else:\n raise NotImplementedError\n\n self.train()\n self.reset_parameters()\n\n def reset_parameters(self):\n self.apply(weights_init)\n\n relu_gain = nn.init.calculate_gain('relu')\n self.conv1.weight.data.mul_(relu_gain)\n self.conv2.weight.data.mul_(relu_gain)\n self.conv3.weight.data.mul_(relu_gain)\n self.linear1.weight.data.mul_(relu_gain)\n\n if self.dist.__class__.__name__ == \"DiagGaussian\":\n self.dist.fc_mean.weight.data.mul_(0.01)\n\n def forward(self, inputs):\n x = self.conv1(inputs / 255.0)\n x = F.relu(x)\n\n x = self.conv2(x)\n x = F.relu(x)\n\n x = self.conv3(x)\n x = F.relu(x)\n\n x = x.view(-1, 32 * 7 * 7)\n x = self.linear1(x)\n x = F.relu(x)\n\n return self.critic_linear(x), x\n\n\ndef weights_init_mlp(m):\n classname = m.__class__.__name__\n if classname.find('Linear') != -1:\n m.weight.data.normal_(0, 1)\n m.weight.data *= 1 / torch.sqrt(m.weight.data.pow(2).sum(1, keepdim=True))\n if m.bias is not None:\n m.bias.data.fill_(0)\n\n\nclass MLPPolicy(FFPolicy):\n def __init__(self, num_inputs, action_space):\n super(MLPPolicy, self).__init__()\n\n self.obs_filter = ObsNorm((1, num_inputs), clip=5)\n self.action_space = action_space\n\n self.a_fc1 = nn.Linear(num_inputs, 64)\n self.a_fc2 = nn.Linear(64, 64)\n\n self.v_fc1 = nn.Linear(num_inputs, 64)\n self.v_fc2 = nn.Linear(64, 64)\n self.v_fc3 = nn.Linear(64, 1)\n\n if action_space.__class__.__name__ == \"Discrete\":\n num_outputs = action_space.n\n self.dist = Categorical(64, num_outputs)\n elif action_space.__class__.__name__ == \"Box\":\n num_outputs = action_space.shape[0]\n self.dist = DiagGaussian(64, num_outputs)\n else:\n raise NotImplementedError\n\n self.train()\n self.reset_parameters()\n\n def reset_parameters(self):\n self.apply(weights_init_mlp)\n\n \"\"\"\n tanh_gain = nn.init.calculate_gain('tanh')\n self.a_fc1.weight.data.mul_(tanh_gain)\n self.a_fc2.weight.data.mul_(tanh_gain)\n self.v_fc1.weight.data.mul_(tanh_gain)\n self.v_fc2.weight.data.mul_(tanh_gain)\n \"\"\"\n\n if self.dist.__class__.__name__ == \"DiagGaussian\":\n self.dist.fc_mean.weight.data.mul_(0.01)\n\n def cuda(self, **args):\n super(MLPPolicy, self).cuda(**args)\n self.obs_filter.cuda()\n\n def cpu(self, **args):\n super(MLPPolicy, self).cpu(**args)\n self.obs_filter.cpu()\n\n def forward(self, inputs):\n inputs.data = self.obs_filter(inputs.data)\n\n x = self.v_fc1(inputs)\n x = F.tanh(x)\n\n x = self.v_fc2(x)\n x = F.tanh(x)\n\n x = self.v_fc3(x)\n value = x\n\n x = self.a_fc1(inputs)\n x = F.tanh(x)\n\n x = self.a_fc2(x)\n x = F.tanh(x)\n\n return value, x\n"
] |
[
[
"torch.nn.Linear",
"torch.nn.init.orthogonal",
"torch.nn.Conv2d",
"torch.nn.init.calculate_gain",
"torch.nn.functional.relu",
"torch.nn.functional.tanh"
]
] |
asl-epfl/sml_icassp2021
|
[
"ed64c487c59a53d59f5d8676adbbb7a22d08cf88"
] |
[
"social_learning.py"
] |
[
"import numpy as np\nimport torch\nimport nn\nfrom parameters import *\nfrom generate_data import *\nimport matplotlib.pyplot as plt\n\n#%%\n\ndef generate_sc_graph(num_agents):\n '''\n Generate strongly connected graph.\n\n Parameters\n ----------\n num_agents: int\n number of agents\n\n Returns\n -------\n G: ndarray\n graph adjacency matrix\n '''\n G = np.random.choice([0.0, 1.0], size=(num_agents, num_agents), p=[0.3, 0.7])\n G = G + np.eye(num_agents)\n G = (G > 0) * 1.0\n return G\n\n\ndef create_uniform_combination_matrix(G):\n '''\n Generate combination matrix using the uniform rule.\n\n Parameters\n ----------\n G: ndarray\n adjacency matrix\n\n Returns\n -------\n A: ndarray\n combination matrix\n '''\n A = G / np.sum(G, 0)\n return A\n\ndef create_graph_of_nn(num_agents, hidden_size, num_classes, mnist_input):\n '''\n Attribute the training models for each gent.\n\n Parameters\n ----------\n num_agents: int\n number of agents\n hidden_size: int\n size of the hidden layer for the NN\n num_classes: int\n output size for the NN\n mnist_input: int\n input size for the NN\n\n Returns\n -------\n N: list(nn.Module)\n list of all modules\n A: ndarray\n combination matrix\n '''\n G = generate_sc_graph(num_agents)\n A = create_uniform_combination_matrix(G)\n N = []\n for i in range(num_agents):\n N.append(nn.Net(mnist_input[i], hidden_size, num_classes))\n N[i].load_state_dict(torch.load('models/agent_{}.pkl'.format(i)))\n N[i].eval()\n return N, A\n\n\ndef asl(mu_0, d, test_loader, num_agents, N, A):\n '''\n Run prediction phase using the ASL algorithm.\n\n Parameters\n ----------\n mu_0: ndarray\n initial beliefs\n d: float\n step-size parameter\n test_loader: Dataloader\n test Dataloader\n num_agents: int\n number of agents\n N: list(nn.Module)\n list of NN models\n A: ndarray\n combination matrix\n\n Returns\n -------\n MU: list(ndarray)\n Belief (log-ratio) evolution over time\n '''\n mu = np.log(mu_0[:, 1] / mu_0[:, 0])\n MU = [mu]\n for i in range(len(test_loader[0])):\n L=[]\n for j in range(num_agents):\n feat = (test_loader[j].dataset.data[i]).float()\n feat = feat.view(1, -1)\n outputs = N[j](feat)\n L.append(outputs.detach().numpy())\n L = np.array(L)[:, 0]\n mu = (1-d) * A.T @ mu + d * A.T @ np.log(L[:,1] / L[:,0])\n MU.append(mu)\n return MU\n\n"
] |
[
[
"numpy.array",
"numpy.random.choice",
"numpy.log",
"numpy.sum",
"numpy.eye"
]
] |
bGhorbani/linearized_neural_networks
|
[
"a6d987d960988595ec1e5ec69e211535f1d4921b"
] |
[
"NTK_Kernel_Gen.py"
] |
[
"\"\"\"\r\nThis code implements functionalities required for computing the NT Kernel for multi-layer\r\nfully-connected neural networks. The computed kernels are saved to the disk. \r\n\r\nThe code is written for Python 3.6. \r\n\r\nInputs: \r\n\tnoise_id: The index of the noise intensity: valid range 0 to 14.\r\n\tnum_layers: The number of layers: valid range {2, 3, 4}.\r\n\"\"\"\r\n\r\nfrom __future__ import print_function\r\nimport math\r\nimport os \r\nimport sys\r\nimport time\r\nfrom preprocess import prep_data\r\nimport numpy as np\r\n\r\nfrom jax import random\r\nfrom neural_tangents import stax\r\n\r\nnoise_id = np.int(sys.argv[1])\r\nnum_layers = np.int(sys.argv[2])\r\ndataset = 'NFMNIST'\r\nX, Y, Xtest, Ytest = prep_data(dataset, False, noise_id)\t\r\n\r\nif num_layers == 2:\r\n\tinit_fn, apply_fn, kernel_fn = stax.serial(stax.Dense(512), stax.Relu(), stax.Dense(1))\r\nelif num_layers == 3:\r\n\tinit_fn, apply_fn, kernel_fn = stax.serial(stax.Dense(512), stax.Relu(), stax.Dense(512), stax.Relu(), stax.Dense(1))\r\nelif num_layers == 4:\r\n\tinit_fn, apply_fn, kernel_fn = stax.serial(stax.Dense(512), stax.Relu(), stax.Dense(512), stax.Relu(), stax.Dense(512), stax.Relu(), stax.Dense(1))\r\nelse:\r\n\traise Exception('Non-valid Kernel')\r\n\r\nn = X.shape[0]\r\nkernel = np.zeros((n, n), dtype=np.float32)\r\nm = n / 10\r\nm = np.int(m)\r\n# To avoid memory overflow, for training data, we fill the kernel matrix block by block\r\nfor i in range(10):\r\n\tfor j in range(10):\r\n\t\tprint('%d and %d'%(i, j))\r\n\t\tx1 = X[i * m:(i + 1) * m, :]\r\n\t\tx2 = X[j * m:(j + 1) * m, :]\r\n\t\tkernel[i * m:(i + 1) * m, j * m:(j + 1) * m] = kernel_fn(x1, x2, 'ntk')\r\nprint(kernel.shape)\r\ndirectory = './NTK_Kernels/'\r\nif not os.path.exists(directory):\r\n\tos.makedirs(directory)\r\nfile_name = 'Train_NTK_%d_layers_%d_%s.npy'%(noise_id, num_layers, dataset)\r\nnp.save(directory + file_name, kernel)\r\n\r\nfile_name = 'Test_NTK_%d_layers_%d_%s.npy'%(noise_id, num_layers, dataset)\r\nkernel = kernel_fn(Xtest, X, 'ntk')\r\nnp.save(directory + file_name, kernel)"
] |
[
[
"numpy.int",
"numpy.save",
"numpy.zeros"
]
] |
Bhavay192/GANmapper
|
[
"e059e8485c280d51b70dcfad7fb9c9d1324a9217"
] |
[
"options/base_options.py"
] |
[
"import argparse\nimport os\nfrom util import util\nimport torch\nimport models\nimport data\n\n\nclass BaseOptions():\n \"\"\"This class defines options used during both training and test time.\n\n It also implements several helper functions such as parsing, printing, and saving the options.\n It also gathers additional options defined in <modify_commandline_options> functions in both dataset class and model class.\n \"\"\"\n\n def __init__(self):\n \"\"\"Reset the class; indicates the class hasn't been initailized\"\"\"\n self.initialized = False\n\n def initialize(self, parser):\n \"\"\"Define the common options that are used in both training and test.\"\"\"\n # basic parameters\n parser.add_argument('--dataroot', required=True, help='path to images (should have subfolders trainA, trainB, valA, valB, etc)')\n parser.add_argument('--name', type=str, default='experiment_name', help='name of the experiment. It decides where to store samples and models')\n parser.add_argument('--gpu_ids', type=str, default='0', help='gpu ids: e.g. 0 0,1,2, 0,2. use -1 for CPU')\n parser.add_argument('--checkpoints_dir', type=str, default='./checkpoints', help='models are saved here')\n # model parameters\n parser.add_argument('--model', type=str, default='pix2pix')\n parser.add_argument('--input_nc', type=int, default=3, help='# of input image channels: 3 for RGB and 1 for grayscale')\n parser.add_argument('--output_nc', type=int, default=3, help='# of output image channels: 3 for RGB and 1 for grayscale')\n parser.add_argument('--ngf', type=int, default=64, help='# of gen filters in the last conv layer')\n parser.add_argument('--ndf', type=int, default=64, help='# of discrim filters in the first conv layer')\n parser.add_argument('--netD', type=str, default='basic', help='specify discriminator architecture [basic | n_layers | pixel]. The basic model is a 70x70 PatchGAN. n_layers allows you to specify the layers in the discriminator')\n parser.add_argument('--netG', type=str, default='resnet_9blocks', help='specify generator architecture [resnet_9blocks | resnet_6blocks | unet_256 | unet_128]')\n parser.add_argument('--n_layers_D', type=int, default=3, help='only used if netD==n_layers')\n parser.add_argument('--norm', type=str, default='instance', help='instance normalization or batch normalization [instance | batch | none]')\n parser.add_argument('--init_type', type=str, default='normal', help='network initialization [normal | xavier | kaiming | orthogonal]')\n parser.add_argument('--init_gain', type=float, default=0.02, help='scaling factor for normal, xavier and orthogonal.')\n parser.add_argument('--no_dropout', action='store_true', help='no dropout for the generator')\n # dataset parameters\n parser.add_argument('--dataset_mode', type=str, default='aligned', help='chooses how datasets are loaded. [unaligned | aligned | single | colorization]')\n parser.add_argument('--direction', type=str, default='AtoB', help='AtoB or BtoA')\n parser.add_argument('--serial_batches', action='store_true', help='if true, takes images in order to make batches, otherwise takes them randomly')\n parser.add_argument('--num_threads', default=4, type=int, help='# threads for loading data')\n parser.add_argument('--batch_size', type=int, default=1, help='input batch size')\n parser.add_argument('--load_size', type=int, default=512, help='scale images to this size')\n parser.add_argument('--crop_size', type=int, default=512, help='then crop to this size')\n parser.add_argument('--max_dataset_size', type=int, default=float(\"inf\"), help='Maximum number of samples allowed per dataset. If the dataset directory contains more than max_dataset_size, only a subset is loaded.')\n parser.add_argument('--preprocess', type=str, default='resize_and_crop', help='scaling and cropping of images at load time [resize_and_crop | crop | scale_width | scale_width_and_crop | none]')\n parser.add_argument('--no_flip', action='store_false', help='if specified, do not flip the images for data augmentation')\n parser.add_argument('--display_winsize', type=int, default=256, help='display window size for both visdom and HTML')\n # additional parameters\n parser.add_argument('--epoch', type=str, default='latest', help='which epoch to load? set to latest to use latest cached model')\n parser.add_argument('--load_iter', type=int, default='0', help='which iteration to load? if load_iter > 0, the code will load models by iter_[load_iter]; otherwise, the code will load models by [epoch]')\n parser.add_argument('--verbose', action='store_true', help='if specified, print more debugging information')\n parser.add_argument('--suffix', default='', type=str, help='customized suffix: opt.name = opt.name + suffix: e.g., {model}_{netG}_size{load_size}')\n self.initialized = True\n return parser\n\n def gather_options(self):\n \"\"\"Initialize our parser with basic options(only once).\n Add additional model-specific and dataset-specific options.\n These options are defined in the <modify_commandline_options> function\n in model and dataset classes.\n \"\"\"\n if not self.initialized: # check if it has been initialized\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser = self.initialize(parser)\n\n # get the basic options\n opt, _ = parser.parse_known_args()\n\n # modify model-related parser options\n model_name = opt.model\n model_option_setter = models.get_option_setter(model_name)\n parser = model_option_setter(parser, self.isTrain)\n opt, _ = parser.parse_known_args() # parse again with new defaults\n\n # modify dataset-related parser options\n dataset_name = opt.dataset_mode\n dataset_option_setter = data.get_option_setter(dataset_name)\n parser = dataset_option_setter(parser, self.isTrain)\n\n # save and return the parser\n self.parser = parser\n return parser.parse_args()\n\n def print_options(self, opt):\n \"\"\"Print and save options\n\n It will print both current options and default values(if different).\n It will save options into a text file / [checkpoints_dir] / opt.txt\n \"\"\"\n message = ''\n message += '----------------- Options ---------------\\n'\n for k, v in sorted(vars(opt).items()):\n comment = ''\n default = self.parser.get_default(k)\n if v != default:\n comment = '\\t[default: %s]' % str(default)\n message += '{:>25}: {:<30}{}\\n'.format(str(k), str(v), comment)\n message += '----------------- End -------------------'\n print(message)\n\n # save to the disk\n expr_dir = os.path.join(opt.checkpoints_dir, opt.name)\n util.mkdirs(expr_dir)\n file_name = os.path.join(expr_dir, '{}_opt.txt'.format(opt.phase))\n with open(file_name, 'wt') as opt_file:\n opt_file.write(message)\n opt_file.write('\\n')\n\n def parse(self):\n \"\"\"Parse our options, create checkpoints directory suffix, and set up gpu device.\"\"\"\n opt = self.gather_options()\n opt.isTrain = self.isTrain # train or test\n\n # process opt.suffix\n if opt.suffix:\n suffix = ('_' + opt.suffix.format(**vars(opt))) if opt.suffix != '' else ''\n opt.name = opt.name + suffix\n\n self.print_options(opt)\n\n # set gpu ids\n str_ids = opt.gpu_ids.split(',')\n opt.gpu_ids = []\n for str_id in str_ids:\n id = int(str_id)\n if id >= 0:\n opt.gpu_ids.append(id)\n if len(opt.gpu_ids) > 0:\n torch.cuda.set_device(opt.gpu_ids[0])\n\n self.opt = opt\n return self.opt\n"
] |
[
[
"torch.cuda.set_device"
]
] |
DrPanigrahi/RoboND-Perception-Project
|
[
"5d755c4a82ef4f7e4bc99c836ae5e03dbda03dcd"
] |
[
"sensor_stick/scripts/kmeans_clustering.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\n\n# Define a function to generate clusters\ndef cluster_gen(n_clusters, pts_minmax=(10, 100), x_mult=(1, 4), y_mult=(1, 3), \n x_off=(0, 50), y_off=(0, 50)):\n \n # n_clusters = number of clusters to generate\n # pts_minmax = range of number of points per cluster \n # x_mult = range of multiplier to modify the size of cluster in the x-direction\n # y_mult = range of multiplier to modify the size of cluster in the y-direction\n # x_off = range of cluster position offset in the x-direction\n # y_off = range of cluster position offset in the y-direction\n \n # Initialize some empty lists to receive cluster member positions\n clusters_x = []\n clusters_y = []\n labels = []\n \n # Genereate random values given parameter ranges\n n_points = np.random.randint(pts_minmax[0], pts_minmax[1], n_clusters)\n x_multipliers = np.random.randint(x_mult[0], x_mult[1], n_clusters)\n y_multipliers = np.random.randint(y_mult[0], y_mult[1], n_clusters)\n x_offsets = np.random.randint(x_off[0], x_off[1], n_clusters)\n y_offsets = np.random.randint(y_off[0], y_off[1], n_clusters)\n \n # Generate random clusters given parameter values\n for idx, npts in enumerate(n_points): \n xpts = np.random.randn(npts) * x_multipliers[idx] + x_offsets[idx]\n ypts = np.random.randn(npts) * y_multipliers[idx] + y_offsets[idx]\n clusters_x.append(xpts)\n clusters_y.append(ypts)\n labels.append(np.zeros_like(xpts) + idx)\n \n # Return cluster positions\n return clusters_x, clusters_y, labels\n\ndef main():\n '''\n\n Parameters to Tweak:\n There are lots of parameters that you can tweak and they will affect the data you generate \n and the result you get from running cv2.kmeans(). Keep the following in mind as you experiment:\n\n 1) n_clusters and k_clusters need not be the same number!\n 2) In your call to cluster_gen() you can tweak pts_minmax, x_mult, y_mult, x_off and y_off \n to change the size and shape of the clusters you generate.\n 3) The criteria you set for your k-means algorithm, max_iter and epsilon will determine \n when the algorithm stops iterating.\n \n '''\n\n # Generate some clusters!\n n_clusters = 50\n clusters_x, clusters_y, labels = cluster_gen(n_clusters, pts_minmax=(50, 80), x_mult=(3, 9), y_mult=(1, 5), \n x_off=(0, 150), y_off=(0, 150))\n # Convert to a single dataset in OpenCV format\n data = np.float32((np.concatenate(clusters_x), np.concatenate(clusters_y))).transpose()\n\n # Define k-means parameters\n # Number of clusters to define\n k_clusters = 7\n # Maximum number of iterations to perform\n max_iter = 20\n # Accuracy criterion for stopping iterations\n epsilon = 0.1\n # Number of times the algorithm is executed using different initial labellings\n attempts = 10\n # Define criteria in OpenCV format\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, max_iter, epsilon)\n # Call k-means algorithm on your dataset\n compactness, label, center = cv2.kmeans(data, k_clusters, None, criteria, attempts, cv2.KMEANS_RANDOM_CENTERS)\n\n # Define some empty lists to receive k-means cluster points\n kmeans_clusters_x = []\n kmeans_clusters_y = []\n\n # Extract k-means clusters from output\n for idx in range (k_clusters):\n kmeans_clusters_x.append(data[label.ravel()==idx][:,0])\n kmeans_clusters_y.append(data[label.ravel()==idx][:,1])\n \n # Plot up a comparison of original clusters vs. k-means clusters\n fig = plt.figure(figsize=(12,6))\n plt.subplot(121)\n min_x = np.min(data[:, 0])\n max_x = np.max(data[:, 0])\n min_y = np.min(data[:, 1])\n max_y = np.max(data[:, 1])\n for idx, xpts in enumerate(clusters_x): \n plt.plot(xpts, clusters_y[idx], 'o')\n plt.xlim(min_x, max_x)\n plt.ylim(min_y, max_y)\n plt.title('Original Clusters', fontsize=20)\n plt.subplot(122)\n for idx, xpts in enumerate(kmeans_clusters_x):\n plt.plot(xpts, kmeans_clusters_y[idx], 'o')\n plt.scatter(center[:,0], center[:,1], s = 80, c = 'r', marker = 's')\n plt.xlim(min_x, max_x)\n plt.ylim(min_y, max_y)\n plt.title('k-means Clusters', fontsize=20)\n fig.tight_layout()\n plt.subplots_adjust(left=0.03, right=0.98, top=0.9, bottom=0.05)\n plt.show()\n #plt.show(block=True)\n\nif __name__ == \"__main__\":\n main()"
] |
[
[
"numpy.max",
"numpy.concatenate",
"numpy.zeros_like",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.title",
"numpy.min",
"numpy.random.randn",
"matplotlib.pyplot.figure",
"numpy.random.randint",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.subplot"
]
] |
alvii147/stumpy
|
[
"5f192a0a41fbb44f144cc4b676d525f19aaeaa98"
] |
[
"stumpy/stump.py"
] |
[
"# STUMPY\n# Copyright 2019 TD Ameritrade. Released under the terms of the 3-Clause BSD license.\n# STUMPY is a trademark of TD Ameritrade IP Company, Inc. All rights reserved.\n\nimport logging\n\nimport numpy as np\nfrom numba import njit, prange\nimport numba\n\nfrom . import core, config\nfrom .aamp import aamp\n\nlogger = logging.getLogger(__name__)\n\n\n@njit(\n # \"(f8[:], f8[:], i8, f8[:], f8[:], f8[:], f8[:], f8[:], f8[:], f8[:], f8[:],\"\n # \"b1[:], b1[:], b1[:], b1[:], i8[:], i8, i8, i8, f8[:, :, :], i8[:, :, :], b1)\",\n fastmath=True,\n)\ndef _compute_diagonal(\n T_A,\n T_B,\n m,\n M_T,\n μ_Q,\n Σ_T_inverse,\n σ_Q_inverse,\n cov_a,\n cov_b,\n cov_c,\n cov_d,\n T_A_subseq_isfinite,\n T_B_subseq_isfinite,\n T_A_subseq_isconstant,\n T_B_subseq_isconstant,\n diags,\n diags_start_idx,\n diags_stop_idx,\n thread_idx,\n ρ,\n I,\n ignore_trivial,\n):\n \"\"\"\n Compute (Numba JIT-compiled) and update the Pearson correlation, ρ, and I\n sequentially along individual diagonals using a single thread and avoiding race\n conditions\n\n Parameters\n ----------\n T_A : numpy.ndarray\n The time series or sequence for which to compute the matrix profile\n\n T_B : numpy.ndarray\n The time series or sequence that will be used to annotate T_A. For every\n subsequence in T_A, its nearest neighbor in T_B will be recorded.\n\n m : int\n Window size\n\n M_T : numpy.ndarray\n Sliding mean of time series, `T`\n\n μ_Q : numpy.ndarray\n Mean of the query sequence, `Q`, relative to the current sliding window\n\n Σ_T_inverse : numpy.ndarray\n Inverse sliding standard deviation of time series, `T`\n\n σ_Q_inverse : numpy.ndarray\n Inverse standard deviation of the query sequence, `Q`, relative to the current\n sliding window\n\n cov_a : numpy.ndarray\n The first covariance term relating T_A[i + k + m - 1] and M_T_m_1[i + k]\n\n cov_b : numpy.ndarray\n The second covariance term relating T_B[i + m - 1] and μ_Q_m_1[i]\n\n cov_c : numpy.ndarray\n The third covariance term relating T_A[i + k - 1] and M_T_m_1[i + k]\n\n cov_d : numpy.ndarray\n The fourth covariance term relating T_B[i - 1] and μ_Q_m_1[i]\n\n μ_Q_m_1 : numpy.ndarray\n Mean of the query sequence, `Q`, relative to the current sliding window and\n using a window size of `m-1`\n\n T_A_subseq_isfinite : numpy.ndarray\n A boolean array that indicates whether a subsequence in `T_A` contains a\n `np.nan`/`np.inf` value (False)\n\n T_B_subseq_isfinite : numpy.ndarray\n A boolean array that indicates whether a subsequence in `T_B` contains a\n `np.nan`/`np.inf` value (False)\n\n T_A_subseq_isconstant : numpy.ndarray\n A boolean array that indicates whether a subsequence in `T_A` is constant (True)\n\n T_B_subseq_isconstant : numpy.ndarray\n A boolean array that indicates whether a subsequence in `T_B` is constant (True)\n\n diags : numpy.ndarray\n The diagonal indices\n\n diags_start_idx : int\n The starting (inclusive) diagonal index\n\n diags_stop_idx : int\n The stopping (exclusive) diagonal index\n\n thread_idx : int\n The thread index\n\n ρ : numpy.ndarray\n The Pearson correlations\n\n I : numpy.ndarray\n The matrix profile indices\n\n ignore_trivial : bool\n Set to `True` if this is a self-join. Otherwise, for AB-join, set this to\n `False`. Default is `True`.\n\n Returns\n -------\n None\n\n Notes\n -----\n `DOI: 10.1007/s10115-017-1138-x \\\n <https://www.cs.ucr.edu/~eamonn/ten_quadrillion.pdf>`__\n\n See Section 4.5\n\n The above reference outlines a general approach for traversing the distance\n matrix in a diagonal fashion rather than in a row-wise fashion.\n\n `DOI: 10.1145/3357223.3362721 \\\n <https://www.cs.ucr.edu/~eamonn/public/GPU_Matrix_profile_VLDB_30DraftOnly.pdf>`__\n\n See Section 3.1 and Section 3.3\n\n The above reference outlines the use of the Pearson correlation via Welford's\n centered sum-of-products along each diagonal of the distance matrix in place of the\n sliding window dot product found in the original STOMP method.\n \"\"\"\n n_A = T_A.shape[0]\n n_B = T_B.shape[0]\n m_inverse = 1.0 / m\n constant = (m - 1) * m_inverse * m_inverse # (m - 1)/(m * m)\n\n for diag_idx in range(diags_start_idx, diags_stop_idx):\n k = diags[diag_idx]\n\n if k >= 0:\n iter_range = range(0, min(n_A - m + 1, n_B - m + 1 - k))\n else:\n iter_range = range(-k, min(n_A - m + 1, n_B - m + 1 - k))\n\n for i in iter_range:\n if i == 0 or (k < 0 and i == -k):\n cov = (\n np.dot(\n (T_B[i + k : i + k + m] - M_T[i + k]), (T_A[i : i + m] - μ_Q[i])\n )\n * m_inverse\n )\n else:\n # The next lines are equivalent and left for reference\n # cov = cov + constant * (\n # (T_B[i + k + m - 1] - M_T_m_1[i + k])\n # * (T_A[i + m - 1] - μ_Q_m_1[i])\n # - (T_B[i + k - 1] - M_T_m_1[i + k]) * (T_A[i - 1] - μ_Q_m_1[i])\n # )\n cov = cov + constant * (\n cov_a[i + k] * cov_b[i] - cov_c[i + k] * cov_d[i]\n )\n\n if T_B_subseq_isfinite[i + k] and T_A_subseq_isfinite[i]:\n # Neither subsequence contains NaNs\n if T_B_subseq_isconstant[i + k] or T_A_subseq_isconstant[i]:\n pearson = 0.5\n else:\n pearson = cov * Σ_T_inverse[i + k] * σ_Q_inverse[i]\n\n if T_B_subseq_isconstant[i + k] and T_A_subseq_isconstant[i]:\n pearson = 1.0\n\n if pearson > ρ[thread_idx, i, 0]:\n ρ[thread_idx, i, 0] = pearson\n I[thread_idx, i, 0] = i + k\n\n if ignore_trivial: # self-joins only\n if pearson > ρ[thread_idx, i + k, 0]:\n ρ[thread_idx, i + k, 0] = pearson\n I[thread_idx, i + k, 0] = i\n\n if i < i + k:\n # left pearson correlation and left matrix profile index\n if pearson > ρ[thread_idx, i + k, 1]:\n ρ[thread_idx, i + k, 1] = pearson\n I[thread_idx, i + k, 1] = i\n\n # right pearson correlation and right matrix profile index\n if pearson > ρ[thread_idx, i, 2]:\n ρ[thread_idx, i, 2] = pearson\n I[thread_idx, i, 2] = i + k\n\n return\n\n\n@njit(\n # \"(f8[:], f8[:], i8, f8[:], f8[:], f8[:], f8[:], f8[:], f8[:], b1[:], b1[:],\"\n # \"b1[:], b1[:], i8[:], b1)\",\n parallel=True,\n fastmath=True,\n)\ndef _stump(\n T_A,\n T_B,\n m,\n M_T,\n μ_Q,\n Σ_T_inverse,\n σ_Q_inverse,\n M_T_m_1,\n μ_Q_m_1,\n T_A_subseq_isfinite,\n T_B_subseq_isfinite,\n T_A_subseq_isconstant,\n T_B_subseq_isconstant,\n diags,\n ignore_trivial,\n):\n \"\"\"\n A Numba JIT-compiled version of STOMPopt with Pearson correlations for parallel\n computation of the matrix profile, matrix profile indices, left matrix profile\n indices, and right matrix profile indices.\n\n Parameters\n ----------\n T_A : numpy.ndarray\n The time series or sequence for which to compute the matrix profile\n\n T_B : numpy.ndarray\n The time series or sequence that will be used to annotate T_A. For every\n subsequence in T_A, its nearest neighbor in T_B will be recorded.\n\n m : int\n Window size\n\n M_T : numpy.ndarray\n Sliding mean of time series, `T`\n\n μ_Q : numpy.ndarray\n Mean of the query sequence, `Q`, relative to the current sliding window\n\n Σ_T_inverse : numpy.ndarray\n Inverse sliding standard deviation of time series, `T`\n\n σ_Q_inverse : numpy.ndarray\n Inverse standard deviation of the query sequence, `Q`, relative to the current\n sliding window\n\n M_T_m_1 : numpy.ndarray\n Sliding mean of time series, `T`, using a window size of `m-1`\n\n μ_Q_m_1 : numpy.ndarray\n Mean of the query sequence, `Q`, relative to the current sliding window and\n using a window size of `m-1`\n\n T_A_subseq_isfinite : numpy.ndarray\n A boolean array that indicates whether a subsequence in `T_A` contains a\n `np.nan`/`np.inf` value (False)\n\n T_B_subseq_isfinite : numpy.ndarray\n A boolean array that indicates whether a subsequence in `T_B` contains a\n `np.nan`/`np.inf` value (False)\n\n T_A_subseq_isconstant : numpy.ndarray\n A boolean array that indicates whether a subsequence in `T_A` is constant (True)\n\n T_B_subseq_isconstant : numpy.ndarray\n A boolean array that indicates whether a subsequence in `T_B` is constant (True)\n\n diags : numpy.ndarray\n The diagonal indices\n\n ignore_trivial : bool\n Set to `True` if this is a self-join. Otherwise, for AB-join, set this to\n `False`. Default is `True`.\n\n Returns\n -------\n profile : numpy.ndarray\n Matrix profile\n\n indices : numpy.ndarray\n The first column consists of the matrix profile indices, the second\n column consists of the left matrix profile indices, and the third\n column consists of the right matrix profile indices.\n\n Notes\n -----\n `DOI: 10.1007/s10115-017-1138-x \\\n <https://www.cs.ucr.edu/~eamonn/ten_quadrillion.pdf>`__\n\n See Section 4.5\n\n The above reference outlines a general approach for traversing the distance\n matrix in a diagonal fashion rather than in a row-wise fashion.\n\n `DOI: 10.1145/3357223.3362721 \\\n <https://www.cs.ucr.edu/~eamonn/public/GPU_Matrix_profile_VLDB_30DraftOnly.pdf>`__\n\n See Section 3.1 and Section 3.3\n\n The above reference outlines the use of the Pearson correlation via Welford's\n centered sum-of-products along each diagonal of the distance matrix in place of the\n sliding window dot product found in the original STOMP method.\n\n `DOI: 10.1109/ICDM.2016.0085 \\\n <https://www.cs.ucr.edu/~eamonn/STOMP_GPU_final_submission_camera_ready.pdf>`__\n\n See Table II\n\n Timeseries, T_A, will be annotated with the distance location\n (or index) of all its subsequences in another times series, T_B.\n\n Return: For every subsequence, Q, in T_A, you will get a distance\n and index for the closest subsequence in T_B. Thus, the array\n returned will have length T_A.shape[0]-m+1. Additionally, the\n left and right matrix profiles are also returned.\n\n Note: Unlike in the Table II where T_A.shape is expected to be equal\n to T_B.shape, this implementation is generalized so that the shapes of\n T_A and T_B can be different. In the case where T_A.shape == T_B.shape,\n then our algorithm reduces down to the same algorithm found in Table II.\n\n Additionally, unlike STAMP where the exclusion zone is m/2, the default\n exclusion zone for STOMP is m/4 (See Definition 3 and Figure 3).\n\n For self-joins, set `ignore_trivial = True` in order to avoid the\n trivial match.\n\n Note that left and right matrix profiles are only available for self-joins.\n \"\"\"\n n_A = T_A.shape[0]\n n_B = T_B.shape[0]\n l = n_A - m + 1\n n_threads = numba.config.NUMBA_NUM_THREADS\n ρ = np.full((n_threads, l, 3), -np.inf, dtype=np.float64)\n I = np.full((n_threads, l, 3), -1, dtype=np.int64)\n\n ndist_counts = core._count_diagonal_ndist(diags, m, n_A, n_B)\n diags_ranges = core._get_array_ranges(ndist_counts, n_threads, False)\n\n cov_a = T_B[m - 1 :] - M_T_m_1[:-1]\n cov_b = T_A[m - 1 :] - μ_Q_m_1[:-1]\n # The next lines are equivalent and left for reference\n # cov_c = np.roll(T_A, 1)\n # cov_ = cov_c[:M_T_m_1.shape[0]] - M_T_m_1[:]\n cov_c = np.empty(M_T_m_1.shape[0], dtype=np.float64)\n cov_c[1:] = T_B[: M_T_m_1.shape[0] - 1]\n cov_c[0] = T_B[-1]\n cov_c[:] = cov_c - M_T_m_1\n # The next lines are equivalent and left for reference\n # cov_d = np.roll(T_B, 1)\n # cov_d = cov_d[:μ_Q_m_1.shape[0]] - μ_Q_m_1[:]\n cov_d = np.empty(μ_Q_m_1.shape[0], dtype=np.float64)\n cov_d[1:] = T_A[: μ_Q_m_1.shape[0] - 1]\n cov_d[0] = T_A[-1]\n cov_d[:] = cov_d - μ_Q_m_1\n\n for thread_idx in prange(n_threads):\n # Compute and update cov, I within a single thread to avoiding race conditions\n _compute_diagonal(\n T_A,\n T_B,\n m,\n M_T,\n μ_Q,\n Σ_T_inverse,\n σ_Q_inverse,\n cov_a,\n cov_b,\n cov_c,\n cov_d,\n T_A_subseq_isfinite,\n T_B_subseq_isfinite,\n T_A_subseq_isconstant,\n T_B_subseq_isconstant,\n diags,\n diags_ranges[thread_idx, 0],\n diags_ranges[thread_idx, 1],\n thread_idx,\n ρ,\n I,\n ignore_trivial,\n )\n\n # Reduction of results from all threads\n for thread_idx in range(1, n_threads):\n for i in prange(l):\n if ρ[0, i, 0] < ρ[thread_idx, i, 0]:\n ρ[0, i, 0] = ρ[thread_idx, i, 0]\n I[0, i, 0] = I[thread_idx, i, 0]\n # left pearson correlation and left matrix profile indices\n if ρ[0, i, 1] < ρ[thread_idx, i, 1]:\n ρ[0, i, 1] = ρ[thread_idx, i, 1]\n I[0, i, 1] = I[thread_idx, i, 1]\n # right pearson correlation and right matrix profile indices\n if ρ[0, i, 2] < ρ[thread_idx, i, 2]:\n ρ[0, i, 2] = ρ[thread_idx, i, 2]\n I[0, i, 2] = I[thread_idx, i, 2]\n\n # Convert pearson correlations to distances\n D = np.abs(2 * m * (1 - ρ[0, :, :]))\n for i in prange(D.shape[0]):\n if D[i, 0] < config.STUMPY_D_SQUARED_THRESHOLD:\n D[i, 0] = 0.0\n if D[i, 1] < config.STUMPY_D_SQUARED_THRESHOLD:\n D[i, 1] = 0.0\n if D[i, 2] < config.STUMPY_D_SQUARED_THRESHOLD:\n D[i, 2] = 0.0\n P = np.sqrt(D)\n\n return P[:, :], I[0, :, :]\n\n\n@core.non_normalized(aamp)\ndef stump(T_A, m, T_B=None, ignore_trivial=True, normalize=True):\n \"\"\"\n Compute the z-normalized matrix profile\n\n This is a convenience wrapper around the Numba JIT-compiled parallelized\n `_stump` function which computes the matrix profile according to STOMPopt with\n Pearson correlations.\n\n Parameters\n ----------\n T_A : numpy.ndarray\n The time series or sequence for which to compute the matrix profile\n\n m : int\n Window size\n\n T_B : numpy.ndarray, default None\n The time series or sequence that will be used to annotate T_A. For every\n subsequence in T_A, its nearest neighbor in T_B will be recorded. Default is\n `None` which corresponds to a self-join.\n\n ignore_trivial : bool, default True\n Set to `True` if this is a self-join. Otherwise, for AB-join, set this\n to `False`. Default is `True`.\n\n normalize : bool, default True\n When set to `True`, this z-normalizes subsequences prior to computing distances.\n Otherwise, this function gets re-routed to its complementary non-normalized\n equivalent set in the `@core.non_normalized` function decorator.\n\n Returns\n -------\n out : numpy.ndarray\n The first column consists of the matrix profile, the second column\n consists of the matrix profile indices, the third column consists of\n the left matrix profile indices, and the fourth column consists of\n the right matrix profile indices.\n\n See Also\n --------\n stumpy.stumped : Compute the z-normalized matrix profile with a distributed dask\n cluster\n stumpy.gpu_stump : Compute the z-normalized matrix profile with one or more GPU\n devices\n stumpy.scrump : Compute an approximate z-normalized matrix profile\n\n Notes\n -----\n `DOI: 10.1007/s10115-017-1138-x \\\n <https://www.cs.ucr.edu/~eamonn/ten_quadrillion.pdf>`__\n\n See Section 4.5\n\n The above reference outlines a general approach for traversing the distance\n matrix in a diagonal fashion rather than in a row-wise fashion.\n\n `DOI: 10.1145/3357223.3362721 \\\n <https://www.cs.ucr.edu/~eamonn/public/GPU_Matrix_profile_VLDB_30DraftOnly.pdf>`__\n\n See Section 3.1 and Section 3.3\n\n The above reference outlines the use of the Pearson correlation via Welford's\n centered sum-of-products along each diagonal of the distance matrix in place of the\n sliding window dot product found in the original STOMP method.\n\n `DOI: 10.1109/ICDM.2016.0085 \\\n <https://www.cs.ucr.edu/~eamonn/STOMP_GPU_final_submission_camera_ready.pdf>`__\n\n See Table II\n\n Timeseries, T_A, will be annotated with the distance location\n (or index) of all its subsequences in another times series, T_B.\n\n Return: For every subsequence, Q, in T_A, you will get a distance\n and index for the closest subsequence in T_B. Thus, the array\n returned will have length T_A.shape[0]-m+1. Additionally, the\n left and right matrix profiles are also returned.\n\n Note: Unlike in the Table II where T_A.shape is expected to be equal\n to T_B.shape, this implementation is generalized so that the shapes of\n T_A and T_B can be different. In the case where T_A.shape == T_B.shape,\n then our algorithm reduces down to the same algorithm found in Table II.\n\n Additionally, unlike STAMP where the exclusion zone is m/2, the default\n exclusion zone for STOMP is m/4 (See Definition 3 and Figure 3).\n\n For self-joins, set `ignore_trivial = True` in order to avoid the\n trivial match.\n\n Note that left and right matrix profiles are only available for self-joins.\n\n Examples\n --------\n >>> import stumpy\n >>> stumpy.stump(np.array([584., -11., 23., 79., 1001., 0., -19.]), m=3)\n array([[0.11633857113691416, 4, -1, 4],\n [2.694073918063438, 3, -1, 3],\n [3.0000926340485923, 0, 0, 4],\n [2.694073918063438, 1, 1, -1],\n [0.11633857113691416, 0, 0, -1]], dtype=object)\n \"\"\"\n if T_B is None:\n T_B = T_A\n ignore_trivial = True\n\n (\n T_A,\n μ_Q,\n σ_Q_inverse,\n μ_Q_m_1,\n T_A_subseq_isfinite,\n T_A_subseq_isconstant,\n ) = core.preprocess_diagonal(T_A, m)\n\n (\n T_B,\n M_T,\n Σ_T_inverse,\n M_T_m_1,\n T_B_subseq_isfinite,\n T_B_subseq_isconstant,\n ) = core.preprocess_diagonal(T_B, m)\n\n if T_A.ndim != 1: # pragma: no cover\n raise ValueError(\n f\"T_A is {T_A.ndim}-dimensional and must be 1-dimensional. \"\n \"For multidimensional STUMP use `stumpy.mstump` or `stumpy.mstumped`\"\n )\n\n if T_B.ndim != 1: # pragma: no cover\n raise ValueError(\n f\"T_B is {T_B.ndim}-dimensional and must be 1-dimensional. \"\n \"For multidimensional STUMP use `stumpy.mstump` or `stumpy.mstumped`\"\n )\n\n core.check_window_size(m, max_size=min(T_A.shape[0], T_B.shape[0]))\n\n if ignore_trivial is False and core.are_arrays_equal(T_A, T_B): # pragma: no cover\n logger.warning(\"Arrays T_A, T_B are equal, which implies a self-join.\")\n logger.warning(\"Try setting `ignore_trivial = True`.\")\n\n if ignore_trivial and core.are_arrays_equal(T_A, T_B) is False: # pragma: no cover\n logger.warning(\"Arrays T_A, T_B are not equal, which implies an AB-join.\")\n logger.warning(\"Try setting `ignore_trivial = False`.\")\n\n n_A = T_A.shape[0]\n n_B = T_B.shape[0]\n l = n_A - m + 1\n\n excl_zone = int(np.ceil(m / config.STUMPY_EXCL_ZONE_DENOM))\n out = np.empty((l, 4), dtype=object)\n\n if ignore_trivial:\n diags = np.arange(excl_zone + 1, n_A - m + 1, dtype=np.int64)\n else:\n diags = np.arange(-(n_A - m + 1) + 1, n_B - m + 1, dtype=np.int64)\n\n P, I = _stump(\n T_A,\n T_B,\n m,\n M_T,\n μ_Q,\n Σ_T_inverse,\n σ_Q_inverse,\n M_T_m_1,\n μ_Q_m_1,\n T_A_subseq_isfinite,\n T_B_subseq_isfinite,\n T_A_subseq_isconstant,\n T_B_subseq_isconstant,\n diags,\n ignore_trivial,\n )\n\n out[:, 0] = P[:, 0]\n out[:, 1:] = I\n\n threshold = 10e-6\n if core.are_distances_too_small(out[:, 0], threshold=threshold): # pragma: no cover\n logger.warning(f\"A large number of values are smaller than {threshold}.\")\n logger.warning(\"For a self-join, try setting `ignore_trivial = True`.\")\n\n return out\n"
] |
[
[
"numpy.full",
"numpy.ceil",
"numpy.dot",
"numpy.empty",
"numpy.arange",
"numpy.sqrt",
"numpy.abs"
]
] |
rmst/rlrd
|
[
"05a5329066dcabfb7278ec8745890bc2e7edce15"
] |
[
"rlrd/dcac.py"
] |
[
"# Delay Correcting Actor-Critic\n\nfrom copy import deepcopy\nfrom dataclasses import dataclass\nfrom functools import reduce\nimport torch\nfrom torch.nn.functional import mse_loss\nimport rlrd.sac\nfrom rlrd.memory import TrajMemoryNoHidden\nfrom rlrd.nn import no_grad, exponential_moving_average\nfrom rlrd.util import partial\nfrom rlrd.dcac_models import Mlp\nfrom rlrd.envs import RandomDelayEnv\nfrom rlrd import Training\n\n\n@dataclass(eq=0)\nclass Agent(rlrd.sac.Agent):\n Model: type = Mlp\n loss_alpha: float = 0.2\n rtac: bool = False\n\n def __post_init__(self, Env):\n with Env() as env:\n observation_space, action_space = env.observation_space, env.action_space\n self.sup_obs_delay = env.obs_delay_range.stop\n self.sup_act_delay = env.act_delay_range.stop\n self.act_buf_size = self.sup_obs_delay + self.sup_act_delay - 1\n self.old_act_buf_size = deepcopy(self.act_buf_size)\n if self.rtac:\n self.act_buf_size = 1\n\n assert self.device is not None\n device = self.device # or (\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model = self.Model(observation_space, action_space)\n self.model = model.to(device)\n self.model_target = no_grad(deepcopy(self.model))\n\n self.outputnorm = self.OutputNorm(self.model.critic_output_layers)\n self.outputnorm_target = self.OutputNorm(self.model_target.critic_output_layers)\n\n self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.lr)\n self.memory = TrajMemoryNoHidden(self.memory_size, self.batchsize, device, history=self.act_buf_size)\n self.traj_new_actions = [None, ] * self.act_buf_size\n self.traj_new_actions_detach = [None, ] * self.act_buf_size\n self.traj_new_actions_log_prob = [None, ] * self.act_buf_size\n self.traj_new_actions_log_prob_detach = [None, ] * self.act_buf_size\n self.traj_new_augm_obs = [None, ] * (self.act_buf_size + 1)\n\n self.is_training = False\n\n def train(self):\n # sample a trajectory of length self.act_buf_size\n # NB: when terminals is True, the terminal augmented state is the last one of the trajectory (this is ensured by the sampling procedure)\n\n # TODO: act_traj is useless, it could be removed from the replay memory\n # FIXME: the profiler indicates that memory is inefficient, optimize\n\n augm_obs_traj, act_traj, rew_traj, terminals = self.memory.sample()\n\n batch_size = terminals.shape[0]\n\n # value of the first augmented state:\n values = [c(augm_obs_traj[0]).squeeze() for c in self.model.critics]\n\n # nstep_len is the number of valid transitions of the sampled sub-trajectory, not counting the first one which is always valid since we consider the action delay to be always >= 1.\n # nstep_len will be e.g. 0 in the rtrl setting (an action delay of 0 here means an action delay of 1 in the paper).\n\n int_tens_type = obs_del = augm_obs_traj[0][2].dtype\n ones_tens = torch.ones(batch_size, device=self.device, dtype=int_tens_type, requires_grad=False)\n\n if not self.rtac:\n nstep_len = ones_tens * (self.act_buf_size - 1)\n for i in reversed(range(self.act_buf_size)): # we don't care about the delay of the first observation in the trajectory, but we care about the last one\n obs_del = augm_obs_traj[i + 1][2] # observation delay (alpha)\n act_del = augm_obs_traj[i + 1][4] # action_delay (beta)\n tot_del = obs_del + act_del\n # TODO: the last iteration is useless\n nstep_len = torch.where((tot_del <= i), ones_tens * (i - 1), nstep_len)\n nstep_max_len = torch.max(nstep_len)\n nstep_min_len = torch.min(nstep_len)\n assert nstep_min_len >= 0, \"Each total delay must be at least 1 (instantaneous turn-based RL not supported)\"\n nstep_one_hot = torch.zeros(len(nstep_len), nstep_max_len + 1, device=self.device, requires_grad=False).scatter_(1, nstep_len.unsqueeze(1).long(), 1.)\n else: # RTAC is equivalent to doing only 1-step backups (i.e. nstep_len==0)\n nstep_len = torch.zeros(batch_size, device=self.device, dtype=int_tens_type, requires_grad=False)\n nstep_max_len = torch.max(nstep_len)\n nstep_one_hot = torch.zeros(len(nstep_len), nstep_max_len + 1, device=self.device, requires_grad=False).scatter_(1, nstep_len.unsqueeze(1).long(), 1.)\n terminals = terminals if self.act_buf_size == 1 else terminals * 0.0 # the way the replay memory works, RTAC will never encounter terminal states for buffers of more than 1 action\n\n # use the current policy to compute a new trajectory of actions of length self.act_buf_size\n for i in range(self.act_buf_size + 1):\n # compute a new action and update the corresponding *next* augmented observation:\n augm_obs = augm_obs_traj[i]\n if i > 0:\n act_slice = tuple(self.traj_new_actions[self.act_buf_size - i:self.act_buf_size])\n augm_obs = augm_obs[:1] + ((act_slice + augm_obs[1][i:]), ) + augm_obs[2:]\n if i < self.act_buf_size: # we don't compute the action for the last observation of the trajectory\n new_action_distribution = self.model.actor(augm_obs)\n # this is stored in right -> left order for replacing correctly in augm_obs:\n self.traj_new_actions[self.act_buf_size - i - 1] = new_action_distribution.rsample()\n self.traj_new_actions_detach[self.act_buf_size - i - 1] = self.traj_new_actions[self.act_buf_size - i - 1].detach()\n # this is stored in left -> right order for to be consistent with the reward trajectory:\n self.traj_new_actions_log_prob[i] = new_action_distribution.log_prob(self.traj_new_actions[self.act_buf_size - i - 1])\n self.traj_new_actions_log_prob_detach[i] = self.traj_new_actions_log_prob[i].detach()\n # this is stored in left -> right order:\n self.traj_new_augm_obs[i] = augm_obs\n\n # We now compute the state-value estimate\n # (this can be a different position in the trajectory for each element of the batch).\n # We expect each augmented state to be of shape (obs:tensor, act_buf:(tensor, ..., tensor), obs_del:tensor, act_del:tensor). Each tensor is batched.\n # To execute only 1 forward pass in the state-value estimator we recreate an artificially batched augmented state for this specific purpose.\n\n # FIXME: the profiler indicates that the following 5 lines are very inefficient, optimize\n\n obs_s = torch.stack([self.traj_new_augm_obs[i + 1][0][ibatch] for ibatch, i in enumerate(nstep_len)])\n act_s = tuple(torch.stack([self.traj_new_augm_obs[i + 1][1][iact][ibatch] for ibatch, i in enumerate(nstep_len)]) for iact in range(self.old_act_buf_size))\n od_s = torch.stack([self.traj_new_augm_obs[i + 1][2][ibatch] for ibatch, i in enumerate(nstep_len)])\n ad_s = torch.stack([self.traj_new_augm_obs[i + 1][3][ibatch] for ibatch, i in enumerate(nstep_len)])\n mod_augm_obs = tuple((obs_s, act_s, od_s, ad_s))\n\n with torch.no_grad():\n\n # These are the delayed state-value estimates we are looking for:\n target_mod_val = [c(mod_augm_obs) for c in self.model_target.critics]\n target_mod_val = reduce(torch.min, torch.stack(target_mod_val)).squeeze() # minimum target estimate\n target_mod_val = target_mod_val * (1. - terminals)\n\n # Now let us use this to compute the state-value targets of the batch of initial augmented states:\n\n value_target = torch.zeros(batch_size, device=self.device)\n backup_started = torch.zeros(batch_size, device=self.device)\n for i in reversed(range(nstep_max_len + 1)):\n start_backup_mask = nstep_one_hot[:, i]\n backup_started += start_backup_mask\n value_target = self.reward_scale * rew_traj[i] - self.entropy_scale * self.traj_new_actions_log_prob_detach[i] + backup_started * self.discount * (value_target + start_backup_mask * target_mod_val)\n\n assert values[0].shape == value_target.shape, f\"values[0].shape : {values[0].shape} != value_target.shape : {value_target.shape}\"\n assert not value_target.requires_grad\n\n # Now the critic loss is:\n\n loss_critic = sum(mse_loss(v, value_target) for v in values)\n\n # actor loss:\n # TODO: there is probably a way of merging this with the previous for loop\n\n model_mod_val = [c(mod_augm_obs) for c in self.model_nograd.critics]\n model_mod_val = reduce(torch.min, torch.stack(model_mod_val)).squeeze() # minimum model estimate\n model_mod_val = model_mod_val * (1. - terminals)\n\n loss_actor = torch.zeros(batch_size, device=self.device)\n backup_started = torch.zeros(batch_size, device=self.device)\n for i in reversed(range(nstep_max_len + 1)):\n start_backup_mask = nstep_one_hot[:, i]\n backup_started += start_backup_mask\n loss_actor = - self.entropy_scale * self.traj_new_actions_log_prob[i] + backup_started * self.discount * (loss_actor + start_backup_mask * model_mod_val)\n loss_actor = - loss_actor.mean(0)\n\n # update model\n self.optimizer.zero_grad()\n loss_total = self.loss_alpha * loss_actor + (1 - self.loss_alpha) * loss_critic\n loss_total.backward()\n self.optimizer.step()\n\n # update target model\n exponential_moving_average(self.model_target.parameters(), self.model.parameters(), self.target_update)\n\n # exponential_moving_average(self.outputnorm_target.parameters(), self.outputnorm.parameters(), self.target_update) # this is for trying PopArt in the future\n\n return dict(\n loss_total=loss_total.detach(),\n loss_critic=loss_critic.detach(),\n loss_actor=loss_actor.detach(),\n memory_size=len(self.memory),\n )\n"
] |
[
[
"torch.zeros",
"torch.stack",
"torch.min",
"torch.max",
"torch.no_grad",
"torch.ones",
"torch.nn.functional.mse_loss",
"torch.where"
]
] |
aadland6/OutlierScores
|
[
"9044b4638f0383429d2ce67a893a4c8daceef7f1"
] |
[
"outlier_detection.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 16 08:15:33 2017\n\n@author: maadland\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom sklearn.datasets import load_digits\nfrom sklearn.decomposition import PCA\nfrom sklearn.ensemble import IsolationForest\nfrom sklearn.neighbors.lof import LocalOutlierFactor\nfrom sklearn import svm\n# from sklearn.mixture import GaussianMixture\n\n# Constants\npd.options.mode.chained_assignment = None\nRNG = np.random.RandomState(42)\n\ndef build_pca(data):\n \"\"\"Creates a PCA with two dimensions for plotting the data\n \"\"\"\n data_pca = PCA(n_components=2).fit_transform(data)\n data[\"PCA_X\"] = data_pca[:, 0]\n data[\"PCA_Y\"] = data_pca[:, 1]\n return data\n\ndef count_outliers(outlier_tuple):\n \"\"\"Counts the number of tests that identified a datapoint as an outlier\n \"\"\"\n outlier_count = 0\n for item in outlier_tuple:\n if item == -1:\n outlier_count += 1\n return outlier_count\n\ndef subset_df(data, target_col, columns, target):\n \"\"\"Creates a training and target subset for the columns\n \"\"\"\n target_subset = data[data[target_col] == target]\n training_subset = target_subset[columns]\n return target_subset, training_subset\n\ndef outlier_ensemble(data, target_col, columns):\n \"\"\"Runs outlier tests for Single Class SVM, Local Outlier Factor,\n and IsolationForest for each datapoint subsetted by its target class\n \"\"\"\n target_dfs = []\n for target in set(data[target_col]):\n target_subset, training_subset = subset_df(data, target_col, columns,\n target)\n # initalize the classifiers\n iso_clf = IsolationForest(max_samples=100, random_state=RNG)\n lof_clf = LocalOutlierFactor(n_neighbors=20)\n\n # fit the classifiers\n iso_clf.fit(training_subset)\n \n lof_predictions = lof_clf.fit_predict(training_subset)\n # Predict the classifers\n iso_predictions = iso_clf.predict(training_subset)\n \n outliers_count = [count_outliers(x) for x in zip(iso_predictions,\n lof_predictions)]\n # join the data to the subset\n target_subset[\"IsolationPrediction\"] = iso_predictions\n target_subset[\"LOFPrediction\"] = lof_predictions\n target_subset[\"OutlierCount\"] = outliers_count\n target_dfs.append(target_subset)\n joined_df = pd.concat(target_dfs)\n return joined_df\n\ndef outliers_zscore(col, threshold=3.5):\n \"\"\"Computes the modified z score for a column\n \"\"\"\n median_y = np.median(col)\n mad_y = np.median([np.abs(y - median_y) for y in col])\n if mad_y > 0:\n z_scores = [.6754 * (y - median_y) / mad_y for y in col]\n outliers = [1 if z >= threshold else 0 for z in z_scores]\n else:\n print(\"MAD is 0\")\n outliers = [0] * len(col)\n return outliers\n\ndef outliers_iqr(col):\n \"\"\"Computes the IQR and returns 1 if the data is outside the bounds\n \"\"\"\n quartile_1, quartile_3 = np.percentile(col, [25, 75])\n iqr = quartile_3 - quartile_1\n lower_bound = quartile_1 - (iqr * 1.5)\n upper_bound = quartile_3 + (iqr * 1.5)\n outliers = [1 if x > upper_bound or x < lower_bound else 0 for x in col]\n return outliers\n\ndef build_maddf(data, columns):\n \"\"\"Builds a new Dataframe with the modified Z scores on each column\n \"\"\"\n column_dict = {}\n for column in columns:\n column_key = \"{0}_MAD\".format(column)\n column_dict[column_key] = outliers_zscore(data[column])\n return column_dict\n\ndef global_mad(data, target_col, columns):\n \"\"\"Calculates the outliers for the whole dataframe\n \"\"\"\n df_list = []\n for target in set(data[target_col]):\n target_subset, training_subset = subset_df(data, target_col, columns,\n target)\n mad_df = pd.DataFrame.from_dict(build_maddf(training_subset, columns))\n df_list.append(mad_df)\n outlier_columns = pd.concat(df_list)\n return outlier_columns\n\ndef row_outliers(row):\n \"\"\"Appends the column name where an outlier was detected\n \"\"\"\n outlier_cols = []\n for item in row.index:\n if row[item] == 1:\n outlier_cols.append(item)\n return \" \".join(outlier_cols)\n\n\nif __name__ == \"__main__\":\n fuel_data = pd.read_csv(\"fuel_d_imputed.csv\")\n keep_columns = ['Fuel', 'Acid No', 'Sulfur', 'Tr-Ca', \n 'Tr-Pb', 'Tr-Na+K', 'Tr-V', '90% Rec', 'FBP', \n '%R&L', 'Flash', 'Density',\n 'Viscosity', 'Cloud Pt', 'Pour Pt', \n 'Ash', 'Carb Res', 'Acc Stab', 'PC', 'Demuls', 'Cet Indx']\n fuel_trimmed = fuel_data[keep_columns].dropna(axis=0, how=\"any\")\n sans_fuel =[x for x in keep_columns if x != \"Fuel\"]\n fuel_pre_pca = fuel_trimmed[sans_fuel]\n fuel_post_pca = build_pca(fuel_pre_pca)\n fuel_post_pca[\"Fuel\"] = fuel_trimmed[\"Fuel\"]\n outlier_df = outlier_ensemble(fuel_post_pca, target_col=\"Fuel\",\n columns=sans_fuel)\n out_columns = [\"Fuel\", \"IsolationPrediction\", \"LOFPrediction\", \"PCA_X\",\n \"PCA_Y\", \"OutlierCount\"]\n outlier_df[out_columns].to_csv(\"FuelsOutlierLabeled.csv\", index=False)"
] |
[
[
"numpy.random.RandomState",
"numpy.median",
"numpy.percentile",
"sklearn.neighbors.lof.LocalOutlierFactor",
"sklearn.ensemble.IsolationForest",
"numpy.abs",
"pandas.concat",
"pandas.read_csv",
"sklearn.decomposition.PCA"
]
] |
Weakcat/Reinforcement-Learning
|
[
"9368e13571480053a58f40f3b4fbe5b94927f3bc"
] |
[
"chapter06/cliff_walking.py"
] |
[
"#######################################################################\n# Copyright (C) #\n# 2016-2018 Shangtong Zhang(zhangshangtong.cpp@gmail.com) #\n# 2016 Kenta Shimada(hyperkentakun@gmail.com) #\n# Permission given to modify the code as long as you keep this #\n# declaration at the top #\n#######################################################################\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\n# world height\nWORLD_HEIGHT = 4\n\n# world width\nWORLD_WIDTH = 12\n\n# probability for exploration\nEPSILON = 0.1\n\n# step size\nALPHA = 0.5\n\n# gamma for Q-Learning and Expected Sarsa\nGAMMA = 1\n\n# all possible actions\nACTION_UP = 0\nACTION_DOWN = 1\nACTION_LEFT = 2\nACTION_RIGHT = 3\nACTIONS = [ACTION_UP, ACTION_DOWN, ACTION_LEFT, ACTION_RIGHT]\n\n# initial state action pair values\nSTART = [3, 0]\nGOAL = [3, 11]\n\ndef step(state, action):\n i, j = state\n if action == ACTION_UP:\n next_state = [max(i - 1, 0), j]\n elif action == ACTION_LEFT:\n next_state = [i, max(j - 1, 0)]\n elif action == ACTION_RIGHT:\n next_state = [i, min(j + 1, WORLD_WIDTH - 1)]\n elif action == ACTION_DOWN:\n next_state = [min(i + 1, WORLD_HEIGHT - 1), j]\n else:\n assert False\n\n reward = -1\n if (action == ACTION_DOWN and i == 2 and 1 <= j <= 10) or (\n action == ACTION_RIGHT and state == START):\n reward = -100\n next_state = START\n\n return next_state, reward\n\n# reward for each action in each state\n# actionRewards = np.zeros((WORLD_HEIGHT, WORLD_WIDTH, 4))\n# actionRewards[:, :, :] = -1.0\n# actionRewards[2, 1:11, ACTION_DOWN] = -100.0\n# actionRewards[3, 0, ACTION_RIGHT] = -100.0\n\n# set up destinations for each action in each state\n# actionDestination = []\n# for i in range(0, WORLD_HEIGHT):\n# actionDestination.append([])\n# for j in range(0, WORLD_WIDTH):\n# destinaion = dict()\n# destinaion[ACTION_UP] = [max(i - 1, 0), j]\n# destinaion[ACTION_LEFT] = [i, max(j - 1, 0)]\n# destinaion[ACTION_RIGHT] = [i, min(j + 1, WORLD_WIDTH - 1)]\n# if i == 2 and 1 <= j <= 10:\n# destinaion[ACTION_DOWN] = START\n# else:\n# destinaion[ACTION_DOWN] = [min(i + 1, WORLD_HEIGHT - 1), j]\n# actionDestination[-1].append(destinaion)\n# actionDestination[3][0][ACTION_RIGHT] = START\n\n# choose an action based on epsilon greedy algorithm\n# exploration and exploitation trade-off!\ndef choose_action(state, q_value):\n if np.random.binomial(1, EPSILON) == 1:\n return np.random.choice(ACTIONS)\n else:\n values_ = q_value[state[0], state[1], :]\n return np.random.choice([action_ for action_, value_ in enumerate(values_) if value_ == np.max(values_)])\n\n# an episode with Sarsa\n# @q_value: values for state action pair, will be updated\n# @expected: if True, will use expected Sarsa algorithm\n# @step_size: step size for updating\n# @return: total rewards within this episode\ndef sarsa(q_value, expected=False, step_size=ALPHA):\n state = START\n action = choose_action(state, q_value)\n rewards = 0.0\n while state != GOAL:\n next_state, reward = step(state, action)\n next_action = choose_action(next_state, q_value)\n rewards += reward\n if not expected:\n target = q_value[next_state[0], next_state[1], next_action]\n else:\n # calculate the expected value of new state\n target = 0.0\n q_next = q_value[next_state[0], next_state[1], :]\n best_actions = np.argwhere(q_next == np.max(q_next))\n for action_ in ACTIONS:\n if action_ in best_actions:\n target += ((1.0 - EPSILON) / len(best_actions) + EPSILON / len(ACTIONS)) * q_value[next_state[0], next_state[1], action_]\n else:\n target += EPSILON / len(ACTIONS) * q_value[next_state[0], next_state[1], action_]\n target *= GAMMA\n q_value[state[0], state[1], action] += step_size * (\n reward + target - q_value[state[0], state[1], action])\n state = next_state\n action = next_action\n return rewards\n\n# an episode with Q-Learning\n# @q_value: values for state action pair, will be updated\n# @step_size: step size for updating\n# @return: total rewards within this episode\ndef q_learning(q_value, step_size=ALPHA):\n state = START\n rewards = 0.0\n while state != GOAL:\n action = choose_action(state, q_value)\n next_state, reward = step(state, action)\n rewards += reward\n # Q-Learning update\n q_value[state[0], state[1], action] += step_size * (\n reward + GAMMA * np.max(q_value[next_state[0], next_state[1], :]) -\n q_value[state[0], state[1], action])\n state = next_state\n return rewards\n\n# print optimal policy\ndef print_optimal_policy(q_value):\n optimal_policy = []\n for i in range(0, WORLD_HEIGHT):\n optimal_policy.append([])\n for j in range(0, WORLD_WIDTH):\n if [i, j] == GOAL:\n optimal_policy[-1].append('G')\n continue\n bestAction = np.argmax(q_value[i, j, :])\n if bestAction == ACTION_UP:\n optimal_policy[-1].append('U')\n elif bestAction == ACTION_DOWN:\n optimal_policy[-1].append('D')\n elif bestAction == ACTION_LEFT:\n optimal_policy[-1].append('L')\n elif bestAction == ACTION_RIGHT:\n optimal_policy[-1].append('R')\n for row in optimal_policy:\n print(row)\n\n# Use multiple runs instead of a single run and a sliding window\n# With a single run I failed to present a smooth curve\n# However the optimal policy converges well with a single run\n# Sarsa converges to the safe path, while Q-Learning converges to the optimal path\ndef figure_6_4():\n # episodes of each run\n episodes = 500\n\n # perform 40 independent runs\n runs = 50\n\n rewards_sarsa = np.zeros(episodes)\n rewards_q_learning = np.zeros(episodes)\n for r in tqdm(range(runs)):\n q_sarsa = np.zeros((WORLD_HEIGHT, WORLD_WIDTH, 4))\n q_q_learning = np.copy(q_sarsa)\n for i in range(0, episodes):\n # cut off the value by -100 to draw the figure more elegantly\n # rewards_sarsa[i] += max(sarsa(q_sarsa), -100)\n # rewards_q_learning[i] += max(q_learning(q_q_learning), -100)\n rewards_sarsa[i] += sarsa(q_sarsa)\n rewards_q_learning[i] += q_learning(q_q_learning)\n\n # averaging over independt runs\n rewards_sarsa /= runs\n rewards_q_learning /= runs\n\n # draw reward curves\n plt.plot(rewards_sarsa, label='Sarsa')\n plt.plot(rewards_q_learning, label='Q-Learning')\n plt.xlabel('Episodes')\n plt.ylabel('Sum of rewards during episode')\n plt.ylim([-100, 0])\n plt.legend()\n\n plt.savefig('../images/figure_6_4.png')\n plt.close()\n\n # display optimal policy\n print('Sarsa Optimal Policy:')\n print_optimal_policy(q_sarsa)\n print('Q-Learning Optimal Policy:')\n print_optimal_policy(q_q_learning)\n\n# Due to limited capacity of calculation of my machine, I can't complete this experiment\n# with 100,000 episodes and 50,000 runs to get the fully averaged performance\n# However even I only play for 1,000 episodes and 10 runs, the curves looks still good.\ndef figure_6_6():\n step_sizes = np.arange(0.1, 1.1, 0.1)\n episodes = 1000\n runs = 10\n\n ASY_SARSA = 0\n ASY_EXPECTED_SARSA = 1\n ASY_QLEARNING = 2\n INT_SARSA = 3\n INT_EXPECTED_SARSA = 4\n INT_QLEARNING = 5\n methods = range(0, 6)\n\n performace = np.zeros((6, len(step_sizes)))\n for run in range(runs):\n for ind, step_size in tqdm(list(zip(range(0, len(step_sizes)), step_sizes))):\n q_sarsa = np.zeros((WORLD_HEIGHT, WORLD_WIDTH, 4))\n q_expected_sarsa = np.copy(q_sarsa)\n q_q_learning = np.copy(q_sarsa)\n for ep in range(episodes):\n sarsa_reward = sarsa(q_sarsa, expected=False, step_size=step_size)\n expected_sarsa_reward = sarsa(q_expected_sarsa, expected=True, step_size=step_size)\n q_learning_reward = q_learning(q_q_learning, step_size=step_size)\n performace[ASY_SARSA, ind] += sarsa_reward\n performace[ASY_EXPECTED_SARSA, ind] += expected_sarsa_reward\n performace[ASY_QLEARNING, ind] += q_learning_reward\n\n if ep < 100:\n performace[INT_SARSA, ind] += sarsa_reward\n performace[INT_EXPECTED_SARSA, ind] += expected_sarsa_reward\n performace[INT_QLEARNING, ind] += q_learning_reward\n\n performace[:3, :] /= episodes * runs\n performace[3:, :] /= 100 * runs\n labels = ['Asymptotic Sarsa', 'Asymptotic Expected Sarsa', 'Asymptotic Q-Learning',\n 'Interim Sarsa', 'Interim Expected Sarsa', 'Interim Q-Learning']\n\n for method, label in zip(methods, labels):\n plt.plot(step_sizes, performace[method, :], label=label)\n plt.xlabel('alpha')\n plt.ylabel('reward per episode')\n plt.legend()\n\n plt.savefig('../images/figure_6_6.png')\n plt.close()\n\nif __name__ == '__main__':\n figure_6_4()\n figure_6_6()\n"
] |
[
[
"matplotlib.use",
"numpy.max",
"numpy.random.binomial",
"numpy.random.choice",
"numpy.zeros",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.close",
"numpy.copy",
"numpy.arange",
"numpy.argmax",
"matplotlib.pyplot.ylabel"
]
] |
colinpoler/case-name-changer
|
[
"e3cd3880607f2eacb567e97188f04da7b2728f3e"
] |
[
"nameutils.py"
] |
[
"import re\nimport pandas as pd\nimport json\nimport random\nfrom functools import partial\n\n# Tzioumis, Konstantinos (2018) Demographic aspects of first names, Scientific Data, 5:180025 [dx.doi.org/10.1038/sdata.2018.25].\nfirstnames=pd.read_csv('firstnames.csv')\n# https://github.com/fivethirtyeight/data/tree/master/most-common-name\nsurnames=pd.read_csv('surnames.csv')\n\nfirstnames_set = set(firstnames['name'])\nsurnames_set = set(surnames['name'])\n\ndef is_wordpair_name(wordpair):\n firstname, surname = wordpair\n if surname == 'Booth':\n print(firstname, surname)\n\n # If it's not title case, it's not a name\n if not (firstname.title() == firstname and surname.title() == surname):\n return False\n\n # If first and last name not in database, it's not a name\n if not (firstname.title() in firstnames_set and surname.title() in surnames_set):\n return False\n\n # If the firstname is too rare, it's not a name\n rowfirstname = firstnames.loc[firstnames['name'] == firstname.title()]\n if rowfirstname['count'].values < 10:\n return False\n\n # If the surname is too rare, it's not a name\n rowsurname = surnames.loc[surnames['name'] == surname.title()]\n if rowsurname['count'].values < 300:\n return False\n\n # It's probably a name!\n return True\n\ndef find_names(text):\n words = text.split()\n wordpairs = [(words[i], words[i+1]) for i in range(len(words) - 1)]\n\n names = set([wp for wp in wordpairs if is_wordpair_name(wp)])\n return names\n\nrace_codes = [\n ('white', [r'white', r'european', r'caucasian'], 65),\n ('black', [r'black', r'african([\\s\\-]american)?'], 11),\n ('api', [r'asian', r'(pacific )?islander', r'arabic', r'middle eastern'], 5),\n ('aian', [r'native([\\s\\-]american)?', r'alaska([\\s\\-]native)'], 1),\n ('hispanic', [r'hispanic', r'latin(o|a|x)'], 15),\n ('2prace', [r'biracial'], 2),\n]\ndef get_race_code(race):\n if race is None:\n return random.choice(race_codes)[0]\n for race_code, patterns, pct in race_codes:\n if any(re.match(p, race) for p in patterns):\n return race_code\n return '2prace'\n\nsuggested_names_used = []\ndef suggest_name(firstnamelen, surnamelen, race_code=None):\n global suggested_names_used\n # Choose valid lengths\n valid_firstnames = firstnames.loc[(firstnames['name'].str.len() <= firstnamelen) & ~surnames['name'].isin(suggested_names_used)].copy()\n valid_surnames = surnames.loc[(surnames['name'].str.len() <= surnamelen) & ~surnames['name'].isin(suggested_names_used)].copy()\n\n if race_code is not None:\n pct_race = next(pct for code, patterns, pct in race_codes if code == race_code)\n race_code = 'pct' + race_code\n\n # Make sure it is likely the right race\n valid_firstnames = valid_firstnames.loc[valid_firstnames[race_code] / pct_race > 1]\n valid_surnames = valid_surnames.loc[valid_surnames[race_code] / pct_race > 1]\n \n # Modify the weights based on pct of this race\n valid_firstnames['count'] *= valid_firstnames[race_code]\n valid_surnames['count'] *= valid_surnames[race_code]\n\n # Choose randomly based on count\n firstname = valid_firstnames.sample(1, weights=valid_firstnames['count'])['name'].iloc[0]\n surname = valid_surnames.sample(1, weights=valid_surnames['count'])['name'].iloc[0]\n\n suggested_names_used += [firstname, surname]\n return firstname, surname\n\ndef get_suggestions(old_names, race=None):\n return {old: suggest_name(len(old[0]), len(old[1]), get_race_code(race)) for old in old_names}\n\ndef stringify(t):\n return \"{} {}\".format(t[0], t[1])\ndef tuplify(s):\n return tuple(s.split())\n\ndef case_insensitive_replacer(old, new):\n return partial(re.sub, old, new, flags=re.IGNORECASE)\ndef get_group(s):\n return s.group()\ndef compose(*fs):\n def func(x):\n result = x\n for f in fs:\n result = f(result)\n return result\n return func\ndef make_replacers(names):\n replacers = []\n for old, new in names.items():\n # First in tuple is regex to match either full name, first name or last name\n regex = re.compile('\\s({}\\s{}|{}|{})\\s'.format(old[0],old[1],old[0],old[1]), flags=re.IGNORECASE)\n # Second in tuple is a function to change either full name, first name or last name to corresponding new name\n func = compose(get_group, case_insensitive_replacer(old[0], new[0]), case_insensitive_replacer(old[1], new[1]))\n \n replacers.append((regex, func))\n return replacers\n\n"
] |
[
[
"pandas.read_csv"
]
] |
BU-Lisp/ogb
|
[
"882786c0b71f5c836275c03b8554ad919bfe34e4",
"1d6dde8080261931bc6ce2491e9149298af1ea98"
] |
[
"examples/linkproppred/wikikg2/run.py",
"examples/graphproppred/code/main_pyg.py"
] |
[
"#!/usr/bin/python3\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport json\nimport logging\nimport os\nimport re\nimport random\n\nimport numpy as np\nimport torch\n\nfrom torch.utils.data import DataLoader\n\nfrom model import KGEModel\n\nfrom dataloader import TrainDataset\nfrom dataloader import BidirectionalOneShotIterator\n\nfrom ogb.linkproppred import LinkPropPredDataset, Evaluator\nfrom collections import defaultdict\nfrom tqdm import tqdm\nimport time\nfrom tensorboardX import SummaryWriter\n\ndef parse_args(args=None):\n parser = argparse.ArgumentParser(\n description='Training and Testing Knowledge Graph Embedding Models',\n usage='train.py [<args>] [-h | --help]'\n )\n\n parser.add_argument('--cuda', action='store_true', help='use GPU')\n parser.add_argument('--meta_dict', type=str, default='', help='name of dictionary')\n parser.add_argument('--do_train', action='store_true')\n parser.add_argument('--do_valid', action='store_true')\n parser.add_argument('--do_test', action='store_true')\n parser.add_argument('--evaluate_train', action='store_true', help='Evaluate on training data')\n \n parser.add_argument('--dataset', type=str, default='ogbl-wikikg2', help='dataset name, default to wikikg2')\n parser.add_argument('--split', default='', type=str)\n parser.add_argument('--add_random_fraction', default=0.0, type=float, help='add N*arg random edges to train, all of a new edge type')\n parser.add_argument('--seed', default=1234, type=int)\n parser.add_argument('--model', default='TransE', type=str)\n parser.add_argument('-de', '--double_entity_embedding', action='store_true')\n parser.add_argument('-dr', '--double_relation_embedding', action='store_true')\n \n parser.add_argument('-n', '--negative_sample_size', default=128, type=int)\n parser.add_argument('-d', '--hidden_dim', default=500, type=int)\n parser.add_argument('-g', '--gamma', default=12.0, type=float)\n parser.add_argument('-adv', '--negative_adversarial_sampling', action='store_true')\n parser.add_argument('-a', '--adversarial_temperature', default=1.0, type=float)\n parser.add_argument('-b', '--batch_size', default=1024, type=int)\n parser.add_argument('-r', '--regularization', default=0.0, type=float)\n parser.add_argument('--test_batch_size', default=4, type=int, help='valid/test batch size')\n parser.add_argument('--uni_weight', action='store_true', \n help='Otherwise use subsampling weighting like in word2vec')\n \n parser.add_argument('-lr', '--learning_rate', default=0.0001, type=float)\n parser.add_argument('-cpu', '--cpu_num', default=10, type=int)\n parser.add_argument('-init', '--init_checkpoint', default=None, type=str)\n parser.add_argument('-save', '--save_path', default=None, type=str)\n parser.add_argument('--max_steps', default=100000, type=int)\n parser.add_argument('--warm_up_steps', default=None, type=int)\n \n parser.add_argument('--save_checkpoint_steps', default=10000, type=int)\n parser.add_argument('--valid_steps', default=10000, type=int)\n parser.add_argument('--log_steps', default=100, type=int, help='train log every xx steps')\n parser.add_argument('--test_log_steps', default=1000, type=int, help='valid/test log every xx steps')\n \n parser.add_argument('--nentity', type=int, default=0, help='DO NOT MANUALLY SET')\n parser.add_argument('--nrelation', type=int, default=0, help='DO NOT MANUALLY SET')\n \n parser.add_argument('--print_on_screen', action='store_true', help='log on screen or not')\n parser.add_argument('--ntriples_eval_train', type=int, default=200000, help='number of training triples to evaluate eventually')\n parser.add_argument('--neg_size_eval_train', type=int, default=500, help='number of negative samples when evaluating training triples')\n parser.add_argument('--test_random_sample', action='store_true' )\n parser.add_argument('--dump_train', action='store_true' )\n parser.add_argument('--extra_test_statistics', action='store_true' )\n\n return parser.parse_args(args)\n\ndef override_config(args):\n '''\n Override model and data configuration\n '''\n \n with open(os.path.join(args.init_checkpoint, 'config.json'), 'r') as fjson:\n argparse_dict = json.load(fjson)\n \n# args.dataset = argparse_dict['dataset']\n args.model = argparse_dict['model']\n args.double_entity_embedding = argparse_dict['double_entity_embedding']\n args.double_relation_embedding = argparse_dict['double_relation_embedding']\n args.hidden_dim = argparse_dict['hidden_dim']\n args.test_batch_size = argparse_dict['test_batch_size']\n args.gamma = argparse_dict['gamma']\n\ndef save_model(model, optimizer, save_variable_list, args):\n '''\n Save the parameters of the model and the optimizer,\n as well as some other variables such as step and learning_rate\n '''\n \n argparse_dict = vars(args)\n with open(os.path.join(args.save_path, 'config.json'), 'w') as fjson:\n json.dump(argparse_dict, fjson)\n\n torch.save({\n **save_variable_list,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict()},\n os.path.join(args.save_path, 'checkpoint')\n )\n \n entity_embedding = model.entity_embedding.detach().cpu().numpy()\n np.save(\n os.path.join(args.save_path, 'entity_embedding'), \n entity_embedding\n )\n \n relation_embedding = model.relation_embedding.detach().cpu().numpy()\n np.save(\n os.path.join(args.save_path, 'relation_embedding'), \n relation_embedding\n )\n\ndef set_logger(args):\n '''\n Write logs to checkpoint and console\n '''\n\n if args.do_train:\n log_file = os.path.join(args.save_path or args.init_checkpoint, 'train.log')\n else:\n log_file = os.path.join(args.save_path or args.init_checkpoint, 'test.log')\n print( 'Starting logging to ', log_file )\n\n logging.basicConfig(\n format='%(asctime)s %(levelname)-8s %(message)s',\n level=logging.INFO,\n datefmt='%Y-%m-%d %H:%M:%S',\n filename=log_file,\n filemode='w'\n )\n\n if args.print_on_screen:\n console = logging.StreamHandler()\n console.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')\n console.setFormatter(formatter)\n logging.getLogger('').addHandler(console)\n\ndef log_metrics(mode, step, metrics, writer):\n '''\n Print the evaluation logs\n '''\n for metric in metrics:\n logging.info('%s %s at step %d: %f' % (mode, metric, step, metrics[metric]))\n writer.add_scalar(\"_\".join([mode, metric]), metrics[metric], step)\n \n\ndef append_rng( args, nentity, set_relation, train_triples ):\n import networkx as nx\n edge_probability = args.add_random_fraction*len(train_triples['head'])/nentity/nentity\n logging.info('add_random_fraction (* # train edges): %f' % args.add_random_fraction)\n logging.info('edge_probability: %.8f' % edge_probability)\n logging.info('seed: %d' % args.seed)\n g = nx.fast_gnp_random_graph(nentity, edge_probability, seed=args.seed, directed=True)\n edges = np.array(g.edges)\n return { 'head': np.concatenate([train_triples['head'],edges[:,0]]),\n 'tail': np.concatenate([train_triples['tail'],edges[:,1]]),\n 'relation': np.concatenate([train_triples['relation'],np.full(edges.shape[0],set_relation)]) }\n \ndef main(args):\n if (not args.do_train) and (not args.do_valid) and (not args.do_test) and (not args.evaluate_train):\n raise ValueError('one of train/val/test mode must be chosen')\n \n if args.init_checkpoint:\n override_config(args)\n\n run_label = ''\n if args.save_path and args.save_path[-1]=='-': \n ( run_label, args.save_path ) = ( args.save_path, None )\n if args.save_path == None:\n args.save_path = 'log/%s/%s/%s%s-%s/%s'%(args.dataset, args.model, run_label, args.hidden_dim, args.gamma, time.time())\n writer = SummaryWriter(args.save_path)\n \n # Write logs to checkpoint and console\n set_logger(args)\n\n if args.meta_dict=='':\n meta = 'dataset_' + re.sub('-','_',args.dataset) + '/meta_dict.pt'\n if os.path.exists(meta):\n args.meta_dict = meta\n \n if args.meta_dict!='':\n meta_dict = torch.load(args.meta_dict)\n print( meta_dict )\n dataset = LinkPropPredDataset(name = args.dataset, meta_dict=meta_dict)\n else:\n meta_dict = None\n dataset = LinkPropPredDataset(name = args.dataset)\n\n\n if args.split!='':\n split_dict = dataset.get_edge_split(split_type=args.split)\n else:\n split_dict = dataset.get_edge_split()\n nentity = int(dataset.graph['num_nodes'])\n nrelation = int(max(dataset.graph['edge_reltype'])[0])+1\n\n evaluator = Evaluator(name = args.dataset, meta_info=meta_dict)\n\n args.nentity = nentity\n args.nrelation = nrelation\n if args.add_random_fraction>0:\n nrelation += 1\n \n logging.info('Model: %s' % args.model)\n logging.info('Dataset: %s' % args.dataset)\n if args.split!='':\n logging.info('Split: %s' % args.split)\n logging.info('#entity: %d' % nentity)\n logging.info('#relation: %d' % nrelation)\n \n train_triples = split_dict['train']\n if args.add_random_fraction>0:\n train_triples = append_rng( args, nentity, nrelation-1, train_triples )\n if args.dump_train:\n for i in range(train_triples['head'].shape[0]):\n print( train_triples['head'][i],train_triples['relation'][i],train_triples['tail'][i], sep=',' )\n exit(0)\n logging.info('#train: %d' % len(train_triples['head']))\n valid_triples = split_dict['valid']\n logging.info('#valid: %d' % len(valid_triples['head']))\n test_triples = split_dict['test']\n logging.info('#test: %d' % len(test_triples['head']))\n\n train_count, train_true_head, train_true_tail = defaultdict(lambda: 4), defaultdict(list), defaultdict(list)\n for i in tqdm(range(len(train_triples['head']))):\n head, relation, tail = train_triples['head'][i], train_triples['relation'][i], train_triples['tail'][i]\n train_count[(head, relation)] += 1\n train_count[(tail, -relation-1)] += 1\n train_true_head[(relation, tail)].append(head)\n train_true_tail[(head, relation)].append(tail)\n \n kge_model = KGEModel(\n model_name=args.model,\n nentity=nentity,\n nrelation=nrelation,\n hidden_dim=args.hidden_dim,\n gamma=args.gamma,\n double_entity_embedding=args.double_entity_embedding,\n double_relation_embedding=args.double_relation_embedding,\n evaluator=evaluator\n )\n \n logging.info('Model Parameter Configuration:')\n for name, param in kge_model.named_parameters():\n logging.info('Parameter %s: %s, require_grad = %s' % (name, str(param.size()), str(param.requires_grad)))\n\n if args.cuda:\n kge_model = kge_model.cuda()\n \n if args.do_train:\n # Set training dataloader iterator\n train_dataloader_head = DataLoader(\n TrainDataset(train_triples, nentity, nrelation, \n args.negative_sample_size, 'head-batch',\n train_count, train_true_head, train_true_tail), \n batch_size=args.batch_size,\n shuffle=True, \n num_workers=max(1, args.cpu_num//2),\n collate_fn=TrainDataset.collate_fn\n )\n \n train_dataloader_tail = DataLoader(\n TrainDataset(train_triples, nentity, nrelation, \n args.negative_sample_size, 'tail-batch',\n train_count, train_true_head, train_true_tail), \n batch_size=args.batch_size,\n shuffle=True, \n num_workers=max(1, args.cpu_num//2),\n collate_fn=TrainDataset.collate_fn\n )\n \n train_iterator = BidirectionalOneShotIterator(train_dataloader_head, train_dataloader_tail)\n \n # Set training configuration\n current_learning_rate = args.learning_rate\n optimizer = torch.optim.Adam(\n filter(lambda p: p.requires_grad, kge_model.parameters()), \n lr=current_learning_rate\n )\n if args.warm_up_steps:\n warm_up_steps = args.warm_up_steps\n else:\n warm_up_steps = args.max_steps // 2\n\n if args.init_checkpoint:\n # Restore model from checkpoint directory\n logging.info('Loading checkpoint %s...' % args.init_checkpoint)\n checkpoint = torch.load(os.path.join(args.init_checkpoint, 'checkpoint'))\n init_step = checkpoint['step']\n kge_model.load_state_dict(checkpoint['model_state_dict'])\n if args.do_train:\n current_learning_rate = checkpoint['current_learning_rate']\n warm_up_steps = checkpoint['warm_up_steps']\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n else:\n logging.info('Ramdomly Initializing %s Model...' % args.model)\n init_step = 0\n \n step = init_step\n \n logging.info('Start Training...')\n logging.info('init_step = %d' % init_step)\n logging.info('batch_size = %d' % args.batch_size)\n logging.info('negative_adversarial_sampling = %d' % args.negative_adversarial_sampling)\n logging.info('hidden_dim = %d' % args.hidden_dim)\n logging.info('gamma = %f' % args.gamma)\n logging.info('negative_adversarial_sampling = %s' % str(args.negative_adversarial_sampling))\n if args.negative_adversarial_sampling:\n logging.info('adversarial_temperature = %f' % args.adversarial_temperature)\n \n # Set valid dataloader as it would be evaluated during training\n \n if args.do_train:\n logging.info('learning_rate = %f' % current_learning_rate)\n\n training_logs = []\n \n #Training Loop\n for step in range(init_step, args.max_steps):\n \n log = kge_model.train_step(kge_model, optimizer, train_iterator, args)\n training_logs.append(log)\n \n if step >= warm_up_steps:\n current_learning_rate = current_learning_rate / 10\n logging.info('Change learning_rate to %f at step %d' % (current_learning_rate, step))\n optimizer = torch.optim.Adam(\n filter(lambda p: p.requires_grad, kge_model.parameters()), \n lr=current_learning_rate\n )\n warm_up_steps = warm_up_steps * 3\n \n if step % args.save_checkpoint_steps == 0 and step > 0: # ~ 41 seconds/saving\n save_variable_list = {\n 'step': step, \n 'current_learning_rate': current_learning_rate,\n 'warm_up_steps': warm_up_steps\n }\n save_model(kge_model, optimizer, save_variable_list, args)\n\n if step % args.log_steps == 0:\n metrics = {}\n for metric in training_logs[0].keys():\n metrics[metric] = sum([log[metric] for log in training_logs])/len(training_logs)\n log_metrics('Train', step, metrics, writer)\n training_logs = []\n \n if args.do_valid and step % args.valid_steps == 0 and step > 0:\n logging.info('Evaluating on Valid Dataset...')\n metrics = kge_model.test_step(kge_model, valid_triples, args, random_sampling=args.test_random_sample)\n log_metrics('Valid', step, metrics, writer)\n \n save_variable_list = {\n 'step': step, \n 'current_learning_rate': current_learning_rate,\n 'warm_up_steps': warm_up_steps\n }\n save_model(kge_model, optimizer, save_variable_list, args)\n \n if args.do_valid:\n logging.info('Evaluating on Valid Dataset...')\n metrics = kge_model.test_step(kge_model, valid_triples, args, random_sampling=args.test_random_sample)\n log_metrics('Valid', step, metrics, writer)\n \n if args.do_test:\n logging.info('Evaluating on Test Dataset...')\n metrics = kge_model.test_step(kge_model, test_triples, args, random_sampling=args.test_random_sample)\n log_metrics('Test', step, metrics, writer)\n \n if args.evaluate_train:\n logging.info('Evaluating on Training Dataset...')\n small_train_triples = {}\n indices = np.random.choice(len(train_triples['head']), args.ntriples_eval_train, replace=False)\n for i in train_triples:\n small_train_triples[i] = train_triples[i][indices]\n metrics = kge_model.test_step(kge_model, small_train_triples, args, random_sampling=True)\n log_metrics('Train', step, metrics, writer)\n \nif __name__ == '__main__':\n main(parse_args())\n",
"import torch\nfrom torch_geometric.data import DataLoader\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torchvision import transforms\nfrom gnn import GNN\n\nfrom tqdm import tqdm\nimport argparse\nimport time\nimport numpy as np\nimport pandas as pd\nimport os\n\n### importing OGB\nfrom ogb.graphproppred import PygGraphPropPredDataset, Evaluator\n\n### importing utils\nfrom utils import ASTNodeEncoder, get_vocab_mapping\n### for data transform\nfrom utils import augment_edge, encode_y_to_arr, decode_arr_to_seq\n\n\nmulticls_criterion = torch.nn.CrossEntropyLoss()\n\ndef train(model, device, loader, optimizer):\n model.train()\n\n loss_accum = 0\n for step, batch in enumerate(tqdm(loader, desc=\"Iteration\")):\n batch = batch.to(device)\n\n if batch.x.shape[0] == 1 or batch.batch[-1] == 0:\n pass\n else:\n pred_list = model(batch)\n optimizer.zero_grad()\n\n loss = 0\n for i in range(len(pred_list)):\n loss += multicls_criterion(pred_list[i].to(torch.float32), batch.y_arr[:,i])\n\n loss = loss / len(pred_list)\n \n loss.backward()\n optimizer.step()\n\n loss_accum += loss.item()\n\n print('Average training loss: {}'.format(loss_accum / (step + 1)))\n\ndef eval(model, device, loader, evaluator, arr_to_seq):\n model.eval()\n seq_ref_list = []\n seq_pred_list = []\n\n for step, batch in enumerate(tqdm(loader, desc=\"Iteration\")):\n batch = batch.to(device)\n\n if batch.x.shape[0] == 1:\n pass\n else:\n with torch.no_grad():\n pred_list = model(batch)\n\n mat = []\n for i in range(len(pred_list)):\n mat.append(torch.argmax(pred_list[i], dim = 1).view(-1,1))\n mat = torch.cat(mat, dim = 1)\n \n seq_pred = [arr_to_seq(arr) for arr in mat]\n \n # PyG = 1.4.3\n # seq_ref = [batch.y[i][0] for i in range(len(batch.y))]\n\n # PyG >= 1.5.0\n seq_ref = [batch.y[i] for i in range(len(batch.y))]\n\n seq_ref_list.extend(seq_ref)\n seq_pred_list.extend(seq_pred)\n\n input_dict = {\"seq_ref\": seq_ref_list, \"seq_pred\": seq_pred_list}\n\n return evaluator.eval(input_dict)\n\ndef main():\n # Training settings\n parser = argparse.ArgumentParser(description='GNN baselines on ogbg-code data with Pytorch Geometrics')\n parser.add_argument('--device', type=int, default=0,\n help='which gpu to use if any (default: 0)')\n parser.add_argument('--gnn', type=str, default='gcn-virtual',\n help='GNN gin, gin-virtual, or gcn, or gcn-virtual (default: gcn-virtual)')\n parser.add_argument('--drop_ratio', type=float, default=0,\n help='dropout ratio (default: 0)')\n parser.add_argument('--max_seq_len', type=int, default=5,\n help='maximum sequence length to predict (default: 5)')\n parser.add_argument('--num_vocab', type=int, default=5000,\n help='the number of vocabulary used for sequence prediction (default: 5000)')\n parser.add_argument('--num_layer', type=int, default=5,\n help='number of GNN message passing layers (default: 5)')\n parser.add_argument('--emb_dim', type=int, default=300,\n help='dimensionality of hidden units in GNNs (default: 300)')\n parser.add_argument('--batch_size', type=int, default=128,\n help='input batch size for training (default: 128)')\n parser.add_argument('--epochs', type=int, default=30,\n help='number of epochs to train (default: 30)')\n parser.add_argument('--num_workers', type=int, default=0,\n help='number of workers (default: 0)')\n parser.add_argument('--dataset', type=str, default=\"ogbg-code\",\n help='dataset name (default: ogbg-code)')\n\n parser.add_argument('--filename', type=str, default=\"\",\n help='filename to output result (default: )')\n args = parser.parse_args()\n\n device = torch.device(\"cuda:\" + str(args.device)) if torch.cuda.is_available() else torch.device(\"cpu\")\n\n ### automatic dataloading and splitting\n dataset = PygGraphPropPredDataset(name = args.dataset)\n\n seq_len_list = np.array([len(seq) for seq in dataset.data.y])\n print('Target seqence less or equal to {} is {}%.'.format(args.max_seq_len, np.sum(seq_len_list <= args.max_seq_len) / len(seq_len_list)))\n\n split_idx = dataset.get_idx_split()\n\n # print(split_idx['train'])\n # print(split_idx['valid'])\n # print(split_idx['test'])\n\n # train_method_name = [' '.join(dataset.data.y[i]) for i in split_idx['train']]\n # valid_method_name = [' '.join(dataset.data.y[i]) for i in split_idx['valid']]\n # test_method_name = [' '.join(dataset.data.y[i]) for i in split_idx['test']]\n # print('#train')\n # print(len(train_method_name))\n # print('#valid')\n # print(len(valid_method_name))\n # print('#test')\n # print(len(test_method_name))\n\n # train_method_name_set = set(train_method_name)\n # valid_method_name_set = set(valid_method_name)\n # test_method_name_set = set(test_method_name)\n\n # # unique method name\n # print('#unique train')\n # print(len(train_method_name_set))\n # print('#unique valid')\n # print(len(valid_method_name_set))\n # print('#unique test')\n # print(len(test_method_name_set))\n\n # # unique valid/test method name\n # print('#valid unseen during training')\n # print(len(valid_method_name_set - train_method_name_set))\n # print('#test unseen during training')\n # print(len(test_method_name_set - train_method_name_set))\n\n\n ### building vocabulary for sequence predition. Only use training data.\n\n vocab2idx, idx2vocab = get_vocab_mapping([dataset.data.y[i] for i in split_idx['train']], args.num_vocab)\n\n # test encoder and decoder\n # for data in dataset:\n # # PyG >= 1.5.0\n # print(data.y)\n #\n # # PyG 1.4.3\n # # print(data.y[0])\n # data = encode_y_to_arr(data, vocab2idx, args.max_seq_len)\n # print(data.y_arr[0])\n # decoded_seq = decode_arr_to_seq(data.y_arr[0], idx2vocab)\n # print(decoded_seq)\n # print('')\n\n ## test augment_edge\n # data = dataset[2]\n # print(data)\n # data_augmented = augment_edge(data)\n # print(data_augmented)\n\n ### set the transform function\n # augment_edge: add next-token edge as well as inverse edges. add edge attributes.\n # encode_y_to_arr: add y_arr to PyG data object, indicating the array representation of a sequence.\n dataset.transform = transforms.Compose([augment_edge, lambda data: encode_y_to_arr(data, vocab2idx, args.max_seq_len)])\n\n ### automatic evaluator. takes dataset name as input\n evaluator = Evaluator(args.dataset)\n\n train_loader = DataLoader(dataset[split_idx[\"train\"]], batch_size=args.batch_size, shuffle=True, num_workers = args.num_workers)\n valid_loader = DataLoader(dataset[split_idx[\"valid\"]], batch_size=args.batch_size, shuffle=False, num_workers = args.num_workers)\n test_loader = DataLoader(dataset[split_idx[\"test\"]], batch_size=args.batch_size, shuffle=False, num_workers = args.num_workers)\n\n nodetypes_mapping = pd.read_csv(os.path.join(dataset.root, 'mapping', 'typeidx2type.csv.gz'))\n nodeattributes_mapping = pd.read_csv(os.path.join(dataset.root, 'mapping', 'attridx2attr.csv.gz'))\n\n ### Encoding node features into emb_dim vectors.\n ### The following three node features are used.\n # 1. node type\n # 2. node attribute\n # 3. node depth\n node_encoder = ASTNodeEncoder(args.emb_dim, num_nodetypes = len(nodetypes_mapping['type']), num_nodeattributes = len(nodeattributes_mapping['attr']), max_depth = 20)\n\n if args.gnn == 'gin':\n model = GNN(num_vocab = len(vocab2idx), max_seq_len = args.max_seq_len, node_encoder = node_encoder, num_layer = args.num_layer, gnn_type = 'gin', emb_dim = args.emb_dim, drop_ratio = args.drop_ratio, virtual_node = False).to(device)\n elif args.gnn == 'gin-virtual':\n model = GNN(num_vocab = len(vocab2idx), max_seq_len = args.max_seq_len, node_encoder = node_encoder, num_layer = args.num_layer, gnn_type = 'gin', emb_dim = args.emb_dim, drop_ratio = args.drop_ratio, virtual_node = True).to(device)\n elif args.gnn == 'gcn':\n model = GNN(num_vocab = len(vocab2idx), max_seq_len = args.max_seq_len, node_encoder = node_encoder, num_layer = args.num_layer, gnn_type = 'gcn', emb_dim = args.emb_dim, drop_ratio = args.drop_ratio, virtual_node = False).to(device)\n elif args.gnn == 'gcn-virtual':\n model = GNN(num_vocab = len(vocab2idx), max_seq_len = args.max_seq_len, node_encoder = node_encoder, num_layer = args.num_layer, gnn_type = 'gcn', emb_dim = args.emb_dim, drop_ratio = args.drop_ratio, virtual_node = True).to(device)\n else:\n raise ValueError('Invalid GNN type')\n\n optimizer = optim.Adam(model.parameters(), lr=0.001)\n\n valid_curve = []\n test_curve = []\n train_curve = []\n\n for epoch in range(1, args.epochs + 1):\n print(\"=====Epoch {}\".format(epoch))\n print('Training...')\n train(model, device, train_loader, optimizer)\n\n print('Evaluating...')\n train_perf = eval(model, device, train_loader, evaluator, arr_to_seq = lambda arr: decode_arr_to_seq(arr, idx2vocab))\n valid_perf = eval(model, device, valid_loader, evaluator, arr_to_seq = lambda arr: decode_arr_to_seq(arr, idx2vocab))\n test_perf = eval(model, device, test_loader, evaluator, arr_to_seq = lambda arr: decode_arr_to_seq(arr, idx2vocab))\n\n\n print({'Train': train_perf, 'Validation': valid_perf, 'Test': test_perf})\n\n train_curve.append(train_perf[dataset.eval_metric])\n valid_curve.append(valid_perf[dataset.eval_metric])\n test_curve.append(test_perf[dataset.eval_metric])\n\n print('F1')\n best_val_epoch = np.argmax(np.array(valid_curve))\n best_train = max(train_curve)\n print('Finished training!')\n print('Best validation score: {}'.format(valid_curve[best_val_epoch]))\n print('Test score: {}'.format(test_curve[best_val_epoch]))\n\n if not args.filename == '':\n result_dict = {'Val': valid_curve[best_val_epoch], 'Test': test_curve[best_val_epoch], 'Train': train_curve[best_val_epoch], 'BestTrain': best_train}\n torch.save(result_dict, args.filename)\n\n\nif __name__ == \"__main__\":\n main()"
] |
[
[
"numpy.concatenate",
"numpy.full",
"numpy.array",
"torch.load"
],
[
"torch.device",
"numpy.array",
"torch.cat",
"torch.argmax",
"numpy.sum",
"torch.save",
"torch.no_grad",
"torch.cuda.is_available",
"torch.nn.CrossEntropyLoss"
]
] |
OsmanMalik/TM-GCN
|
[
"275d057a7261d8e6b544dad66b7daa7943d11c4f",
"275d057a7261d8e6b544dad66b7daa7943d11c4f"
] |
[
"TM-GCN-master/experiment_amlsim_baseline.py",
"TM-GCN-master/embedding_help_functions.py"
] |
[
"# This version of the amlsim experiment imports data preprocessed in Matlab, and uses the GCN baseline\n\n# Imports and aliases\nimport pickle\nimport torch as t\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.datasets as datasets\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cProfile\nimport pandas as pd\nimport datetime\nfrom scipy.sparse import csr_matrix\nimport os.path\nimport embedding_help_functions as ehf\nimport scipy.io as sio\nunsq = t.unsqueeze\nsq = t.squeeze\n\n# Settings\nalpha_vec = [.75, .76, .77, .78, .79, .80, .81, .82, .83, .84, .85, .86, .87, .88, .89, .90, .91, .92, .93, .94, .95]\nno_layers = 1\nno_epochs = 10000\ndataset = \"amlsim\"\nmat_f_name = \"saved_content_amlsim.mat\"\nno_trials = 1\n\ndata_loc = \"data/amlsim/1Kvertices-100Kedges/\"\nS_train, S_val, S_test = 150, 25, 25\nlr = 0.01\nmomentum = 0.9\n\n# Load stuff from mat file\nsaved_content = sio.loadmat(data_loc + mat_f_name)\nT = np.max(saved_content[\"A_labels_subs\"][:,0])\nN1 = np.max(saved_content[\"A_labels_subs\"][:,1])\nN2 = np.max(saved_content[\"A_labels_subs\"][:,2])\nN = max(N1, N2)\nA_sz = t.Size([T, N, N])\nC_sz = t.Size([S_train, N, N])\nA_labels = t.sparse.FloatTensor(t.tensor(np.array(saved_content[\"A_labels_subs\"].transpose(1,0), dtype=int) - 1, dtype=t.long), sq(t.tensor(saved_content[\"A_labels_vals\"])), A_sz).coalesce()\nC = t.sparse.FloatTensor(t.tensor(np.array(saved_content[\"C_subs\"].transpose(1,0), dtype=int), dtype=t.long) - 1, sq(t.tensor(saved_content[\"C_vals\"])), t.Size([T,N,N])).coalesce()\n\nA = t.sparse.FloatTensor(A_labels._indices(), t.ones(A_labels._values().shape), A_sz).coalesce()\n\n# Turn C_train, C_val and C_test into lists of sparse matrices so that we can use them in matrix multiplication...\nC_train = []\nfor j in range(S_train):\n\tidx = C._indices()[0] == j\n\tC_train.append(t.sparse.FloatTensor(C._indices()[1:3,idx], C._values()[idx]))\t\nC_val = []\nfor j in range(S_train, S_train+S_val):\n\tidx = C._indices()[0] == j\n\tC_val.append(t.sparse.FloatTensor(C._indices()[1:3,idx], C._values()[idx]))\nC_test = []\nfor j in range(S_train+S_val, S_train+S_val+S_test):\n\tidx = C._indices()[0] == j\n\tC_test.append(t.sparse.FloatTensor(C._indices()[1:3,idx], C._values()[idx]))\n\n# Create features for the nodes\nX = t.zeros(A.shape[0], A.shape[1], 2)\nX[:, :, 0] = t.sparse.sum(A, 1).to_dense()\nX[:, :, 1] = t.sparse.sum(A, 2).to_dense()\nX_train = X[0:S_train].double()\nX_val = X[S_train:S_train+S_val].double()\nX_test = X[S_train+S_val:].double()\n\n# Divide adjacency matrices and labels into training, validation and testing sets\n# \tTraining\nsubs_train = A_labels._indices()[0]<S_train\nedges_train = A_labels._indices()[:, subs_train]\nlabels_train = t.sign(A_labels._values()[subs_train])\ntarget_train = (labels_train!=-1).long() # element = 0 if class is -1; and 1 if class is 0 or +1\n\n#\tValidation\nsubs_val = (A_labels._indices()[0]>=S_train) & (A_labels._indices()[0]<S_train+S_val)\nedges_val = A_labels._indices()[:, subs_val]\nedges_val[0] -= S_train\nlabels_val = t.sign(A_labels._values()[subs_val])\ntarget_val = (labels_val!=-1).long()\n\n#\tTesting\nsubs_test = (A_labels._indices()[0]>=S_train+S_val) \nedges_test = A_labels._indices()[:, subs_test]\nedges_test[0] -= (S_train+S_val)\nlabels_test = t.sign(A_labels._values()[subs_test])\ntarget_test = (labels_test!=-1).long()\n\nif no_trials > 1:\n\tep_acc_loss_vec = []\n\nfor tr in range(no_trials):\n\tfor alpha in alpha_vec:\n\t\tclass_weights = t.tensor([alpha, 1.0-alpha])\n\t\tsave_res_fname = \"results_BASELINE_layers\" + str(no_layers) + \"_w\" + str(round(float(class_weights[0])*100)) + \"_\" + dataset\n\n\t\t# Create gcn for training\n\t\tif no_layers == 2:\n\t\t\tgcn = ehf.EmbeddingKWGCN(C_train, X_train, edges_train, [6,6,2], nonlin2=\"selu\")\n\t\telif no_layers == 1:\n\t\t\tgcn = ehf.EmbeddingKWGCN(C_train, X_train, edges_train, [6,2])\n\n\t\t# Train\n\t\toptimizer = t.optim.SGD(gcn.parameters(), lr=lr, momentum=momentum)\n\t\tcriterion = nn.CrossEntropyLoss(weight=class_weights) # Takes arguments (output, target)\n\t\tep_acc_loss = np.zeros((no_epochs,12)) # (precision_train, recall_train, f1_train, loss_train, precision_val, recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test)\n\t\tfor ep in range(no_epochs):\n\t\t\t# Compute loss and take step\n\t\t\toptimizer.zero_grad()\n\t\t\toutput_train = gcn()\n\t\t\tloss_train = criterion(output_train, target_train)\n\t\t\tloss_train.backward()\n\t\t\toptimizer.step()\n\n\t\t\t# Things that don't require gradient\n\t\t\twith t.no_grad():\n\t\t\t\tguess_train = t.argmax(output_train, dim=1)\n\t\t\t\ttp = t.sum((guess_train==0)&(target_train==0), dtype=t.float64) # true positive\n\t\t\t\tfp = t.sum((guess_train==0)&(target_train!=0), dtype=t.float64) # false positive\n\t\t\t\tfn = t.sum((guess_train!=0)&(target_train==0), dtype=t.float64) # false negative\n\t\t\t\tprecision_train = tp/(tp+fp)\n\t\t\t\trecall_train = tp/(tp+fn)\n\t\t\t\tf1_train = 2*(precision_train*recall_train)/(precision_train + recall_train)\n\t\t\t\tif ep % 100 == 0:\n\t\t\t\t\t# Compute stats for validation data\n\t\t\t\t\toutput_val = gcn(C_val, X_val, edges_val)\n\t\t\t\t\tguess_val = t.argmax(output_val, dim=1)\n\t\t\t\t\ttp = t.sum((guess_val==0)&(target_val==0), dtype=t.float64) # true positive\n\t\t\t\t\tfp = t.sum((guess_val==0)&(target_val!=0), dtype=t.float64) # false positive\n\t\t\t\t\tfn = t.sum((guess_val!=0)&(target_val==0), dtype=t.float64) # false negative\n\t\t\t\t\tprecision_val = tp/(tp+fp)\n\t\t\t\t\trecall_val = tp/(tp+fn)\n\t\t\t\t\tf1_val = 2*(precision_val*recall_val)/(precision_val + recall_val)\n\t\t\t\t\tloss_val = criterion(output_val, target_val)\n\t\t\t\t\t\n\t\t\t\t\t# Compute stats for test data\n\t\t\t\t\toutput_test = gcn(C_test, X_test, edges_test)\n\t\t\t\t\tguess_test = t.argmax(output_test, dim=1)\n\t\t\t\t\ttp = t.sum((guess_test==0)&(target_test==0), dtype=t.float64) # true positive\n\t\t\t\t\tfp = t.sum((guess_test==0)&(target_test!=0), dtype=t.float64) # false positive\n\t\t\t\t\tfn = t.sum((guess_test!=0)&(target_test==0), dtype=t.float64) # false negative\n\t\t\t\t\tprecision_test = tp/(tp+fp)\n\t\t\t\t\trecall_test = tp/(tp+fn)\n\t\t\t\t\tf1_test = 2*(precision_test*recall_test)/(precision_test + recall_test)\n\t\t\t\t\tloss_test = criterion(output_test, target_test)\n\n\t\t\t\t\t# Print\n\t\t\t\t\tprint(\"Tr/Ep %d/%d. Train precision/recall/f1 %.16f/%.16f/%.16f. Train loss %.16f.\" % (tr, ep, precision_train, recall_train, f1_train, loss_train))\n\t\t\t\t\tprint(\"Tr/Ep %d/%d. Val precision/recall/f1 %.16f/%.16f/%.16f. Val loss %.16f.\" % (tr, ep, precision_val, recall_val, f1_val, loss_val))\n\t\t\t\t\tprint(\"Tr/Ep %d/%d. Test precision/recall/f1 %.16f/%.16f/%.16f. Test loss %.16f.\\n\" % (tr, ep, precision_test, recall_test, f1_test, loss_test))\n\t\t\t\tep_acc_loss[ep] = [precision_train, recall_train, f1_train, loss_train, precision_val, recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test]\n\n\t\tprint(\"FINAL: Train precision/recall/f1 %.16f/%.16f/%.16f. Train loss %.16f.\" % (precision_train, recall_train, f1_train, loss_train))\n\t\tprint(\"FINAL: Val precision/recall/f1 %.16f/%.16f/%.16f. Val loss %.16f.\" % (precision_val, recall_val, f1_val, loss_val))\n\t\tprint(\"FINAL: Test precision/recall/f1 %.16f/%.16f/%.16f. Test loss %.16f.\\n\" % (precision_test, recall_test, f1_test, loss_test))\n\n\t\tif no_trials == 1:\n\t\t\tpickle.dump(ep_acc_loss, open(save_res_fname, \"wb\"))\n\t\t\tprint(\"Results saved for single trial\")\n\t\telse:\n\t\t\tep_acc_loss_vec.append(ep_acc_loss)\n\nif no_trials > 1:\n\tpickle.dump(ep_acc_loss_vec, open(save_res_fname + \"_no_trials\" + str(no_trials), \"wb\"))\n\tprint(\"Results saved for all trials\")",
"# This file contains help functions for TensorGCN\n\n# Imports and aliases\nimport pickle\nimport torch as t\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.datasets as datasets\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cProfile\nimport pandas as pd\nimport datetime\nimport random\nfrom scipy.sparse import csr_matrix\nfrom scipy.sparse import coo_matrix\nimport math\nimport os.path\nimport scipy.io as sio\nfrom sklearn.metrics import average_precision_score\nunsq = t.unsqueeze\nsq = t.squeeze\n\n\n# Function for computing At\n# Presently, I don't think this function is used. Can probably be removed in the future.\ndef compute_At(fname_At_mat, fname_ij_matT, A, M, normalization_type=0):\n\tT = A.shape[0]\n\tN = A.shape[1]\n\tsz = t.Size([T, N, N])\n\t# START OF IF {\n\tif (not os.path.isfile(fname_At_mat)) and (not os.path.isfile(fname_ij_matT)):\n\t\tprint(\"Files <<\" + fname_At_mat + \">> and <<\" + fname_ij_matT + \">> do not exist. Creating them... (this will take time)\")\n\n\t\tif normalization_type == 0:\n\t\t\t# Normalize adjacency matrices, i.e., add identity to each frontal\n\t\t\t# slice and then divide each column fiber by its 1-norm.\n\t\t\tself_loop_idx = t.zeros(3, T*N).long()\n\t\t\tself_loop_idx[0] = t.tensor(np.repeat(np.arange(0,T), N)).long()\n\t\t\tself_loop_idx[1] = t.tensor(np.tile(np.arange(0,N), T)).long()\n\t\t\tself_loop_idx[2] = self_loop_idx[1]\n\t\t\tself_loop_vals = t.ones(T*N)\n\t\t\tA = A + t.sparse.FloatTensor(self_loop_idx, self_loop_vals, sz)\n\t\t\tA = A.coalesce()\n\t\t\tA_col_sum = t.sparse.sum(A, dim=1)\n\t\t\tAT = A.transpose(1,2).coalesce() # flip row and col, so that row index is last\n\t\t\tnorm_idx = 0\n\t\t\tk_old = AT._indices()[0][0]\n\t\t\tj_old = AT._indices()[1][0]\n\t\t\tfor nnz_idx in range(AT._nnz()):\n\t\t\t\tk = AT._indices()[0][nnz_idx]\n\t\t\t\tj = AT._indices()[1][nnz_idx]\n\t\t\t\tif not (k == k_old and j == j_old):\n\t\t\t\t\tnorm_idx += 1\n\t\t\t\t\tk_old = k\n\t\t\t\t\tj_old = j\n\t\t\t\tAT._values()[nnz_idx] /= A_col_sum._values()[norm_idx]\n\t\t\tA = AT.transpose(1,2) # Now A has all column sums equal to 1\n\n\t\telif normalization_type == 1:\n\t\t\t# Normalize adjacency matrices\n\t\t\tA = A + A.transpose(1,2)\n\t\t\tA = A/2\n\t\t\tself_loop_idx = t.zeros(3, T*N).long()\n\t\t\tself_loop_idx[0] = t.tensor(np.repeat(np.arange(0,T), N)).long()\n\t\t\tself_loop_idx[1] = t.tensor(np.tile(np.arange(0,N), T)).long()\n\t\t\tself_loop_idx[2] = self_loop_idx[1]\n\t\t\tself_loop_vals = t.ones(T*N)\n\t\t\tA = A + t.sparse.FloatTensor(self_loop_idx, self_loop_vals, sz)\n\t\t\tA = A.coalesce()\n\t\t\tA_row_sum = t.sparse.sum(A, dim=2)\n\n\t\t\t# Multiply with D^{-1/2} from the right\n\t\t\tAT = A.transpose(1,2).coalesce()\n\t\t\tnorm_idx = 0\n\t\t\tk_old = AT._indices()[0][0]\n\t\t\tj_old = AT._indices()[1][0]\n\t\t\tfor nnz_idx in range(AT._nnz()):\n\t\t\t\tk = AT._indices()[0][nnz_idx]\n\t\t\t\tj = AT._indices()[1][nnz_idx]\n\t\t\t\tif not (k == k_old and j == j_old):\n\t\t\t\t\tnorm_idx += 1\n\t\t\t\t\tk_old = k\n\t\t\t\t\tj_old = j\n\t\t\t\tAT._values()[nnz_idx] /= math.sqrt(A_row_sum._values()[norm_idx])\n\t\t\tA = AT.transpose(1,2).coalesce() # Now A has all column sums equal to 1\n\n\t\t\t# Multiply with D^{-1/2} from the left\n\t\t\tnorm_idx = 0\n\t\t\tk_old = A._indices()[0][0]\n\t\t\ti_old = A._indices()[1][0]\n\t\t\tfor nnz_idx in range(A._nnz()):\n\t\t\t\tk = A._indices()[0][nnz_idx]\n\t\t\t\ti = A._indices()[1][nnz_idx]\n\t\t\t\tif not (k == k_old and i == i_old):\n\t\t\t\t\tnorm_idx += 1\n\t\t\t\t\tk_old = k\n\t\t\t\t\ti_old = i\n\t\t\t\tA._values()[nnz_idx] /= math.sqrt(A_row_sum._values()[norm_idx])\t\t\t\n\t\t\n\t\t# Compute the tubes of the M-transform of A\n\t\tnnzcol = t.sparse.sum(A, dim=0)._nnz()\n\t\tAt_matT = t.zeros(nnzcol, T)\n\t\tij_mat = t.zeros(nnzcol, 2).long()\n\t\tAT = A.transpose(0,2).coalesce()\n\t\tvalT = AT._values()\n\t\tidxT = AT._indices()\n\t\ti_old = idxT[1][0]\n\t\tj_old = idxT[0][0]\n\t\tvec = t.zeros(T)\n\t\tcnt = 0\n\t\tMT = M.transpose(1,0) # Note: This should be transpose of M, NOT inverse of M\n\t\tfor c in range(idxT.shape[1]):\n\t\t\tj = idxT[0][c]\n\t\t\ti = idxT[1][c]\n\t\t\tk = idxT[2][c]\n\t\t\tif i == i_old and j == j_old:\n\t\t\t\tvec += valT[c]*MT[k]\n\t\t\telse:\n\t\t\t\tAt_matT[cnt] = vec\n\t\t\t\tij_mat[cnt] = t.tensor([i_old, j_old]).long()\n\t\t\t\tcnt += 1\n\t\t\t\tvec = valT[c]*MT[k]\n\t\t\t\ti_old = i\n\t\t\t\tj_old = j\n\t\t\tif c % 10000 == 0:\n\t\t\t\tprint(c)\n\t\tAt_matT[cnt] = vec\n\t\tij_mat[cnt] = t.tensor([i_old, j_old]).long()\n\n\t\t# Compute a list containing the frontal matrices of At\n\t\tij_matT = ij_mat.transpose(1,0)\n\t\tAt_mat = At_matT.transpose(1,0)\n\n\t\tprint(\"Saving to files <<\" + fname_ij_matT + \">> and <<\" + fname_At_mat + \">>.\")\n\t\tpickle.dump(At_mat, open(fname_At_mat, \"wb\"))\n\t\tpickle.dump(ij_matT, open(fname_ij_matT, \"wb\"))\n\n\t# } END OF IF\n\t# START OF ELSE {\n\telse:\n\t\tprint(\"Loading files <<\" + fname_ij_matT + \">> and <<\" + fname_At_mat + \">> from file...\")\n\t\tij_matT = pickle.load(open(fname_ij_matT, \"rb\"))\n\t\tAt_mat = pickle.load(open(fname_At_mat, \"rb\"))\n\t# } END OF ELSE\n\n\tAt = []\n\tfor vl in At_mat:\n\t\tAt.append(t.sparse.FloatTensor(ij_matT, vl))\n\n\treturn At\n# END OF FUNCTION compute_At\n# I have verified this function, and made some fixes, on 20-July-2019 \n\nclass EmbeddingGCN(nn.Module):\n\t\"\"\"\n\tOur proposed TensorGCN with 1 layer\n\t\"\"\"\n\tdef __init__(self, At, X, edges, M, hidden_feat=[2,2], condensed_W=False, use_Minv=True):\n\t\t\"\"\"\n\t\tInitialize EmbeddingGCN layer\n\n\t\tParameters:\n\t\t\tAt\t\t\t\t:\ttorch.Tensor\n\t\t\t\tA tensor containing the M-transformed version of the normalized graph Laplacian. It should be of size T x N x N, where T is the number of time steps, and N is the number of nodes.\n\t\t\tX\t\t\t\t:\ttorch.Tensor\n\t\t\t\tA tensor of size T x N x 2 which contains the node signals. T is time, and N is the number of nodes. The size 2 third dimension comes from the fact that, in this experiment, each node has 2 features.\n\t\t\tedges\t\t\t:\ttorch.Tensor, dtype=t.long\n\t\t\t\tA matrix of size 3 x no_edges which contains information on the edges. Specifically, each column of edges has three entries: time slice, source node and target node.\n\t\t\tM\t\t\t\t: \ttorch.Tensor\n\t\t\t\tA matrix of size T x T, where T is the number of time steps. M is assumed to be invertible.\n\t\t\thidden_feat \t:\tlist of int\n\t\t\t\tThe number of hidden layers to utilize. More specifically, this is the number of features for each node that the GCN outputs. Should be list of 2 integers.\n\t\t\tcondensed_W\t\t:\tbool\n\t\t\t\tSet to True to use condensed weight tensor, i.e., use the same weight matrix for each time point.\n\t\t\tuse_Minv\t\t:\tbool\n\t\t\t\tSet to False to avoid every applying the inverse M transform.\n\t\t\"\"\"\n\t\tsuper(EmbeddingGCN, self).__init__()\n\t\tself.M = M\n\t\tself.use_Minv = use_Minv\n\t\tif use_Minv:\n\t\t\tself.Minv = t.tensor(np.linalg.inv(M))\n\t\tself.T = X.shape[0]\n\t\tself.N = X.shape[1]\n\t\tself.F = [X.shape[-1]] + hidden_feat\n\t\tif condensed_W:\n\t\t\tself.W = nn.Parameter(t.randn(self.F[0], self.F[1]))\n\t\telse:\n\t\t\tself.W = nn.Parameter(t.randn(self.T, self.F[0], self.F[1]))\n\t\tself.U = nn.Parameter(t.randn(2*self.F[1], self.F[2]))\n\t\tself.sigmoid = nn.Sigmoid()\n\t\t\n\t\tself.AtXt = self.compute_AtXt(At, X)\n\t\tself.v = t.tensor([self.N, 1], dtype=t.long)\n\t\tself.edge_src_nodes = t.matmul(edges[[0,1]].transpose(1,0), self.v)\n\t\tself.edge_trg_nodes = t.matmul(edges[[0,2]].transpose(1,0), self.v)\n\n\tdef __call__(self, At=None, X=None, edges=None):\n\t\treturn self.forward(At, X, edges)\n\n\tdef compute_AtXt(self, At, X):\n\t\tXt = t.matmul(self.M, X.reshape(self.T, -1)).reshape(X.size())\n\t\tAtXt = t.zeros(self.T, self.N, self.F[0])\n\t\tfor k in range(self.T):\n\t\t\tAtXt[k] = t.sparse.mm(At[k], Xt[k])\n\t\treturn AtXt\n\n\tdef forward(self, At=None, X=None, edges=None):\n\t\t# Either use existing AtXt and edges, or compute new\n\t\tif type(At)==list and type(X)==t.Tensor and type(edges)==t.Tensor:\n\t\t\tAtXt = self.compute_AtXt(At, X)\n\t\t\tedge_src_nodes = t.matmul(edges[[0,1]].transpose(1,0), self.v)\n\t\t\tedge_trg_nodes = t.matmul(edges[[0,2]].transpose(1,0), self.v)\n\t\telse:\n\t\t\tAtXt = self.AtXt\n\t\t\tedge_src_nodes = self.edge_src_nodes\n\t\t\tedge_trg_nodes = self.edge_trg_nodes\n\t\t\n\t\tWt = self.W # Do not transform W\n\t\tAtXtWt = t.matmul(AtXt, Wt)\n\t\tif self.use_Minv:\n\t\t\tY = t.matmul(self.Minv, AtXtWt.reshape(self.T, -1)).reshape(AtXtWt.size()) \n\t\telse:\n\t\t\tY = AtXtWt\n\n\t\tAXW_mat_edge_src_nodes = Y.reshape(-1, self.F[1])[edge_src_nodes]\n\t\tAXW_mat_edge_trg_nodes = Y.reshape(-1, self.F[1])[edge_trg_nodes]\n\t\tAXW_mat = t.cat((AXW_mat_edge_src_nodes, AXW_mat_edge_trg_nodes), dim=1)\n\n\t\toutput = t.matmul(AXW_mat, self.U)\n\n\t\treturn output\n\nclass EmbeddingGCN2(nn.Module):\n\t\"\"\"\n\tOur proposed TensorGCN with 2 layers\n\t\"\"\"\n\tdef __init__(self, At, X, edges, M, hidden_feat=[2,2,2], condensed_W=False, use_Minv=True, apply_M_twice=False, apply_M_three_times=False, nonlin2=\"relu\"):\n\t\t\"\"\"\n\t\tInitialize EmbeddingGCN2 layer\n\n\t\tParameters:\n\t\t\tAt\t\t\t\t:\ttorch.Tensor\n\t\t\t\tA tensor containing the M-transformed version of the normalized graph Laplacian. It should be of size T x N x N, where T is the number of time steps, and N is the number of nodes.\n\t\t\tX\t\t\t\t:\ttorch.Tensor\n\t\t\t\tA tensor of size T x N x 2 which contains the node signals. T is time, and N is the number of nodes. The size 2 third dimension comes from the fact that, in this experiment, each node has 2 features.\n\t\t\tedges\t\t\t:\ttorch.Tensor, dtype=t.long\n\t\t\t\tA matrix of size 3 x no_edges which contains information on the edges. Specifically, each column of edges has three entries: time slice, source node and target node.\n\t\t\tM\t\t\t\t: \ttorch.Tensor\n\t\t\t\tA matrix of size T x T, where T is the number of time steps. M is assumed to be invertible.\n\t\t\thidden_feat \t:\tlist of int\n\t\t\t\tThe number of hidden layers to utilize. More specifically, this is the number of features for each node that the GCN outputs. Should be list of 3 integers.\n\t\t\tcondensed_W\t\t:\tbool\n\t\t\t\tSet to True to use condensed weight tensor, i.e., use the same weight matrix for each time point.\n\t\t\tuse_Minv\t\t:\tbool\n\t\t\t\tSet to False to avoid every applying the inverse M transform.\n\t\t\tapply_M_twice \t: \tbool\n\t\t\t\tWhen use_Minv is set to false, this is used to still force the program to apply the M matrix a second time before going into the second layer. The idea here is that this may help improve the performance, since it corresponds to doing a time mixing twice.\n\t\t\tself.apply_M_three_times\t:\tbool\n\t\t\t\tIf we want to apply M a final time in the 2-layer architechture before putting the signal into the classifier\n\t\t\tnonlin2\t\t\t: \tstr\n\t\t\t\tSet to either \"relu\", \"leaky\" or \"selu\" use a ReLU, leaky ReLU, and SELU as the nonlinearity in between layers.\n\t\t\"\"\"\n\t\tsuper(EmbeddingGCN2, self).__init__()\n\t\tself.At = At\n\t\tself.M = M\n\t\tself.use_Minv = use_Minv\n\t\tself.apply_M_twice = apply_M_twice\n\t\tself.apply_M_three_times = apply_M_three_times\n\t\tif use_Minv:\n\t\t\tself.Minv = t.tensor(np.linalg.inv(M))\n\t\tself.T = X.shape[0]\n\t\tself.N = X.shape[1]\n\t\tself.F = [X.shape[-1]] + hidden_feat\n\t\tif condensed_W:\n\t\t\tself.W1 = nn.Parameter(t.randn(self.F[0], self.F[1]))\n\t\t\tself.W2 = nn.Parameter(t.randn(self.F[1], self.F[2]))\n\t\telse:\n\t\t\tself.W1 = nn.Parameter(t.randn(self.T, self.F[0], self.F[1]))\n\t\t\tself.W2 = nn.Parameter(t.randn(self.T, self.F[1], self.F[2]))\n\t\tself.U = nn.Parameter(t.randn(self.F[2]*2,self.F[3]))\n\t\tif nonlin2 == \"relu\":\n\t\t\tself.nonlin_func = nn.ReLU(inplace=False)\n\t\telif nonlin2 == \"leaky\":\n\t\t\tself.nonlin_func = nn.LeakyReLU(negative_slope=0.01, inplace=False)\n\t\telif nonlin2 == \"selu\":\n\t\t\tself.nonlin_func = nn.SELU(inplace=False)\n\n\t\tself.sigmoid = nn.Sigmoid()\n\t\t\n\t\tself.AtXt = self.compute_AtXt(At, X)\n\t\tself.v = t.tensor([self.N, 1], dtype=t.long)\n\t\tself.edge_src_nodes = t.matmul(edges[[0,1]].transpose(1,0), self.v)\n\t\tself.edge_trg_nodes = t.matmul(edges[[0,2]].transpose(1,0), self.v)\n\n\tdef __call__(self, At=None, X=None, edges=None):\n\t\treturn self.forward(At, X, edges)\n\n\tdef compute_AX(self, A, X):\n\t\tAX = t.zeros(self.T, self.N, X.shape[-1])\n\t\tfor k in range(self.T):\n\t\t\tAX[k] = t.sparse.mm(A[k], X[k])\n\t\treturn AX\n\n\tdef compute_AtXt(self, At, X):\n\t\tXt = t.matmul(self.M, X.reshape(self.T, -1)).reshape(X.size())\n\t\tAtXt = t.zeros(self.T, self.N, X.shape[-1])\n\t\tfor k in range(self.T):\n\t\t\tAtXt[k] = t.sparse.mm(At[k], Xt[k])\n\t\treturn AtXt\n\n\tdef forward(self, At=None, X=None, edges=None):\n\t\t# Either use existing AtXt and edges, or compute new\n\t\tif type(At)==list and type(X)==t.Tensor and type(edges)==t.Tensor:\n\t\t\tAtXt = self.compute_AtXt(At, X)\n\t\t\tedge_src_nodes = t.matmul(edges[[0,1]].transpose(1,0), self.v)\n\t\t\tedge_trg_nodes = t.matmul(edges[[0,2]].transpose(1,0), self.v)\n\t\telse:\n\t\t\tAtXt = self.AtXt\n\t\t\tedge_src_nodes = self.edge_src_nodes\n\t\t\tedge_trg_nodes = self.edge_trg_nodes\n\n\t\t# Do not transform weight tensors/matrices\n\t\tW1t = self.W1\n\t\tW2t = self.W2\n\n\t\t# First layer\n\t\tAtXtW1t = t.matmul(AtXt, W1t)\n\t\tif self.use_Minv:\n\t\t\tY = self.nonlin_func(t.matmul(self.Minv, AtXtW1t.reshape(self.T, -1)).reshape(AtXtW1t.size())) \n\t\telse:\n\t\t\tY = self.nonlin_func(AtXtW1t)\n\t\tY = Y.double()\n\n\t\t# Second layer\n\t\tif self.use_Minv:\n\t\t\tAtYt = self.compute_AtXt(self.At, Y)\n\t\t\tAtYtW2t = t.matmul(AtYt, W2t)\n\t\t\tZ = t.matmul(self.Minv, AtYtW2t.reshape(self.T, -1)).reshape(AtYtW2t.size())\n\t\telif self.apply_M_twice:\n\t\t\tAtYt = self.compute_AtXt(self.At, Y)\n\t\t\tZ = t.matmul(AtYt, W2t)\n\t\t\tif self.apply_M_three_times:\n\t\t\t\tZ = t.matmul(self.M, Z.reshape(self.T, -1).double()).reshape(Z.size())\n\t\telse:\n\t\t\tAY = self.compute_AX(self.At, Y)\n\t\t\tZ = t.matmul(AY, W2t)\n\n\t\tZ_mat_edge_src_nodes = Z.reshape(-1, self.F[2])[edge_src_nodes]\n\t\tZ_mat_edge_trg_nodes = Z.reshape(-1, self.F[2])[edge_trg_nodes]\n\t\tZ_mat = t.cat((Z_mat_edge_src_nodes, Z_mat_edge_trg_nodes), dim=1)\n\n\t\toutput = t.matmul(Z_mat.float(), self.U)\n\n\t\treturn output\n\nclass EmbeddingGCN_reg(nn.Module):\n\t\"\"\"\n\tOur proposed TensorGCN with 1 layer\n\t\"\"\"\n\tdef __init__(self, At, X, M, hidden_feat=[2,2], condensed_W=False, use_Minv=True):\n\t\t\"\"\"\n\t\tInitialize EmbeddingGCN layer\n\n\t\tParameters:\n\t\t\tAt\t\t\t\t:\ttorch.Tensor\n\t\t\t\tA tensor containing the M-transformed version of the normalized graph Laplacian. It should be of size T x N x N, where T is the number of time steps, and N is the number of nodes.\n\t\t\tX\t\t\t\t:\ttorch.Tensor\n\t\t\t\tA tensor of size T x N x 2 which contains the node signals. T is time, and N is the number of nodes. The size 2 third dimension comes from the fact that, in this experiment, each node has 2 features.\n\t\t\tedges\t\t\t:\ttorch.Tensor, dtype=t.long\n\t\t\t\tA matrix of size 3 x no_edges which contains information on the edges. Specifically, each column of edges has three entries: time slice, source node and target node.\n\t\t\tM\t\t\t\t: \ttorch.Tensor\n\t\t\t\tA matrix of size T x T, where T is the number of time steps. M is assumed to be invertible.\n\t\t\thidden_feat \t:\tlist of int\n\t\t\t\tThe number of hidden layers to utilize. More specifically, this is the number of features for each node that the GCN outputs. Should be list of 2 integers.\n\t\t\tcondensed_W\t\t:\tbool\n\t\t\t\tSet to True to use condensed weight tensor, i.e., use the same weight matrix for each time point.\n\t\t\tuse_Minv\t\t:\tbool\n\t\t\t\tSet to False to avoid every applying the inverse M transform.\n\t\t\"\"\"\n\t\tsuper(EmbeddingGCN_reg, self).__init__()\n\t\tself.M = M\n\t\tself.use_Minv = use_Minv\n\t\tif use_Minv:\n\t\t\tself.Minv = t.tensor(np.linalg.inv(M))\n\t\tself.T = X.shape[0]\n\t\tself.N = X.shape[1]\n\t\tself.F = [X.shape[-1]] + hidden_feat\n\t\tif condensed_W:\n\t\t\tself.W = nn.Parameter(t.randn(self.F[0], self.F[1]))\n\t\telse:\n\t\t\tself.W = nn.Parameter(t.randn(self.T, self.F[0], self.F[1]))\n\t\tself.lin1 = nn.Linear(self.F[1], 1)\n\t\tself.sigmoid = nn.Sigmoid()\n\t\t\n\t\tself.AtXt = self.compute_AtXt(At, X)\n\n\tdef __call__(self, At=None, X=None):\n\t\treturn self.forward(At, X)\n\n\tdef compute_AtXt(self, At, X):\n\t\tXt = t.matmul(self.M, X.reshape(self.T, -1)).reshape(X.size())\n\t\tAtXt = t.zeros(self.T, self.N, self.F[0])\n\t\tfor k in range(self.T):\n\t\t\tAtXt[k] = t.sparse.mm(At[k], Xt[k])\n\t\treturn AtXt\n\n\tdef forward(self, At=None, X=None):\n\t\t# Either use existing AtXt and edges, or compute new\n\t\tAtXt = self.AtXt\n\t\t\n\t\tWt = self.W # Do not transform W\n\t\tAtXtWt = t.matmul(AtXt, Wt)\n\t\tif self.use_Minv:\n\t\t\tY = t.matmul(self.Minv, AtXtWt.reshape(self.T, -1)).reshape(AtXtWt.size()) \n\t\telse:\n\t\t\tY = AtXtWt\n\n\t\toutput = self.lin1(Y)\n\n\t\treturn output.squeeze(2)\n\nclass EmbeddingKWGCN(nn.Module):\n\t\"\"\"\n\tEmbedding implementation of the baseline GCN with 1 or 2 layers\n\t\"\"\"\n\tdef __init__(self, A, X, edges, hidden_feat=[2,2], nonlin2=\"relu\"):\n\t\t\"\"\"\n\t\tInitialize EmbeddingKWGCN layer\n\n\t\tParameters:\n\t\t\tA\t\t\t\t:\ttorch.Tensor\n\t\t\t\tA tensor containing the the normalized graph Laplacian. It should be of size T x N x N, where T is the number of time steps, and N is the number of nodes.\n\t\t\tX\t\t\t\t:\ttorch.Tensor\n\t\t\t\tA tensor of size T x N x F which contains the node signals. T is time, N is the number of nodes, and F is the number of features.\n\t\t\tedges\t\t\t:\ttorch.Tensor, dtype=t.long\n\t\t\t\tA matrix of size 3 x no_edges which contains information on the edges. Specifically, each column of edges has three entries: time slice, source node and target node.\n\t\t\thidden_feat \t:\tlist of int\n\t\t\t\tThe number of hidden layers to utilize. More specifically, this is the number of features for each node that the GCN outputs. Should be list of 2 or 3 integers.\n\t\t\tnonlin2\t\t\t: \tstr\n\t\t\t\tSet to either \"relu\", \"leaky\" or \"selu\" use a ReLU, leaky ReLU, and SELU as the nonlinearity in between layers.\n\t\t\"\"\"\n\t\tsuper(EmbeddingKWGCN, self).__init__()\n\t\tself.no_layers = len(hidden_feat)-1\n\t\tself.T = len(A)\n\t\tself.N = X.shape[1]\n\t\tself.A = A\n\t\tself.F = [X.shape[-1]] + hidden_feat\n\t\tif self.no_layers == 2:\n\t\t\tself.W2 = nn.Parameter(t.randn(self.F[1], self.F[2]))\n\t\tself.W1 = nn.Parameter(t.randn(self.F[0], self.F[1]))\n\t\tself.U = nn.Parameter(t.randn(self.F[-2]*2, self.F[-1]))\n\t\tif nonlin2 == \"relu\":\n\t\t\tself.nonlin_func = nn.ReLU(inplace=False)\n\t\telif nonlin2 == \"leaky\":\n\t\t\tself.nonlin_func = nn.LeakyReLU(negative_slope=0.01, inplace=False)\n\t\telif nonlin2 == \"selu\":\n\t\t\tself.nonlin_func = nn.SELU(inplace=False)\n\t\tself.v = t.tensor([self.N, 1], dtype=t.long)\n\t\tself.edge_src_nodes = t.matmul(edges[[0,1]].transpose(1,0), self.v)\n\t\tself.edge_trg_nodes = t.matmul(edges[[0,2]].transpose(1,0), self.v)\n\t\tself.AX = self.compute_AX(A, X)\n\n\tdef __call__(self, A=None, X=None, edges=None):\n\t\treturn self.forward(A, X, edges)\n\n\tdef compute_AX(self, A, X):\n\t\tAX = t.zeros(self.T, self.N, X.shape[-1])\n\t\tfor k in range(len(A)):\n\t\t\tAX[k] = t.sparse.mm(A[k], X[k])\n\t\treturn AX\n\n\tdef forward(self, A=None, X=None, edges=None):\n\t\tif type(A)==list and type(X)==t.Tensor and type(edges)==t.Tensor:\n\t\t\tAX = self.compute_AX(A, X)\n\t\t\tedge_src_nodes = t.matmul(edges[[0,1]].transpose(1,0), self.v)\n\t\t\tedge_trg_nodes = t.matmul(edges[[0,2]].transpose(1,0), self.v)\n\t\telse:\n\t\t\tAX = self.AX\n\t\t\tedge_src_nodes = self.edge_src_nodes\n\t\t\tedge_trg_nodes = self.edge_trg_nodes\n\n\t\tif self.no_layers == 2:\n\t\t\tY = self.nonlin_func(t.matmul(AX, self.W1)).double()\n\t\t\tZ = t.matmul(self.compute_AX(self.A, Y), self.W2)\n\t\telse:\n\t\t\tZ = t.matmul(AX, self.W1)\n\n\t\tZ_mat_edge_src_nodes = Z.reshape(-1, Z.shape[-1])[edge_src_nodes]\n\t\tZ_mat_edge_trg_nodes = Z.reshape(-1, Z.shape[-1])[edge_trg_nodes]\n\t\tZ_mat = t.cat((Z_mat_edge_src_nodes, Z_mat_edge_trg_nodes), dim=1)\n\n\t\toutput = t.matmul(Z_mat, self.U)\n\n\t\treturn output\n\n# This function is used to construct augmented edge dataset for link prediction\ndef augment_edges(edges, N, beta1, beta2, cutoff):\n\tedges_t = edges.transpose(1,0)\n\tedges_new = []\n\tfor j in range(t.max(edges[0])+1):\n\t\tif j < cutoff:\n\t\t\tbeta = beta1\n\t\telse:\n\t\t\tbeta = beta2\n\t\tto_add = beta*t.sum(edges[0]==j)\n\t\tn_added = 0\n\t\tedges_subset = edges[1:3, edges[0]==j]\n\t\twhile n_added < to_add:\n\t\t\te = [random.randint(0,N-1), random.randint(0,N-1)]\n\t\t\tif t.max(t.sum(edges_subset.transpose(1,0) == t.tensor(e), 1)) < 2:\n\t\t\t\tedges_new.append([j, e[0], e[1]])\n\t\t\t\tn_added += 1\n\t\tprint(j)\n\n\tedges_aug = t.cat((edges, t.tensor(edges_new).transpose(1,0)), 1)\n\t_, sort_id = edges_aug[0].sort()\n\tedges_aug = edges_aug[:, sort_id]\n\tedges_aug_t = edges_aug.transpose(1,0)\n\n\tlabels = t.cat((t.zeros(edges.shape[1], dtype=t.long), t.ones(edges_aug.shape[1]-edges.shape[1], dtype=t.long)), 0)\n\tlabels = labels[sort_id]\n\n\treturn edges_aug, labels\n\n# This function computes precision, recall and F1\n# Makes experiment code more compact by putting this in a separate function rather than repeating in every experiment script. Note 0 is assumed to be minority class, ie positive class we're trying to identify.\ndef compute_f1(guess, target):\n\ttp \t\t\t= t.sum((guess==0)&(target==0), dtype=t.float64) # true positive\n\tfp \t\t\t= t.sum((guess==0)&(target!=0), dtype=t.float64) # false positive\n\tfn \t\t\t= t.sum((guess!=0)&(target==0), dtype=t.float64) # false negative\n\tprecision \t= tp/(tp+fp)\n\trecall \t\t= tp/(tp+fn)\n\tf1 \t\t\t= 2*(precision*recall)/(precision + recall)\n\n\treturn precision, recall, f1\n\n# This function loads the preprocessed data from a mat file, and returns the\n# various quantities that will be used later.\ndef load_data(data_loc, mat_f_name, S_train, S_val, S_test, transformed):\n\t# Load stuff from mat file\n\tsaved_content = sio.loadmat(data_loc + mat_f_name)\n\tT = np.max(saved_content[\"A_labels_subs\"][:,0])\n\tN1 = np.max(saved_content[\"A_labels_subs\"][:,1])\n\tN2 = np.max(saved_content[\"A_labels_subs\"][:,2])\n\tN = max(N1, N2)\n\tA_sz = t.Size([T, N, N])\n\tC_sz = t.Size([S_train, N, N])\n\tA_labels = t.sparse.FloatTensor(t.tensor(np.array(saved_content[\"A_labels_subs\"].transpose(1,0), dtype=int) - 1, dtype=t.long), sq(t.tensor(saved_content[\"A_labels_vals\"])), A_sz).coalesce()\n\tA = t.sparse.FloatTensor(A_labels._indices(), t.ones(A_labels._values().shape), A_sz).coalesce()\n\n\tif transformed:\n\t\tCt_train = t.sparse.FloatTensor(t.tensor(np.array(saved_content[\"Ct_train_subs\"].transpose(1,0), dtype=int), dtype=t.long) - 1, sq(t.tensor(saved_content[\"Ct_train_vals\"])), C_sz).coalesce()\n\t\tCt_val = t.sparse.FloatTensor(t.tensor(np.array(saved_content[\"Ct_val_subs\"].transpose(1,0), dtype=int), dtype=t.long) - 1, sq(t.tensor(saved_content[\"Ct_val_vals\"])), C_sz).coalesce()\n\t\tCt_test = t.sparse.FloatTensor(t.tensor(np.array(saved_content[\"Ct_test_subs\"].transpose(1,0), dtype=int), dtype=t.long) - 1, sq(t.tensor(saved_content[\"Ct_test_vals\"])), C_sz).coalesce()\n\t\tM = t.tensor(saved_content[\"M\"], dtype=t.float64)\n\n\t\t# Turn each Ct_train, Ct_val and Ct_test into a list of sparse matrices so that we can use them in matrix multiplication...\n\t\tCt_train_2 = []\n\t\tfor j in range(S_train):\n\t\t\tidx = Ct_train._indices()[0] == j\n\t\t\tCt_train_2.append(t.sparse.FloatTensor(Ct_train._indices()[1:3,idx], Ct_train._values()[idx]))\t\n\t\tCt_val_2 = []\n\t\tfor j in range(S_train):\n\t\t\tidx = Ct_val._indices()[0] == j\n\t\t\tCt_val_2.append(t.sparse.FloatTensor(Ct_val._indices()[1:3,idx], Ct_val._values()[idx]))\n\t\tCt_test_2 = []\n\t\tfor j in range(S_train):\n\t\t\tidx = Ct_test._indices()[0] == j\n\t\t\tCt_test_2.append(t.sparse.FloatTensor(Ct_test._indices()[1:3,idx], Ct_test._values()[idx]))\n\n\t\treturn A, A_labels, Ct_train_2, Ct_val_2, Ct_test_2, N, M\n\n\telse:\n\t\tC = t.sparse.FloatTensor(t.tensor(np.array(saved_content[\"C_subs\"].transpose(1,0), dtype=int), dtype=t.long) - 1, sq(t.tensor(saved_content[\"C_vals\"])), t.Size([T,N,N])).coalesce()\n\n\t\t# Turn C_train, C_val and C_test into lists of sparse matrices so that we can use them in matrix multiplication...\n\t\tC_train = []\n\t\tfor j in range(S_train):\n\t\t\tidx = C._indices()[0] == j\n\t\t\tC_train.append(t.sparse.FloatTensor(C._indices()[1:3,idx], C._values()[idx]))\t\n\t\tC_val = []\n\t\tfor j in range(S_train, S_train+S_val):\n\t\t\tidx = C._indices()[0] == j\n\t\t\tC_val.append(t.sparse.FloatTensor(C._indices()[1:3,idx], C._values()[idx]))\n\t\tC_test = []\n\t\tfor j in range(S_train+S_val, S_train+S_val+S_test):\n\t\t\tidx = C._indices()[0] == j\n\t\t\tC_test.append(t.sparse.FloatTensor(C._indices()[1:3,idx], C._values()[idx]))\n\n\t\treturn A, A_labels, C_train, C_val, C_test, N\n\n# Create node features for training, validation and test data.\n# Set same_block_size to true for TensorGCN methods, and false for all other methods\ndef create_node_features(A, S_train, S_val, S_test, same_block_size):\n\tX = t.zeros(A.shape[0], A.shape[1], 2)\n\tX[:, :, 0] = t.sparse.sum(A, 1).to_dense()\n\tX[:, :, 1] = t.sparse.sum(A, 2).to_dense()\n\tX_train = X[0:S_train].double()\n\tif same_block_size:\n\t\tX_val = X[S_val:S_train+S_val].double()\n\t\tX_test = X[S_val+S_test:].double()\n\telse:\n\t\tX_val = X[S_train:S_train+S_val].double()\n\t\tX_test = X[S_train+S_val:].double()\n\n\treturn X_train, X_val, X_test\n\n# Divide adjacency matrices and labels into training, validation and testing sets\ndef split_data(edges_aug, labels, S_train, S_val, S_test, same_block_size):\n\t# \tTraining\n\tsubs_train = edges_aug[0]<S_train\n\tedges_train = edges_aug[:, subs_train]\n\ttarget_train = labels[subs_train]\n\te_train = edges_train[:, edges_train[0]!=0]\n\te_train = e_train-t.cat((t.ones(1,e_train.shape[1]), t.zeros(2,e_train.shape[1])),0).long()\n\n\t#\tValidation\n\tif same_block_size:\n\t\tsubs_val = (edges_aug[0]>=S_val) & (edges_aug[0]<S_train+S_val)\n\telse:\n\t\tsubs_val = (edges_aug[0]>=S_train) & (edges_aug[0]<S_train+S_val)\n\tedges_val = edges_aug[:, subs_val]\n\tif same_block_size:\n\t\tedges_val[0] -= S_val\n\telse:\n\t\tedges_val[0] -= S_train\n\ttarget_val = labels[subs_val]\n\tif same_block_size:\n\t\tK_val = t.sum(edges_val[0] - (S_train-S_val-1) > 0)\n\te_val = edges_val[:, edges_val[0]!=0]\n\te_val = e_val-t.cat((t.ones(1,e_val.shape[1]), t.zeros(2,e_val.shape[1])),0).long()\n\n\t#\tTesting\n\tif same_block_size:\n\t\tsubs_test = (edges_aug[0]>=S_test+S_val) \n\telse:\n\t\tsubs_test = (edges_aug[0]>=S_train+S_val)\n\tedges_test = edges_aug[:, subs_test]\n\tif same_block_size:\n\t\tedges_test[0] -= (S_test+S_val)\n\telse:\n\t\tedges_test[0] -= (S_train+S_val)\n\ttarget_test = labels[subs_test]\n\tif same_block_size:\n\t\tK_test = t.sum(edges_test[0] - (S_train-S_test-1) > 0)\n\te_test = edges_test[:, edges_test[0]!=0]\n\te_test = e_test-t.cat((t.ones(1,e_test.shape[1]), t.zeros(2,e_test.shape[1])),0).long()\n\n\tif same_block_size:\n\t\treturn edges_train, target_train, e_train, edges_val, target_val, e_val, K_val, edges_test, target_test, e_test, K_test\n\telse:\n\t\treturn edges_train, target_train, e_train, edges_val, target_val, e_val, edges_test, target_test, e_test\n\n# Used to print results\ndef print_f1(precision_train, recall_train, f1_train, loss_train, precision_val, recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test, alpha=None, tr=None, ep=None, is_final=False):\n\tif is_final:\n\t\tprint(\"FINAL: Train precision/recall/f1 %.16f/%.16f/%.16f. Train loss %.16f.\" % (precision_train, recall_train, f1_train, loss_train))\n\t\tprint(\"FINAL: Val precision/recall/f1 %.16f/%.16f/%.16f. Val loss %.16f.\" % (precision_val, recall_val, f1_val, loss_val))\n\t\tprint(\"FINAL: Test precision/recall/f1 %.16f/%.16f/%.16f. Test loss %.16f.\\n\" % (precision_test, recall_test, f1_test, loss_test))\n\telse:\n\t\tprint(\"alpha/Tr/Ep %.2f/%d/%d. Train precision/recall/f1 %.16f/%.16f/%.16f. Train loss %.16f.\" % (alpha, tr, ep, precision_train, recall_train, f1_train, loss_train))\n\t\tprint(\"alpha/Tr/Ep %.2f/%d/%d. Val precision/recall/f1 %.16f/%.16f/%.16f. Val loss %.16f.\" % (alpha, tr, ep, precision_val, recall_val, f1_val, loss_val))\n\t\tprint(\"alpha/Tr/Ep %.2f/%d/%d. Test precision/recall/f1 %.16f/%.16f/%.16f. Test loss %.16f.\\n\" % (alpha, tr, ep, precision_test, recall_test, f1_test, loss_test))\n\n# get_row_MRR copied from EvolveGCN code\ndef get_row_MRR(probs,true_classes):\n existing_mask = true_classes == 0 # Since 0 is our minority class, i.e., existing edges\n #descending in probability\n ordered_indices = np.flip(probs.argsort())\n\n ordered_existing_mask = existing_mask[ordered_indices]\n\n existing_ranks = np.arange(1,\n true_classes.shape[0]+1,\n dtype=np.float)[ordered_existing_mask]\n\n MRR = (1/existing_ranks).sum()/existing_ranks.shape[0]\n return MRR\n\n# get_MRR copied from EvolveGCN code\ndef get_MRR(predictions,true_classes, adj ,do_softmax=True):\n if do_softmax:\n probs = t.softmax(predictions,dim=1)[:,0] # Send in probabilities for 0 class, i.e., minority class, i.e., existing edges\n else:\n probs = predictions[:,0]\n probs = probs.detach().cpu().numpy()\n true_classes = true_classes.detach().cpu().numpy()\n adj = adj.detach().cpu().numpy()\n pred_matrix = coo_matrix((probs,(adj[0],adj[1]))).toarray()\n true_matrix = coo_matrix((true_classes,(adj[0],adj[1]))).toarray()\n\n row_MRRs = []\n for i,pred_row in enumerate(pred_matrix):\n if np.isin(1,true_matrix[i]):\n row_MRRs.append(get_row_MRR(pred_row,true_matrix[i]))\n\n avg_MRR = t.tensor(row_MRRs).mean()\n return avg_MRR\n\n# get_MAP copied from EvolveGCN code\ndef get_MAP(predictions, true_classes, do_softmax=True):\n if do_softmax:\n probs = t.softmax(predictions,dim=1)[:,0] # Send in probabilities for 0 class, i.e., minority class, i.e., existing edges\n else:\n probs = predictions\n predictions_np = probs.detach().cpu().numpy()\n true_classes_np = true_classes.detach().cpu().numpy()\n return average_precision_score(true_classes_np, predictions_np, pos_label=0) # Since 0 is label we care about, i.e., existing edges\n\n# This function compute MAP and MRR, via EvolveGCN support functions below\ndef compute_MAP_MRR(output, target, edges, do_softmax=True):\n MAP = 0.0\n MRR = 0.0\n # Compute MAP/MRR for each time slice and do weighted average\n for k in edges[0].unique():\n edges_mask = edges[0] == k\n w = t.sum(edges_mask).double()/t.tensor(len(edges_mask)).double()\n adj = edges[1:3, edges_mask]\n predictions = output[edges_mask, :]\n true_classes = target[edges_mask]\n MAP_slice = get_MAP(predictions, true_classes, True)\n MRR_slice = get_MRR(predictions, true_classes, adj, False)\n MAP += MAP_slice*w\n MRR += MRR_slice*w\n\n return MAP, MRR\n"
] |
[
[
"numpy.max",
"torch.Size",
"torch.zeros",
"torch.argmax",
"numpy.zeros",
"torch.no_grad",
"scipy.io.loadmat",
"torch.tensor",
"torch.sparse.sum",
"torch.nn.CrossEntropyLoss",
"torch.sum"
],
[
"torch.nn.Linear",
"torch.cat",
"torch.nn.SELU",
"torch.nn.LeakyReLU",
"torch.ones",
"sklearn.metrics.average_precision_score",
"torch.sum",
"torch.Size",
"numpy.max",
"torch.tensor",
"numpy.arange",
"numpy.linalg.inv",
"torch.sparse.mm",
"torch.zeros",
"scipy.sparse.coo_matrix",
"torch.max",
"torch.nn.ReLU",
"torch.matmul",
"torch.nn.Sigmoid",
"scipy.io.loadmat",
"torch.sparse.FloatTensor",
"torch.softmax",
"torch.sparse.sum",
"torch.randn",
"numpy.isin"
]
] |
NuriaValls/PSO-2RW-Applications
|
[
"129b75ec72fcb32bc9bf43c0ad3bf55c44423092"
] |
[
"Base_PSO/Visualization/boxplot.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\n\nfile1 = open('parabola.txt')\nfile2 = open('ackley.txt')\nfile3 = open('mmaxmmin.txt')\nfile4 = open('rosenbrock.txt')\n\n\nit1 = []\nit2 = []\nit3 = []\nit4 = []\np = 0\n\nfor line in file1:\n aux = line.rstrip('\\n').split(' ')\n it1.append(int(aux[2]))\n p += 1\n\np = 0\n\nfor line in file2:\n aux = line.rstrip('\\n').split(' ')\n it2.append(int(aux[2]))\n p += 1\n\np = 0\n\nfor line in file3:\n aux = line.rstrip('\\n').split(' ')\n it3.append(int(aux[2]))\n p += 1\n\np = 0\n\nfor line in file4:\n aux = line.rstrip('\\n').split(' ')\n it4.append(int(aux[2]))\n p += 1\n\n\ndata = [it1, it2, it3, it4]\n\nfig = plt.figure(figsize=(10,7))\nax = fig.add_subplot(111)\nax.set_title('Basic Plot')\nax.boxplot(data)\nax.set_title('Boxplot comparison of the number of iterations per function')\nax.set_xlabel('function index')\nax.set_ylabel('iterations until convergence')\n\nplt.savefig('boxplot.png', dpi=300)\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
ytchx1999/MAXP_DGL_Graph
|
[
"01ea0dc3e6f957b8c7a9b6958df02559f1866b32"
] |
[
"gnn/utils.py"
] |
[
"# -*- coding:utf-8 -*-\n\n\"\"\"\n Utilities to handel graph data\n\"\"\"\n\nimport os\nimport dgl\nimport pickle\nimport numpy as np\nimport torch as th\nfrom ogb.nodeproppred import DglNodePropPredDataset\n\n\ndef load_dgl_graph(base_path):\n \"\"\"\n 读取预处理的Graph,Feature和Label文件,并构建相应的数据供训练代码使用。\n\n :param base_path:\n :return:\n \"\"\"\n graphs, _ = dgl.load_graphs(os.path.join(base_path, 'graph.bin'))\n graph = graphs[0]\n print('################ Graph info: ###############', flush=True)\n print(graph)\n\n with open(os.path.join(base_path, 'labels.pkl'), 'rb') as f:\n label_data = pickle.load(f)\n\n labels = th.from_numpy(label_data['label'])\n tr_label_idx = label_data['tr_label_idx']\n val_label_idx = label_data['val_label_idx']\n test_label_idx = label_data['test_label_idx']\n print('################ Label info: ################', flush=True)\n print('Total labels (including not labeled): {}'.format(labels.shape[0]), flush=True)\n print(' Training label number: {}'.format(tr_label_idx.shape[0]), flush=True)\n print(' Validation label number: {}'.format(val_label_idx.shape[0]), flush=True)\n print(' Test label number: {}'.format(test_label_idx.shape[0]), flush=True)\n\n # get node features\n features = np.load(os.path.join(base_path, 'features.npy'))\n node_feat = th.from_numpy(features).float()\n print('################ Feature info: ###############', flush=True)\n print('Node\\'s feature shape:{}'.format(node_feat.shape), flush=True)\n\n return graph, labels, tr_label_idx, val_label_idx, test_label_idx, node_feat\n\n\ndef load_dgl_ogb_graph(base_path):\n \"\"\"\n 读取预处理的Graph,Feature和Label文件,并构建相应的数据供训练代码使用。\n\n :param base_path:\n :return:\n \"\"\"\n # graphs, _ = dgl.load_graphs(os.path.join(base_path, 'graph.bin'))\n # graph = graphs[0]\n # print('################ Graph info: ###############', flush=True)\n # print(graph)\n\n # with open(os.path.join(base_path, 'labels.pkl'), 'rb') as f:\n # label_data = pickle.load(f)\n\n # labels = th.from_numpy(label_data['label'])\n # tr_label_idx = label_data['tr_label_idx']\n # val_label_idx = label_data['val_label_idx']\n # test_label_idx = label_data['test_label_idx']\n # print('################ Label info: ################', flush=True)\n # print('Total labels (including not labeled): {}'.format(labels.shape[0]), flush=True)\n # print(' Training label number: {}'.format(tr_label_idx.shape[0]), flush=True)\n # print(' Validation label number: {}'.format(val_label_idx.shape[0]), flush=True)\n # print(' Test label number: {}'.format(test_label_idx.shape[0]), flush=True)\n\n # # get node features\n # features = np.load(os.path.join(base_path, 'features.npy'))\n # node_feat = th.from_numpy(features).float()\n # print('################ Feature info: ###############', flush=True)\n # print('Node\\'s feature shape:{}'.format(node_feat.shape), flush=True)\n\n # return graph, labels, tr_label_idx, val_label_idx, test_label_idx, node_feat\n\n dgldataset = DglNodePropPredDataset('ogbn-papers100M', root='../dataset/ogbn_papers100M') # 有待修改\n graph, labels = dgldataset[0]\n # srcs, dsts = graph.all_edges()\n # graph.add_edges(dsts, srcs)\n labels = labels.view(-1).type(th.long)\n splitted_idx = dgldataset.get_idx_split()\n train_idx, val_idx, test_idx = splitted_idx[\"train\"], splitted_idx[\"valid\"], splitted_idx[\"test\"]\n node_feat = graph.ndata['feat']\n return graph, labels, train_idx, val_idx, test_idx, node_feat\n\n\ndef time_diff(t_end, t_start):\n \"\"\"\n 计算时间差。t_end, t_start are datetime format, so use deltatime\n Parameters\n ----------\n t_end\n t_start\n\n Returns\n -------\n \"\"\"\n diff_sec = (t_end - t_start).seconds\n diff_min, rest_sec = divmod(diff_sec, 60)\n diff_hrs, rest_min = divmod(diff_min, 60)\n return (diff_hrs, rest_min, rest_sec)\n"
] |
[
[
"torch.from_numpy"
]
] |
wangzhen263/allennlp
|
[
"309b2b572aeb0677511b4f972281ac265d7477a9"
] |
[
"allennlp/nn/cov_beam_search.py"
] |
[
"from typing import List, Callable, Tuple, Dict\nimport warnings\n\nimport torch\nimport ipdb\n\nfrom allennlp.common.checks import ConfigurationError\n\n\nStateType = Dict[str, torch.Tensor] # pylint: disable=invalid-name\nStepFunctionType = Callable[[torch.Tensor, StateType], Tuple[torch.Tensor, StateType]] # pylint: disable=invalid-name\n\n\nclass CoverageBeamSearch:\n \"\"\"\n Implements the beam search algorithm for decoding the most likely sequences.\n\n Parameters\n ----------\n end_index : ``int``\n The index of the \"stop\" or \"end\" token in the target vocabulary.\n max_steps : ``int``, optional (default = 50)\n The maximum number of decoding steps to take, i.e. the maximum length\n of the predicted sequences.\n beam_size : ``int``, optional (default = 10)\n The width of the beam used.\n per_node_beam_size : ``int``, optional (default = beam_size)\n The maximum number of candidates to consider per node, at each step in the search.\n If not given, this just defaults to ``beam_size``. Setting this parameter\n to a number smaller than ``beam_size`` may give better results, as it can introduce\n more diversity into the search. See `Beam Search Strategies for Neural Machine Translation.\n Freitag and Al-Onaizan, 2017 <http://arxiv.org/abs/1702.01806>`_.\n \"\"\"\n\n def __init__(self,\n end_index: int,\n max_steps: int = 50,\n beam_size: int = 10,\n per_node_beam_size: int = None) -> None:\n self._end_index = end_index\n self.max_steps = max_steps\n self.beam_size = beam_size\n self.per_node_beam_size = per_node_beam_size or beam_size\n # self.per_node_beam_size = 1\n\n def search(self,\n start_predictions: torch.Tensor,\n start_state: StateType,\n step: StepFunctionType) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Given a starting state and a step function, apply beam search to find the\n most likely target sequences.\n\n Notes\n -----\n If your step function returns ``-inf`` for some log probabilities\n (like if you're using a masked log-softmax) then some of the \"best\"\n sequences returned may also have ``-inf`` log probability. Specifically\n this happens when the beam size is smaller than the number of actions\n with finite log probability (non-zero probability) returned by the step function.\n Therefore if you're using a mask you may want to check the results from ``search``\n and potentially discard sequences with non-finite log probability.\n\n Parameters\n ----------\n start_predictions : ``torch.Tensor``\n A tensor containing the initial predictions with shape ``(batch_size,)``.\n Usually the initial predictions are just the index of the \"start\" token\n in the target vocabulary.\n start_state : ``StateType``\n The initial state passed to the ``step`` function. Each value of the state dict\n should be a tensor of shape ``(batch_size, *)``, where ``*`` means any other\n number of dimensions.\n step : ``StepFunctionType``\n A function that is responsible for computing the next most likely tokens,\n given the current state and the predictions from the last time step.\n The function should accept two arguments. The first being a tensor\n of shape ``(group_size,)``, representing the index of the predicted\n tokens from the last time step, and the second being the current state.\n The ``group_size`` will be ``batch_size * beam_size``, except in the initial\n step, for which it will just be ``batch_size``.\n The function is expected to return a tuple, where the first element\n is a tensor of shape ``(group_size, target_vocab_size)`` containing\n the log probabilities of the tokens for the next step, and the second\n element is the updated state. The tensor in the state should have shape\n ``(group_size, *)``, where ``*`` means any other number of dimensions.\n\n Returns\n -------\n Tuple[torch.Tensor, torch.Tensor]\n Tuple of ``(predictions, log_probabilities)``, where ``predictions``\n has shape ``(batch_size, beam_size, max_steps)`` and ``log_probabilities``\n has shape ``(batch_size, beam_size)``.\n \"\"\"\n batch_size = start_predictions.size()[0]\n\n # List of (batch_size, beam_size) tensors. One for each time step. Does not\n # include the start symbols, which are implicit.\n predictions: List[torch.Tensor] = []\n # Same as predictions, but contains the log probabilities\n word_log_probabilities: List[torch.Tensor] = []\n\n # List of (batch_size, beam_size) tensors. One for each time step. None for\n # the first. Stores the index n for the parent prediction, i.e.\n # predictions[t-1][i][n], that it came from.\n backpointers: List[torch.Tensor] = []\n\n # Calculate the first timestep. This is done outside the main loop\n # because we are going from a single decoder input (the output from the\n # encoder) to the top `beam_size` decoder outputs. On the other hand,\n # within the main loop we are going from the `beam_size` elements of the\n # beam to `beam_size`^2 candidates from which we will select the top\n # `beam_size` elements for the next iteration.\n # shape: (batch_size, num_classes)\n start_class_log_probabilities, state = step(start_predictions, start_state)\n\n num_classes = start_class_log_probabilities.size()[1]\n\n # Make sure `per_node_beam_size` is not larger than `num_classes`.\n if self.per_node_beam_size > num_classes:\n raise ConfigurationError(f\"Target vocab size ({num_classes:d}) too small \"\n f\"relative to per_node_beam_size ({self.per_node_beam_size:d}).\\n\"\n f\"Please decrease beam_size or per_node_beam_size.\")\n\n # shape: (batch_size, beam_size), (batch_size, beam_size)\n start_top_log_probabilities, start_predicted_classes = \\\n start_class_log_probabilities.topk(self.beam_size)\n if self.beam_size == 1 and (start_predicted_classes == self._end_index).all():\n warnings.warn(\"Empty sequences predicted. You may want to increase the beam size or ensure \"\n \"your step function is working properly.\",\n RuntimeWarning)\n return start_predicted_classes.unsqueeze(-1), start_top_log_probabilities\n\n # The log probabilities for the last time step.\n # shape: (batch_size, beam_size)\n last_log_probabilities = start_top_log_probabilities\n\n # shape: [(batch_size, beam_size)]\n predictions.append(start_predicted_classes)\n word_log_probabilities.append(start_top_log_probabilities)\n\n # Log probability tensor that mandates that the end token is selected.\n # shape: (batch_size * beam_size, num_classes)\n log_probs_after_end = start_class_log_probabilities.new_full(\n (batch_size * self.beam_size, num_classes),\n float(\"-inf\")\n )\n log_probs_after_end[:, self._end_index] = 0.\n\n # Set the same state for each element in the beam.\n for key, state_tensor in state.items():\n _, *last_dims = state_tensor.size()\n # shape: (batch_size * beam_size, *)\n state[key] = state_tensor.\\\n unsqueeze(1).\\\n expand(batch_size, self.beam_size, *last_dims).\\\n reshape(batch_size * self.beam_size, *last_dims)\n\n for timestep in range(self.max_steps - 1):\n # shape: (batch_size * beam_size,)\n last_predictions = predictions[-1].reshape(batch_size * self.beam_size)\n\n # If every predicted token from the last step is `self._end_index`,\n # then we can stop early.\n if (last_predictions == self._end_index).all():\n break\n\n # Take a step. This get the predicted log probs of the next classes\n # and updates the state.\n # shape: (batch_size * beam_size, num_classes)\n class_log_probabilities, state = step(last_predictions, state)\n\n # shape: (batch_size * beam_size, num_classes)\n last_predictions_expanded = last_predictions.unsqueeze(-1).expand(\n batch_size * self.beam_size,\n num_classes\n )\n\n # Here we are finding any beams where we predicted the end token in\n # the previous timestep and replacing the distribution with a\n # one-hot distribution, forcing the beam to predict the end token\n # this timestep as well.\n # shape: (batch_size * beam_size, num_classes)\n cleaned_log_probabilities = torch.where(\n last_predictions_expanded == self._end_index,\n log_probs_after_end,\n class_log_probabilities\n )\n\n # shape (both): (batch_size * beam_size, per_node_beam_size)\n top_log_probabilities, predicted_classes = \\\n cleaned_log_probabilities.topk(self.per_node_beam_size)\n\n # Here we expand the last log probabilities to (batch_size * beam_size, per_node_beam_size)\n # so that we can add them to the current log probs for this timestep.\n # This lets us maintain the log probability of each element on the beam.\n # shape: (batch_size * beam_size, per_node_beam_size)\n expanded_last_log_probabilities = last_log_probabilities.\\\n unsqueeze(2).\\\n expand(batch_size, self.beam_size, self.per_node_beam_size).\\\n reshape(batch_size * self.beam_size, self.per_node_beam_size)\n\n # shape: (batch_size * beam_size, per_node_beam_size)\n summed_top_log_probabilities = top_log_probabilities + expanded_last_log_probabilities\n\n # shape: (batch_size, beam_size * per_node_beam_size)\n reshaped_summed = summed_top_log_probabilities.\\\n reshape(batch_size, self.beam_size * self.per_node_beam_size)\n\n # shape: (batch_size, beam_size * per_node_beam_size)\n reshaped_predicted_classes = predicted_classes.\\\n reshape(batch_size, self.beam_size * self.per_node_beam_size)\n\n # Keep only the top `beam_size` beam indices.\n # shape: (batch_size, beam_size), (batch_size, beam_size)\n restricted_beam_log_probs, restricted_beam_indices = reshaped_summed.topk(self.beam_size)\n\n\n # Use the beam indices to extract the corresponding classes.\n # shape: (batch_size, beam_size)\n restricted_predicted_classes = reshaped_predicted_classes.gather(1, restricted_beam_indices)\n\n # shape: (batch_size, beam_size * per_node_beam_size)\n reshaped_top_log_probabilities = top_log_probabilities.\\\n reshape(batch_size, self.beam_size * self.per_node_beam_size)\n # shape: (batch_size, beam_size)\n restricted_top_log_probs = reshaped_top_log_probabilities.gather(1, restricted_beam_indices)\n\n predictions.append(restricted_predicted_classes)\n word_log_probabilities.append(restricted_top_log_probs)\n\n # shape: (batch_size, beam_size)\n last_log_probabilities = restricted_beam_log_probs\n\n # The beam indices come from a `beam_size * per_node_beam_size` dimension where the\n # indices with a common ancestor are grouped together. Hence\n # dividing by per_node_beam_size gives the ancestor. (Note that this is integer\n # division as the tensor is a LongTensor.)\n # shape: (batch_size, beam_size)\n backpointer = restricted_beam_indices / self.per_node_beam_size\n\n backpointers.append(backpointer)\n\n # Keep only the pieces of the state tensors corresponding to the\n # ancestors created this iteration.\n for key, state_tensor in state.items():\n _, *last_dims = state_tensor.size()\n # shape: (batch_size, beam_size, *)\n expanded_backpointer = backpointer.\\\n view(batch_size, self.beam_size, *([1] * len(last_dims))).\\\n expand(batch_size, self.beam_size, *last_dims)\n\n # shape: (batch_size * beam_size, *)\n state[key] = state_tensor.\\\n reshape(batch_size, self.beam_size, *last_dims).\\\n gather(1, expanded_backpointer).\\\n reshape(batch_size * self.beam_size, *last_dims)\n\n if not torch.isfinite(last_log_probabilities).all():\n warnings.warn(\"Infinite log probabilities encountered. Some final sequences may not make sense. \"\n \"This can happen when the beam size is larger than the number of valid (non-zero \"\n \"probability) transitions that the step function produces.\",\n RuntimeWarning)\n\n # Reconstruct the sequences.\n # shape: [(batch_size, beam_size, 1)]\n reconstructed_predictions = [predictions[-1].unsqueeze(2)]\n reconstructed_word_log_probabilities = [word_log_probabilities[-1].unsqueeze(2)]\n\n # shape: (batch_size, beam_size)\n cur_backpointers = backpointers[-1]\n\n for timestep in range(len(predictions) - 2, 0, -1):\n # shape: (batch_size, beam_size, 1)\n cur_preds = predictions[timestep].gather(1, cur_backpointers).unsqueeze(2)\n cur_word_logs = word_log_probabilities[timestep].gather(1, cur_backpointers).unsqueeze(2)\n\n reconstructed_predictions.append(cur_preds)\n reconstructed_word_log_probabilities.append(cur_word_logs)\n\n # shape: (batch_size, beam_size)\n cur_backpointers = backpointers[timestep - 1].gather(1, cur_backpointers)\n\n # shape: (batch_size, beam_size, 1)\n final_preds = predictions[0].gather(1, cur_backpointers).unsqueeze(2)\n final_word_log_probabilities = word_log_probabilities[0].gather(1, cur_backpointers).unsqueeze(2)\n\n reconstructed_predictions.append(final_preds)\n reconstructed_word_log_probabilities.append(final_word_log_probabilities)\n\n # shape: (batch_size, beam_size, max_steps)\n all_predictions = torch.cat(list(reversed(reconstructed_predictions)), 2)\n all_word_log_probabilities = torch.cat(list(reversed(reconstructed_word_log_probabilities)), 2)\n\n return all_predictions, last_log_probabilities, all_word_log_probabilities\n"
] |
[
[
"torch.isfinite",
"torch.where"
]
] |
huuthieu/pytorch-yolov4-tiny
|
[
"fac82da75e161221af74b56242272a42cf64c17e"
] |
[
"utils/utils_bbox.py"
] |
[
"import torch\r\nimport torch.nn as nn\r\nfrom torchvision.ops import nms\r\nimport numpy as np\r\n\r\nclass DecodeBox():\r\n def __init__(self, anchors, num_classes, input_shape, anchors_mask = [[6,7,8], [3,4,5], [0,1,2]]):\r\n super(DecodeBox, self).__init__()\r\n self.anchors = anchors\r\n self.num_classes = num_classes\r\n self.bbox_attrs = 5 + num_classes\r\n self.input_shape = input_shape\r\n #-----------------------------------------------------------#\r\n # 13x13 anchor [81,82],[135,169],[344,319]\r\n # 26x26 anchor [10,14],[23,27],[37,58]\r\n #-----------------------------------------------------------#\r\n self.anchors_mask = anchors_mask\r\n\r\n def decode_box(self, inputs):\r\n outputs = []\r\n for i, input in enumerate(inputs):\r\n #-----------------------------------------------#\r\n # batch_size, 255, 13, 13\r\n # batch_size, 255, 26, 26\r\n #-----------------------------------------------#\r\n batch_size = input.size(0)\r\n input_height = input.size(2)\r\n input_width = input.size(3)\r\n\r\n #-----------------------------------------------#\r\n # stride_h = stride_w = 32、16\r\n #-----------------------------------------------#\r\n stride_h = self.input_shape[0] / input_height\r\n stride_w = self.input_shape[1] / input_width\r\n #-------------------------------------------------#\r\n # The scaled_anchors size obtained at this time is relative to the feature layer\r\n #-------------------------------------------------#\r\n scaled_anchors = [(anchor_width / stride_w, anchor_height / stride_h) for anchor_width, anchor_height in self.anchors[self.anchors_mask[i]]]\r\n\r\n #-----------------------------------------------#\r\n # batch_size, 3, 13, 13, 85\r\n # batch_size, 3, 26, 26, 85\r\n #-----------------------------------------------#\r\n prediction = input.view(batch_size, len(self.anchors_mask[i]),\r\n self.bbox_attrs, input_height, input_width).permute(0, 1, 3, 4, 2).contiguous()\r\n\r\n #-----------------------------------------------#\r\n #-----------------------------------------------#\r\n x = torch.sigmoid(prediction[..., 0]) \r\n y = torch.sigmoid(prediction[..., 1])\r\n #-----------------------------------------------#\r\n #-----------------------------------------------#\r\n w = prediction[..., 2]\r\n h = prediction[..., 3]\r\n #-----------------------------------------------#\r\n #-----------------------------------------------#\r\n conf = torch.sigmoid(prediction[..., 4])\r\n #-----------------------------------------------#\r\n #-----------------------------------------------#\r\n pred_cls = torch.sigmoid(prediction[..., 5:])\r\n\r\n FloatTensor = torch.cuda.FloatTensor if x.is_cuda else torch.FloatTensor\r\n LongTensor = torch.cuda.LongTensor if x.is_cuda else torch.LongTensor\r\n\r\n #----------------------------------------------------------#\r\n # Generate grid, a priori box center, top left corner of grid\r\n # batch_size,3,13,13\r\n #----------------------------------------------------------#\r\n grid_x = torch.linspace(0, input_width - 1, input_width).repeat(input_height, 1).repeat(\r\n batch_size * len(self.anchors_mask[i]), 1, 1).view(x.shape).type(FloatTensor)\r\n grid_y = torch.linspace(0, input_height - 1, input_height).repeat(input_width, 1).t().repeat(\r\n batch_size * len(self.anchors_mask[i]), 1, 1).view(y.shape).type(FloatTensor)\r\n\r\n #----------------------------------------------------------#\r\n # Generate the width and height of the prior box according to the grid format\r\n # batch_size,3,13,13\r\n #----------------------------------------------------------#\r\n anchor_w = FloatTensor(scaled_anchors).index_select(1, LongTensor([0]))\r\n anchor_h = FloatTensor(scaled_anchors).index_select(1, LongTensor([1]))\r\n anchor_w = anchor_w.repeat(batch_size, 1).repeat(1, 1, input_height * input_width).view(w.shape)\r\n anchor_h = anchor_h.repeat(batch_size, 1).repeat(1, 1, input_height * input_width).view(h.shape)\r\n\r\n #----------------------------------------------------------#\r\n #----------------------------------------------------------#\r\n pred_boxes = FloatTensor(prediction[..., :4].shape)\r\n pred_boxes[..., 0] = x.data + grid_x\r\n pred_boxes[..., 1] = y.data + grid_y\r\n pred_boxes[..., 2] = torch.exp(w.data) * anchor_w\r\n pred_boxes[..., 3] = torch.exp(h.data) * anchor_h\r\n\r\n #----------------------------------------------------------#\r\n # Normalize the output result to [0,1]\r\n #----------------------------------------------------------#\r\n _scale = torch.Tensor([input_width, input_height, input_width, input_height]).type(FloatTensor)\r\n output = torch.cat((pred_boxes.view(batch_size, -1, 4) / _scale,\r\n conf.view(batch_size, -1, 1), pred_cls.view(batch_size, -1, self.num_classes)), -1)\r\n outputs.append(output.data)\r\n return outputs\r\n\r\n def yolo_correct_boxes(self, box_xy, box_wh, input_shape, image_shape, letterbox_image):\r\n #-----------------------------------------------------------------#\r\n #-----------------------------------------------------------------#\r\n box_yx = box_xy[..., ::-1]\r\n box_hw = box_wh[..., ::-1]\r\n input_shape = np.array(input_shape)\r\n image_shape = np.array(image_shape)\r\n\r\n if letterbox_image:\r\n #-----------------------------------------------------------------#\r\n # The offset obtained here is the offset of the effective area of the image relative to the upper left corner of the image\r\n # new_shape refers to the width and height scaling\r\n #-----------------------------------------------------------------#\r\n new_shape = np.round(image_shape * np.min(input_shape/image_shape))\r\n offset = (input_shape - new_shape)/2./input_shape\r\n scale = input_shape/new_shape\r\n\r\n box_yx = (box_yx - offset) * scale\r\n box_hw *= scale\r\n\r\n box_mins = box_yx - (box_hw / 2.)\r\n box_maxes = box_yx + (box_hw / 2.)\r\n boxes = np.concatenate([box_mins[..., 0:1], box_mins[..., 1:2], box_maxes[..., 0:1], box_maxes[..., 1:2]], axis=-1)\r\n boxes *= np.concatenate([image_shape, image_shape], axis=-1)\r\n return boxes\r\n\r\n def non_max_suppression(self, prediction, num_classes, input_shape, image_shape, letterbox_image, conf_thres=0.5, nms_thres=0.4):\r\n #----------------------------------------------------------#\r\n # Convert the format of the prediction result to the format in the upper left corner and lower right corner.\r\n # prediction [batch_size, num_anchors, 85]\r\n #----------------------------------------------------------#\r\n box_corner = prediction.new(prediction.shape)\r\n box_corner[:, :, 0] = prediction[:, :, 0] - prediction[:, :, 2] / 2\r\n box_corner[:, :, 1] = prediction[:, :, 1] - prediction[:, :, 3] / 2\r\n box_corner[:, :, 2] = prediction[:, :, 0] + prediction[:, :, 2] / 2\r\n box_corner[:, :, 3] = prediction[:, :, 1] + prediction[:, :, 3] / 2\r\n prediction[:, :, :4] = box_corner[:, :, :4]\r\n\r\n output = [None for _ in range(len(prediction))]\r\n for i, image_pred in enumerate(prediction):\r\n #----------------------------------------------------------#\r\n # Take max for the category prediction\r\n # class_conf [num_anchors, 1] confidence score\r\n # class_pred [num_anchors, 1] class\r\n #----------------------------------------------------------#\r\n class_conf, class_pred = torch.max(image_pred[:, 5:5 + num_classes], 1, keepdim=True)\r\n\r\n #----------------------------------------------------------#\r\n #----------------------------------------------------------#\r\n conf_mask = (image_pred[:, 4] * class_conf[:, 0] >= conf_thres).squeeze()\r\n\r\n #----------------------------------------------------------#\r\n #----------------------------------------------------------#\r\n image_pred = image_pred[conf_mask]\r\n class_conf = class_conf[conf_mask]\r\n class_pred = class_pred[conf_mask]\r\n if not image_pred.size(0):\r\n continue\r\n #-------------------------------------------------------------------------#\r\n # detections [num_anchors, 7]\r\n # 7 attrs:x1, y1, x2, y2, obj_conf, class_conf, class_pred\r\n #-------------------------------------------------------------------------#\r\n detections = torch.cat((image_pred[:, :5], class_conf.float(), class_pred.float()), 1)\r\n\r\n #------------------------------------------#\r\n # Get all the categories included in the prediction result\r\n #------------------------------------------#\r\n unique_labels = detections[:, -1].cpu().unique()\r\n\r\n if prediction.is_cuda:\r\n unique_labels = unique_labels.cuda()\r\n detections = detections.cuda()\r\n\r\n for c in unique_labels:\r\n #------------------------------------------#\r\n # Get all the prediction results after a certain category score filter\r\n #------------------------------------------#\r\n detections_class = detections[detections[:, -1] == c]\r\n\r\n keep = nms(\r\n detections_class[:, :4],\r\n detections_class[:, 4] * detections_class[:, 5],\r\n nms_thres\r\n )\r\n max_detections = detections_class[keep]\r\n \r\n # # Sort by confidence in the existence of objects\r\n # _, conf_sort_index = torch.sort(detections_class[:, 4]*detections_class[:, 5], descending=True)\r\n # detections_class = detections_class[conf_sort_index]\r\n # # NMS\r\n # max_detections = []\r\n # while detections_class.size(0):\r\n # Take out this category with the highest confidence, \r\n # and judge step by step to determine whether the degree of coincidence is greater than nms_thres, \r\n # and if so, remove it# 取出这一类置信度最高的,一步一步往下判断,判断重合程度是否大于nms_thres,如果是则去除掉\r\n # max_detections.append(detections_class[0].unsqueeze(0))\r\n # if len(detections_class) == 1:\r\n # break\r\n # ious = bbox_iou(max_detections[-1], detections_class[1:])\r\n # detections_class = detections_class[1:][ious < nms_thres]\r\n \r\n # max_detections = torch.cat(max_detections).data\r\n \r\n # Add max detections to outputs\r\n output[i] = max_detections if output[i] is None else torch.cat((output[i], max_detections))\r\n \r\n if output[i] is not None:\r\n output[i] = output[i].cpu().numpy()\r\n box_xy, box_wh = (output[i][:, 0:2] + output[i][:, 2:4])/2, output[i][:, 2:4] - output[i][:, 0:2]\r\n output[i][:, :4] = self.yolo_correct_boxes(box_xy, box_wh, input_shape, image_shape, letterbox_image)\r\n return output\r\n"
] |
[
[
"numpy.concatenate",
"torch.sigmoid",
"numpy.array",
"torch.cat",
"torch.max",
"numpy.min",
"torch.linspace",
"torch.Tensor",
"torch.exp"
]
] |
yzh211/pgmpy
|
[
"f3abe04abb75db9f51f333ecf9429a8700477b55",
"f3abe04abb75db9f51f333ecf9429a8700477b55"
] |
[
"pgmpy/tests/test_factors/test_continuous/test_Canonical_Factor.py",
"pgmpy/sampling/HMC.py"
] |
[
"import unittest\n\nimport numpy as np\nimport numpy.testing as np_test\n\nfrom pgmpy.factors.distributions import GaussianDistribution as JGD\nfrom pgmpy.factors.continuous import CanonicalDistribution\n\n\nclass TestCanonicalFactor(unittest.TestCase):\n def test_class_init(self):\n phi = CanonicalDistribution(\n [\"x1\", (\"y\", \"z\"), \"x3\"],\n np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]]),\n np.array([[1], [4.7], [-1]]),\n -2,\n )\n self.assertEqual(phi.variables, [\"x1\", (\"y\", \"z\"), \"x3\"])\n np_test.assert_array_equal(\n phi.K, np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]], dtype=float)\n )\n np_test.assert_array_equal(phi.h, np.array([[1], [4.7], [-1]], dtype=float))\n self.assertEqual(phi.g, -2)\n\n phi = CanonicalDistribution(\n [\"x1\", (\"y\", \"z\"), \"x3\"],\n np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]]),\n np.array([1, 4.7, -1]),\n -2,\n )\n self.assertEqual(phi.variables, [\"x1\", (\"y\", \"z\"), \"x3\"])\n np_test.assert_array_equal(\n phi.K, np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]], dtype=float)\n )\n np_test.assert_array_equal(phi.h, np.array([[1], [4.7], [-1]], dtype=float))\n self.assertEqual(phi.g, -2)\n\n phi = CanonicalDistribution([\"x\"], [[1]], [0], 1)\n self.assertEqual(phi.variables, [\"x\"])\n np_test.assert_array_equal(phi.K, np.array([[1]], dtype=float))\n np_test.assert_array_equal(phi.h, np.array([[0]], dtype=float))\n self.assertEqual(phi.g, 1)\n\n def test_class_init_valueerror(self):\n self.assertRaises(\n ValueError,\n CanonicalDistribution,\n [\"x1\", \"x2\", \"x3\"],\n np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]], dtype=float),\n np.array([1, 2], dtype=float),\n 7,\n )\n self.assertRaises(\n ValueError,\n CanonicalDistribution,\n [\"x1\", \"x2\", \"x3\"],\n np.array([[1.1, -1, 0], [-1, 4], [0, -2, 4]], dtype=object),\n np.array([1, 2, 3], dtype=float),\n 7,\n )\n self.assertRaises(\n ValueError,\n CanonicalDistribution,\n [\"x1\", \"x2\", \"x3\"],\n np.array([[1.1, -1, 0], [0, -2, 4]], dtype=float),\n np.array([1, 2, 3], dtype=float),\n 7,\n )\n self.assertRaises(\n ValueError,\n CanonicalDistribution,\n [\"x1\", \"x3\"],\n np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]], dtype=float),\n np.array([1, 2, 3], dtype=float),\n 7,\n )\n\n\nclass TestJGDMethods(unittest.TestCase):\n def setUp(self):\n self.phi1 = CanonicalDistribution(\n [\"x1\", \"x2\", \"x3\"],\n np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]]),\n np.array([[1], [4.7], [-1]]),\n -2,\n )\n self.phi2 = CanonicalDistribution([\"x\"], [[1]], [0], 1)\n self.phi3 = self.phi1.copy()\n\n self.gauss_phi1 = JGD(\n [\"x1\", \"x2\", \"x3\"],\n np.array([[3.13043478], [2.44347826], [0.97173913]]),\n np.array(\n [\n [1.30434783, 0.43478261, 0.2173913],\n [0.43478261, 0.47826087, 0.23913043],\n [0.2173913, 0.23913043, 0.36956522],\n ],\n dtype=float,\n ),\n )\n self.gauss_phi2 = JGD([\"x\"], np.array([0]), np.array([[1]]))\n\n def test_assignment(self):\n np_test.assert_almost_equal(self.phi1.assignment(1, 2, 3), 0.0007848640)\n np_test.assert_almost_equal(self.phi2.assignment(1.2), 1.323129812337)\n\n def test_to_joint_gaussian(self):\n jgd1 = self.phi1.to_joint_gaussian()\n jgd2 = self.phi2.to_joint_gaussian()\n\n self.assertEqual(jgd1.variables, self.gauss_phi1.variables)\n np_test.assert_almost_equal(jgd1.covariance, self.gauss_phi1.covariance)\n np_test.assert_almost_equal(jgd1.mean, self.gauss_phi1.mean)\n\n self.assertEqual(jgd2.variables, self.gauss_phi2.variables)\n np_test.assert_almost_equal(jgd2.covariance, self.gauss_phi2.covariance)\n np_test.assert_almost_equal(jgd2.mean, self.gauss_phi2.mean)\n\n def test_reduce(self):\n phi = self.phi1.reduce([(\"x1\", 7)], inplace=False)\n self.assertEqual(phi.variables, [\"x2\", \"x3\"])\n np_test.assert_almost_equal(phi.K, np.array([[4.0, -2.0], [-2.0, 4.0]]))\n np_test.assert_almost_equal(phi.h, np.array([[11.7], [-1.0]]))\n np_test.assert_almost_equal(phi.g, -21.95)\n\n phi = self.phi1.reduce([(\"x1\", 4), (\"x2\", 1.23)], inplace=False)\n self.assertEqual(phi.variables, [\"x3\"])\n np_test.assert_almost_equal(phi.K, np.array([[4.0]]))\n np_test.assert_almost_equal(phi.h, np.array([[1.46]]))\n np_test.assert_almost_equal(phi.g, 0.8752)\n\n self.phi1.reduce([(\"x1\", 7)])\n self.assertEqual(self.phi1.variables, [\"x2\", \"x3\"])\n np_test.assert_almost_equal(self.phi1.K, np.array([[4.0, -2.0], [-2.0, 4.0]]))\n np_test.assert_almost_equal(self.phi1.h, np.array([[11.7], [-1.0]]))\n np_test.assert_almost_equal(self.phi1.g, -21.95)\n\n self.phi1 = self.phi3.copy()\n self.phi1.reduce([(\"x1\", 4), (\"x2\", 1.23)])\n self.assertEqual(self.phi1.variables, [\"x3\"])\n np_test.assert_almost_equal(self.phi1.K, np.array([[4.0]]))\n np_test.assert_almost_equal(self.phi1.h, np.array([[1.46]]))\n np_test.assert_almost_equal(self.phi1.g, 0.8752)\n\n self.phi1 = self.phi3.copy()\n self.phi1.reduce([(\"x2\", 1.23), (\"x1\", 4)])\n self.assertEqual(self.phi1.variables, [\"x3\"])\n np_test.assert_almost_equal(self.phi1.K, np.array([[4.0]]))\n np_test.assert_almost_equal(self.phi1.h, np.array([[1.46]]))\n np_test.assert_almost_equal(self.phi1.g, 0.8752)\n\n def test_marginalize(self):\n phi = self.phi1.marginalize([\"x1\"], inplace=False)\n self.assertEqual(phi.variables, [\"x2\", \"x3\"])\n np_test.assert_almost_equal(phi.K, np.array([[3.090909, -2.0], [-2.0, 4.0]]))\n np_test.assert_almost_equal(phi.h, np.array([[5.6090909], [-1.0]]))\n np_test.assert_almost_equal(phi.g, -0.5787165566)\n\n phi = self.phi1.marginalize([\"x1\", \"x2\"], inplace=False)\n self.assertEqual(phi.variables, [\"x3\"])\n np_test.assert_almost_equal(phi.K, np.array([[2.70588235]]))\n np_test.assert_almost_equal(phi.h, np.array([[2.62941176]]))\n np_test.assert_almost_equal(phi.g, 39.25598935059)\n\n self.phi1.marginalize([\"x1\"])\n self.assertEqual(self.phi1.variables, [\"x2\", \"x3\"])\n np_test.assert_almost_equal(\n self.phi1.K, np.array([[3.090909, -2.0], [-2.0, 4.0]])\n )\n np_test.assert_almost_equal(self.phi1.h, np.array([[5.6090909], [-1.0]]))\n np_test.assert_almost_equal(self.phi1.g, -0.5787165566)\n\n self.phi1 = self.phi3\n self.phi1.marginalize([\"x1\", \"x2\"])\n self.assertEqual(self.phi1.variables, [\"x3\"])\n np_test.assert_almost_equal(self.phi1.K, np.array([[2.70588235]]))\n np_test.assert_almost_equal(self.phi1.h, np.array([[2.62941176]]))\n np_test.assert_almost_equal(self.phi1.g, 39.25598935059)\n\n self.phi1 = self.phi3\n\n def test_operate(self):\n phi1 = self.phi1 * CanonicalDistribution(\n [\"x2\", \"x4\"], [[1, 2], [3, 4]], [0, 4.56], -6.78\n )\n phi2 = self.phi1 / CanonicalDistribution(\n [\"x2\", \"x3\"], [[1, 2], [3, 4]], [0, 4.56], -6.78\n )\n\n self.assertEqual(phi1.variables, [\"x1\", \"x2\", \"x3\", \"x4\"])\n np_test.assert_almost_equal(\n phi1.K,\n np.array(\n [\n [1.1, -1.0, 0.0, 0.0],\n [-1.0, 5.0, -2.0, 2.0],\n [0.0, -2.0, 4.0, 0.0],\n [0.0, 3.0, 0.0, 4.0],\n ]\n ),\n )\n np_test.assert_almost_equal(phi1.h, np.array([[1.0], [4.7], [-1.0], [4.56]]))\n np_test.assert_almost_equal(phi1.g, -8.78)\n\n self.assertEqual(phi2.variables, [\"x1\", \"x2\", \"x3\"])\n np_test.assert_almost_equal(\n phi2.K, np.array([[1.1, -1.0, 0.0], [-1.0, 3.0, -4.0], [0.0, -5.0, 0.0]])\n )\n np_test.assert_almost_equal(phi2.h, np.array([[1.0], [4.7], [-5.56]]))\n np_test.assert_almost_equal(phi2.g, 4.78)\n\n def test_copy(self):\n copy_phi1 = self.phi1.copy()\n self.assertEqual(copy_phi1.variables, self.phi1.variables)\n np_test.assert_array_equal(copy_phi1.K, self.phi1.K)\n np_test.assert_array_equal(copy_phi1.h, self.phi1.h)\n np_test.assert_array_equal(copy_phi1.g, self.phi1.g)\n\n copy_phi1.marginalize([\"x1\"])\n self.assertEqual(self.phi1.variables, [\"x1\", \"x2\", \"x3\"])\n np_test.assert_array_equal(\n self.phi1.K, np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]], dtype=float)\n )\n np_test.assert_array_equal(\n self.phi1.h, np.array([[1], [4.7], [-1]], dtype=float)\n )\n self.assertEqual(self.phi1.g, -2)\n\n self.phi1.marginalize([\"x2\"])\n self.assertEqual(copy_phi1.variables, [\"x2\", \"x3\"])\n np_test.assert_almost_equal(\n copy_phi1.K, np.array([[3.090909, -2.0], [-2.0, 4.0]])\n )\n np_test.assert_almost_equal(copy_phi1.h, np.array([[5.6090909], [-1.0]]))\n np_test.assert_almost_equal(copy_phi1.g, -0.5787165566)\n\n self.phi1 = self.phi3\n\n def tearDown(self):\n del self.phi1\n del self.phi2\n del self.phi3\n del self.gauss_phi1\n del self.gauss_phi2\n",
"# -*- coding: UTF-8 -*-\n\"\"\"\n A collection of methods for sampling from continuous models in pgmpy\n\"\"\"\nfrom math import sqrt\n\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom pgmpy.utils import _check_1d_array_object, _check_length_equal\nfrom pgmpy.sampling import (\n LeapFrog,\n BaseSimulateHamiltonianDynamics,\n BaseGradLogPDF,\n _return_samples,\n)\n\n\nclass HamiltonianMC(object):\n \"\"\"\n Class for performing sampling using simple\n Hamiltonian Monte Carlo\n\n Parameters\n ----------\n model: An instance pgmpy.models\n Model from which sampling has to be done\n\n grad_log_pdf: A subclass of pgmpy.inference.continuous.BaseGradLogPDF, defaults to None\n A class to find log and gradient of log distribution for a given assignment\n If None, then will use model.get_gradient_log_pdf\n\n simulate_dynamics: A subclass of pgmpy.inference.continuous.BaseSimulateHamiltonianDynamics\n A class to propose future values of momentum and position in time by simulating\n Hamiltonian Dynamics\n\n Example\n -------\n >>> from pgmpy.sampling import HamiltonianMC as HMC, LeapFrog, GradLogPDFGaussian\n >>> from pgmpy.factors.continuous import GaussianDistribution as JGD\n >>> import numpy as np\n >>> mean = np.array([-3, 4])\n >>> covariance = np.array([[3, 0.7], [0.7, 5]])\n >>> model = JGD(['x', 'y'], mean, covariance)\n >>> sampler = HMC(model=model, grad_log_pdf=GradLogPDFGaussian, simulate_dynamics=LeapFrog)\n >>> samples = sampler.sample(initial_pos=np.array([1, 1]), num_samples = 10000,\n ... trajectory_length=2, stepsize=0.4, return_type='recarray')\n >>> samples\n rec.array([(1.0, 1.0), (-3.1861687131079086, 3.7940994520145654),\n (-1.6920542547310844, 6.347410703806017), ...,\n (-1.8093621120575312, 5.940860883943261),\n (0.3933248026088032, 6.3853098838119235),\n (-0.8654072934719572, 6.023803629334816)],\n dtype=[('x', '<f8'), ('y', '<f8')])\n\n >>> samples = np.array([samples[var_name] for var_name in model.variables])\n >>> np.cov(samples)\n array([[ 3.0352818 , 0.71379304],\n [ 0.71379304, 4.91776713]])\n >>> sampler.accepted_proposals\n 9932.0\n >>> sampler.acceptance_rate\n 0.9932\n\n References\n ----------\n R.Neal. Handbook of Markov Chain Monte Carlo,\n chapter 5: MCMC Using Hamiltonian Dynamics.\n CRC Press, 2011.\n \"\"\"\n\n def __init__(self, model, grad_log_pdf, simulate_dynamics=LeapFrog):\n\n if not issubclass(grad_log_pdf, BaseGradLogPDF):\n raise TypeError(\n \"grad_log_pdf must be an instance of \"\n + \"pgmpy.inference.base_continuous.BaseGradLogPDF\"\n )\n\n if not issubclass(simulate_dynamics, BaseSimulateHamiltonianDynamics):\n raise TypeError(\n \"split_time must be an instance of \"\n + \"pgmpy.inference.base_continuous.BaseSimulateHamiltonianDynamics\"\n )\n\n self.model = model\n self.grad_log_pdf = grad_log_pdf\n self.simulate_dynamics = simulate_dynamics\n self.accepted_proposals = 0.0\n self.acceptance_rate = 0\n\n def _acceptance_prob(self, position, position_bar, momentum, momentum_bar):\n \"\"\"\n Returns the acceptance probability for given new position(position) and momentum\n \"\"\"\n\n # Parameters to help in evaluating Joint distribution P(position, momentum)\n _, logp = self.grad_log_pdf(position, self.model).get_gradient_log_pdf()\n _, logp_bar = self.grad_log_pdf(position_bar, self.model).get_gradient_log_pdf()\n\n # acceptance_prob = P(position_bar, momentum_bar)/ P(position, momentum)\n potential_change = logp_bar - logp # Negative change\n kinetic_change = 0.5 * np.float(\n np.dot(momentum_bar.T, momentum_bar) - np.dot(momentum.T, momentum)\n )\n\n # acceptance probability\n return np.exp(potential_change - kinetic_change)\n\n def _get_condition(self, acceptance_prob, a):\n \"\"\"\n Temporary method to fix issue in numpy 0.12 #852\n \"\"\"\n if a == 1:\n return (acceptance_prob ** a) > (1 / (2 ** a))\n else:\n return (1 / (acceptance_prob ** a)) > (2 ** (-a))\n\n def _find_reasonable_stepsize(self, position, stepsize_app=1):\n \"\"\"\n Method for choosing initial value of stepsize\n\n References\n -----------\n Matthew D. Hoffman, Andrew Gelman, The No-U-Turn Sampler: Adaptively\n Setting Path Lengths in Hamiltonian Monte Carlo. Journal of\n Machine Learning Research 15 (2014) 1351-1381\n Algorithm 4 : Heuristic for choosing an initial value of epsilon\n \"\"\"\n # momentum = N(0, I)\n momentum = np.reshape(np.random.normal(0, 1, len(position)), position.shape)\n\n # Take a single step in time\n position_bar, momentum_bar, _ = self.simulate_dynamics(\n self.model, position, momentum, stepsize_app, self.grad_log_pdf\n ).get_proposed_values()\n\n acceptance_prob = self._acceptance_prob(\n position, position_bar, momentum, momentum_bar\n )\n\n # a = 2I[acceptance_prob] -1\n a = 2 * (acceptance_prob > 0.5) - 1\n\n condition = self._get_condition(acceptance_prob, a)\n\n while condition:\n stepsize_app = (2 ** a) * stepsize_app\n\n position_bar, momentum_bar, _ = self.simulate_dynamics(\n self.model, position, momentum, stepsize_app, self.grad_log_pdf\n ).get_proposed_values()\n\n acceptance_prob = self._acceptance_prob(\n position, position_bar, momentum, momentum_bar\n )\n\n condition = self._get_condition(acceptance_prob, a)\n\n return stepsize_app\n\n def _sample(self, position, trajectory_length, stepsize, lsteps=None):\n \"\"\"\n Runs a single sampling iteration to return a sample\n \"\"\"\n # Resampling momentum\n momentum = np.reshape(np.random.normal(0, 1, len(position)), position.shape)\n\n # position_m here will be the previous sampled value of position\n position_bar, momentum_bar = position.copy(), momentum\n\n # Number of steps L to simulate dynamics\n if lsteps is None:\n lsteps = int(max(1, round(trajectory_length / stepsize, 0)))\n\n grad_bar, _ = self.grad_log_pdf(position_bar, self.model).get_gradient_log_pdf()\n\n for _ in range(lsteps):\n position_bar, momentum_bar, grad_bar = self.simulate_dynamics(\n self.model,\n position_bar,\n momentum_bar,\n stepsize,\n self.grad_log_pdf,\n grad_bar,\n ).get_proposed_values()\n\n acceptance_prob = self._acceptance_prob(\n position, position_bar, momentum, momentum_bar\n )\n\n # Metropolis acceptance probability\n alpha = min(1, acceptance_prob)\n\n # Accept or reject the new proposed value of position, i.e position_bar\n if np.random.rand() < alpha:\n position = position_bar.copy()\n self.accepted_proposals += 1.0\n\n return position, alpha\n\n def sample(\n self,\n initial_pos,\n num_samples,\n trajectory_length,\n stepsize=None,\n return_type=\"dataframe\",\n ):\n \"\"\"\n Method to return samples using Hamiltonian Monte Carlo\n\n Parameters\n ----------\n initial_pos: A 1d array like object\n Vector representing values of parameter position, the starting\n state in markov chain.\n\n num_samples: int\n Number of samples to be generated\n\n trajectory_length: int or float\n Target trajectory length, stepsize * number of steps(L),\n where L is the number of steps taken per HMC iteration,\n and stepsize is step size for splitting time method.\n\n stepsize: float , defaults to None\n The stepsize for proposing new values of position and momentum in simulate_dynamics\n If None, then will be chosen suitably\n\n return_type: string (dataframe | recarray)\n Return type for samples, either of 'dataframe' or 'recarray'.\n Defaults to 'dataframe'\n\n Returns\n -------\n sampled: A pandas.DataFrame or a numpy.recarray object depending upon return_type argument\n\n Examples\n --------\n >>> from pgmpy.sampling import HamiltonianMC as HMC, GradLogPDFGaussian, ModifiedEuler\n >>> from pgmpy.factors.continuous import GaussianDistribution as JGD\n >>> import numpy as np\n >>> mean = np.array([1, -1])\n >>> covariance = np.array([[1, 0.2], [0.2, 1]])\n >>> model = JGD(['x', 'y'], mean, covariance)\n >>> sampler = HMC(model=model, grad_log_pdf=GradLogPDFGaussian, simulate_dynamics=ModifiedEuler)\n >>> samples = sampler.sample(np.array([1, 1]), num_samples = 5,\n ... trajectory_length=6, stepsize=0.25, return_type='dataframe')\n >>> samples\n x y\n 0 1.000000e+00 1.000000e+00\n 1 1.592133e+00 1.152911e+00\n 2 1.608700e+00 1.315349e+00\n 3 1.608700e+00 1.315349e+00\n 4 6.843856e-01 6.237043e-01\n >>> mean = np.array([4, 1, -1])\n >>> covariance = np.array([[1, 0.7 , 0.8], [0.7, 1, 0.2], [0.8, 0.2, 1]])\n >>> model = JGD(['x', 'y', 'z'], mean, covariance)\n >>> sampler = HMC(model=model, grad_log_pdf=GLPG)\n >>> samples = sampler.sample(np.array([1, 1]), num_samples = 10000,\n ... trajectory_length=6, stepsize=0.25, return_type='dataframe')\n >>> np.cov(samples.values.T)\n array([[ 1.00795398, 0.71384233, 0.79802097],\n [ 0.71384233, 1.00633524, 0.21313767],\n [ 0.79802097, 0.21313767, 0.98519017]])\n \"\"\"\n\n self.accepted_proposals = 1.0\n initial_pos = _check_1d_array_object(initial_pos, \"initial_pos\")\n _check_length_equal(\n initial_pos, self.model.variables, \"initial_pos\", \"model.variables\"\n )\n\n if stepsize is None:\n stepsize = self._find_reasonable_stepsize(initial_pos)\n\n types = [(var_name, \"float\") for var_name in self.model.variables]\n samples = np.zeros(num_samples, dtype=types).view(np.recarray)\n\n # Assigning after converting into tuple because value was being changed after assignment\n # Reason for this is unknown\n samples[0] = tuple(initial_pos)\n position_m = initial_pos\n\n lsteps = int(max(1, round(trajectory_length / stepsize, 0)))\n for i in tqdm(range(1, num_samples)):\n\n # Genrating sample\n position_m, _ = self._sample(\n position_m, trajectory_length, stepsize, lsteps\n )\n samples[i] = tuple(position_m)\n\n self.acceptance_rate = self.accepted_proposals / num_samples\n\n return _return_samples(return_type, samples)\n\n def generate_sample(\n self, initial_pos, num_samples, trajectory_length, stepsize=None\n ):\n \"\"\"\n Method returns a generator type object whose each iteration yields a sample\n using Hamiltonian Monte Carlo\n\n Parameters\n ----------\n initial_pos: A 1d array like object\n Vector representing values of parameter position, the starting\n state in markov chain.\n\n num_samples: int\n Number of samples to be generated\n\n trajectory_length: int or float\n Target trajectory length, stepsize * number of steps(L),\n where L is the number of steps taken per HMC iteration,\n and stepsize is step size for splitting time method.\n\n stepsize: float , defaults to None\n The stepsize for proposing new values of position and momentum in simulate_dynamics\n If None, then will be chosen suitably\n\n Returns\n -------\n genrator: yielding a 1d numpy.array type object for a sample\n\n Examples\n --------\n >>> from pgmpy.sampling import HamiltonianMC as HMC, GradLogPDFGaussian as GLPG\n >>> from pgmpy.factors import GaussianDistribution as JGD\n >>> import numpy as np\n >>> mean = np.array([4, -1])\n >>> covariance = np.array([[3, 0.4], [0.4, 3]])\n >>> model = JGD(['x', 'y'], mean, covariance)\n >>> sampler = HMC(model=model, grad_log_pdf=GLPG)\n >>> gen_samples = sampler.generate_sample(np.array([-1, 1]), num_samples = 10000,\n ... trajectory_length=2, stepsize=0.25)\n >>> samples_array = np.array([sample for sample in gen_samples])\n >>> samples_array\n array([[ 0.1467264 , 0.27143857],\n [ 4.0371448 , 0.15871274],\n [ 3.24656208, -1.03742621],\n ...,\n [ 6.45975905, 1.97941306],\n [ 4.89007171, 0.15413156],\n [ 5.9528083 , 1.92983158]])\n >>> np.cov(samples_array.T)\n array([[ 2.95692642, 0.4379419 ],\n [ 0.4379419 , 3.00939434]])\n >>> sampler.acceptance_rate\n 0.9969\n \"\"\"\n\n self.accepted_proposals = 0\n initial_pos = _check_1d_array_object(initial_pos, \"initial_pos\")\n _check_length_equal(\n initial_pos, self.model.variables, \"initial_pos\", \"model.variables\"\n )\n\n if stepsize is None:\n stepsize = self._find_reasonable_stepsize(initial_pos)\n\n lsteps = int(max(1, round(trajectory_length / stepsize, 0)))\n position_m = initial_pos.copy()\n\n for i in range(0, num_samples):\n\n position_m, _ = self._sample(\n position_m, trajectory_length, stepsize, lsteps\n )\n\n yield position_m\n\n self.acceptance_rate = self.accepted_proposals / num_samples\n\n\nclass HamiltonianMCDA(HamiltonianMC):\n \"\"\"\n Class for performing sampling in Continuous model\n using Hamiltonian Monte Carlo with dual averaging for\n adaptaion of parameter stepsize.\n\n Parameters\n ----------\n model: An instance pgmpy.models\n Model from which sampling has to be done\n\n grad_log_pdf: A subclass of pgmpy.inference.continuous.GradientLogPDF\n Class to compute the log and gradient log of distribution\n\n simulate_dynamics: A subclass of pgmpy.inference.continuous.BaseSimulateHamiltonianDynamics\n Class to propose future states of position and momentum in time by simulating\n HamiltonianDynamics\n\n delta: float (in between 0 and 1), defaults to 0.65\n The target HMC acceptance probability\n\n Example\n -------\n >>> from pgmpy.sampling import HamiltonianMCDA as HMCda, LeapFrog, GradLogPDFGaussian as GLPG\n >>> from pgmpy.factors.continuous import GaussianDistribution as JGD\n >>> import numpy as np\n >>> mean = np.array([1, 2, 3])\n >>> covariance = np.array([[2, 0.4, 0.5], [0.4, 3, 0.6], [0.5, 0.6, 4]])\n >>> model = JGD(['x', 'y', 'z'], mean, covariance)\n >>> sampler = HMCda(model=model, grad_log_pdf=GLPG)\n >>> samples = sampler.sample(np.array([0, 0, 0]), num_adapt=10000, num_samples = 10000, trajectory_length=7,\n ... return_type='recarray')\n >>> samples_array = np.array([samples[var_name] for var_name in model.variables])\n >>> np.cov(samples_array)\n array([[ 1.83023816, 0.40449162, 0.51200707],\n [ 0.40449162, 2.85863596, 0.76747343],\n [ 0.51200707, 0.76747343, 3.87020982]])\n >>> sampler.acceptance_rate\n 0.9929\n\n References\n -----------\n Matthew D. Hoffman, Andrew Gelman, The No-U-Turn Sampler: Adaptively\n Setting Path Lengths in Hamiltonian Monte Carlo. Journal of\n Machine Learning Research 15 (2014) 1351-1381\n Algorithm 5 : Hamiltonian Monte Carlo with dual averaging\n \"\"\"\n\n def __init__(\n self, model, grad_log_pdf=None, simulate_dynamics=LeapFrog, delta=0.65\n ):\n\n if not isinstance(delta, float) or delta > 1.0 or delta < 0.0:\n raise ValueError(\"delta should be a floating value in between 0 and 1\")\n\n self.delta = delta\n\n super(HamiltonianMCDA, self).__init__(\n model=model, grad_log_pdf=grad_log_pdf, simulate_dynamics=simulate_dynamics\n )\n\n def _adapt_params(\n self, stepsize, stepsize_bar, h_bar, mu, index_i, alpha, n_alpha=1\n ):\n \"\"\"\n Run tha adaptation for stepsize for better proposals of position\n \"\"\"\n gamma = 0.05 # free parameter that controls the amount of shrinkage towards mu\n t0 = 10.0 # free parameter that stabilizes the initial iterations\n kappa = 0.75\n # See equation (6) section 3.2.1 for details\n\n estimate = 1.0 / (index_i + t0)\n h_bar = (1 - estimate) * h_bar + estimate * (self.delta - alpha / n_alpha)\n\n stepsize = np.exp(mu - sqrt(index_i) / gamma * h_bar)\n i_kappa = index_i ** (-kappa)\n stepsize_bar = np.exp(\n i_kappa * np.log(stepsize) + (1 - i_kappa) * np.log(stepsize_bar)\n )\n\n return stepsize, stepsize_bar, h_bar\n\n def sample(\n self,\n initial_pos,\n num_adapt,\n num_samples,\n trajectory_length,\n stepsize=None,\n return_type=\"dataframe\",\n ):\n \"\"\"\n Method to return samples using Hamiltonian Monte Carlo\n\n Parameters\n ----------\n initial_pos: A 1d array like object\n Vector representing values of parameter position, the starting\n state in markov chain.\n\n num_adapt: int\n The number of iterations to run the adaptation of stepsize\n\n num_samples: int\n Number of samples to be generated\n\n trajectory_length: int or float\n Target trajectory length, stepsize * number of steps(L),\n where L is the number of steps taken per HMC iteration,\n and stepsize is step size for splitting time method.\n\n stepsize: float , defaults to None\n The stepsize for proposing new values of position and momentum in simulate_dynamics\n If None, then will be chosen suitably\n\n return_type: string (dataframe | recarray)\n Return type for samples, either of 'dataframe' or 'recarray'.\n Defaults to 'dataframe'\n\n Returns\n -------\n sampled: A pandas.DataFrame or a numpy.recarray object depending upon return_type argument\n\n Examples\n ---------\n >>> from pgmpy.sampling import HamiltonianMCDA as HMCda, GradLogPDFGaussian as GLPG, LeapFrog\n >>> from pgmpy.factors.continuous import GaussianDistribution as JGD\n >>> import numpy as np\n >>> mean = np.array([1, 1])\n >>> covariance = np.array([[1, 0.7], [0.7, 3]])\n >>> model = JGD(['x', 'y'], mean, covariance)\n >>> sampler = HMCda(model=model, grad_log_pdf=GLPG, simulate_dynamics=LeapFrog)\n >>> samples = sampler.sample(np.array([1, 1]), num_adapt=10000, num_samples = 10000,\n ... trajectory_length=2, stepsize=None, return_type='recarray')\n >>> samples_array = np.array([samples[var_name] for var_name in model.variables])\n >>> np.cov(samples_array)\n array([[ 0.98432155, 0.66517394],\n [ 0.66517394, 2.95449533]])\n\n \"\"\"\n\n self.accepted_proposals = 1.0\n\n initial_pos = _check_1d_array_object(initial_pos, \"initial_pos\")\n _check_length_equal(\n initial_pos, self.model.variables, \"initial_pos\", \"model.variables\"\n )\n\n if stepsize is None:\n stepsize = self._find_reasonable_stepsize(initial_pos)\n\n if num_adapt <= 1: # Return samples genrated using Simple HMC algorithm\n return HamiltonianMC.sample(\n self, initial_pos, num_samples, trajectory_length, stepsize\n )\n\n # stepsize is epsilon\n # freely chosen point, after each iteration xt(/position) is shrunk towards it\n mu = np.log(10.0 * stepsize)\n # log(10 * stepsize) large values to save computation\n # stepsize_bar is epsilon_bar\n stepsize_bar = 1.0\n h_bar = 0.0\n # See equation (6) section 3.2.1 for details\n\n types = [(var_name, \"float\") for var_name in self.model.variables]\n samples = np.zeros(num_samples, dtype=types).view(np.recarray)\n samples[0] = tuple(initial_pos)\n position_m = initial_pos\n\n for i in tqdm(range(1, num_samples)):\n\n # Genrating sample\n position_m, alpha = self._sample(position_m, trajectory_length, stepsize)\n samples[i] = tuple(position_m)\n\n # Adaptation of stepsize till num_adapt iterations\n if i <= num_adapt:\n stepsize, stepsize_bar, h_bar = self._adapt_params(\n stepsize, stepsize_bar, h_bar, mu, i, alpha\n )\n else:\n stepsize = stepsize_bar\n\n self.acceptance_rate = self.accepted_proposals / num_samples\n\n return _return_samples(return_type, samples)\n\n def generate_sample(\n self, initial_pos, num_adapt, num_samples, trajectory_length, stepsize=None\n ):\n \"\"\"\n Method returns a generator type object whose each iteration yields a sample\n using Hamiltonian Monte Carlo\n\n Parameters\n ----------\n initial_pos: A 1d array like object\n Vector representing values of parameter position, the starting\n state in markov chain.\n\n num_adapt: int\n The number of iterations to run the adaptation of stepsize\n\n num_samples: int\n Number of samples to be generated\n\n trajectory_length: int or float\n Target trajectory length, stepsize * number of steps(L),\n where L is the number of steps taken to propose new values of position and momentum\n per HMC iteration and stepsize is step size.\n\n stepsize: float , defaults to None\n The stepsize for proposing new values of position and momentum in simulate_dynamics\n If None, then will be chosen suitably\n\n Returns\n -------\n genrator: yielding a numpy.array type object for a sample\n\n Examples\n --------\n >>> from pgmpy.sampling import HamiltonianMCDA as HMCda, GradLogPDFGaussian as GLPG, LeapFrog\n >>> from pgmpy.factors.continuous import GaussianDistribution as JGD\n >>> import numpy as np\n >>> mean = np.array([1, 1])\n >>> covariance = np.array([[1, 0.7], [0.7, 3]])\n >>> model = JGD(['x', 'y'], mean, covariance)\n >>> sampler = HMCda(model=model, grad_log_pdf=GLPG, simulate_dynamics=LeapFrog)\n >>> gen_samples = sampler.generate_sample(np.array([1, 1]), num_adapt=10000,\n ... num_samples = 10000, trajectory_length=2, stepsize=None)\n >>> samples_array = np.array([sample for sample in gen_samples])\n >>> np.cov(samples_array.T)\n array([[ 0.98432155, 0.69517394],\n [ 0.69517394, 2.95449533]])\n \"\"\"\n self.accepted_proposals = 0\n initial_pos = _check_1d_array_object(initial_pos, \"initial_pos\")\n _check_length_equal(\n initial_pos, self.model.variables, \"initial_pos\", \"model.variables\"\n )\n\n if stepsize is None:\n stepsize = self._find_reasonable_stepsize(initial_pos)\n\n if num_adapt <= 1: # return sample generated using Simple HMC algorithm\n for sample in HamiltonianMC.generate_sample(\n self, initial_pos, num_samples, trajectory_length, stepsize\n ):\n yield sample\n return\n mu = np.log(10.0 * stepsize)\n\n stepsize_bar = 1.0\n h_bar = 0.0\n\n position_m = initial_pos.copy()\n num_adapt += 1\n\n for i in range(1, num_samples + 1):\n\n position_m, alpha = self._sample(position_m, trajectory_length, stepsize)\n\n if i <= num_adapt:\n stepsize, stepsize_bar, h_bar = self._adapt_params(\n stepsize, stepsize_bar, h_bar, mu, i, alpha\n )\n else:\n stepsize = stepsize_bar\n\n yield position_m\n\n self.acceptance_rate = self.accepted_proposals / num_samples\n"
] |
[
[
"numpy.testing.assert_almost_equal",
"numpy.array",
"numpy.testing.assert_array_equal"
],
[
"numpy.dot",
"numpy.random.rand",
"numpy.log",
"numpy.zeros",
"numpy.exp"
]
] |
inonchiu/PyMaG
|
[
"ca6146cd354fd35be1eb21669bf505ff1acd3cb5"
] |
[
"pymag/utils/matching.py"
] |
[
"#!/usr/bin/env python\n\n##################################\n#\n# Utils for PyMag\n#\n##################################\n\nimport numpy as np\nfrom math import *\n\ntry:\n from scipy.spatial import cKDTree as KDT\nexcept ImportError:\n from scipy.spatial import KDTree as KDT\n\n\n\n# ---\n# matching unique id\n# ---\ndef IdMatch(id1, id2, return_indices = True):\n \"\"\"\n Unique ID matching in two arrays. The base (reference) array is id1, and the given array is id2. We want to find what the counterparts of id2 are in id1.\n This utilizes numpp function only.\n \"\"\"\n # sanitize\n id1 = np.array(id1, ndmin = 1)\n id2 = np.array(id2, ndmin = 1)\n # find the common id\n common_ids = list(set(id1).intersection(id2))\n # Return the index in id1\n if return_indices:\n return np.nonzero(np.in1d(id1, common_ids))[0]\n else:\n return np.in1d(id1, common_ids)\n\n# ---\n# matching\n# ---\ndef CartMatch(coord1, coord2, tol = None, nnearest=1):\n \"\"\"\n Cartesian Coordinate mathcing\n \"\"\"\n # sanitize\n coord1 = np.array(coord1, ndmin = 1)\n coord2 = np.array(coord2, ndmin = 1)\n\n # check the dimensions of the coordinate\n npairs1 = len( coord1 )\n ndim1 = 1 if len( np.shape(coord1) ) == 1 else \\\n np.shape(coord1)[1]\n npairs2 = len( coord2 )\n ndim2 = 1 if len( np.shape(coord2) ) == 1 else \\\n np.shape(coord2)[1]\n\n # check whether the coord1 and coord2 have the same shape\n if ndim1 != ndim2:\n raise RuntimeError(\"The dims of coord1/2 are not the same.\")\n else:\n ndim = ndim1\n\n # make proper arrays if they are 1d arrays\n if ndim == 1:\n coord1 = np.array([ coord1, np.zeros(len(coord1)) ]).T\n coord2 = np.array([ coord2, np.zeros(len(coord2)) ]).T\n\n # kdtree the coord2\n kdt = KDT(coord2)\n if nnearest == 1:\n idxs2 = kdt.query(coord1)[1]\n elif nnearest > 1:\n idxs2 = kdt.query(coord1, nnearest)[1][:, -1]\n else:\n raise ValueError('invalid nnearest ' + str(nnearest))\n\n # distance - warning: this could be over float if the precision is not enough, we assume that case is beyond the distance of interest...\n ds = np.sqrt( np.sum( (coord1 - coord2[idxs2])**2, axis = 1) )\n\n # index of coord1 \n idxs1 = np.arange(npairs1)\n\n # distance filtering\n if tol is not None:\n msk = ds < tol\n idxs1 = idxs1[msk]\n idxs2 = idxs2[msk]\n ds = ds[msk]\n\n return idxs1, idxs2, ds\n\n\n\n\n##############\n#\n# Testing\n#\n##############\n\nif __name__ == \"__main__\":\n coord1 = range(0,1000)\n coord2 = np.random.random_integers(0,1000,100)\n\n CartMatch(coord1 = coord1, coord2 = coord2, tol = None, nnearest=1)\n"
] |
[
[
"numpy.array",
"numpy.random.random_integers",
"numpy.sum",
"numpy.shape",
"scipy.spatial.KDTree",
"numpy.arange",
"numpy.in1d"
]
] |
LSSTDESC/firecrown
|
[
"646c15809b48a528a833d2bef3b180b91c3af189"
] |
[
"firecrown/ccl/sources/sources.py"
] |
[
"import numpy as np\nfrom scipy.interpolate import Akima1DInterpolator\n\nimport pyccl as ccl\n\nfrom ..core import Source\nfrom ..systematics import IdentityFunctionMOR, TopHatSelectionFunction\n\n\n__all__ = ['WLSource', 'NumberCountsSource', 'ClusterSource', 'CMBLSource']\n\n\nclass WLSource(Source):\n \"\"\"A CCL weak lensing Source.\n\n Parameters\n ----------\n sacc_tracer : str\n The name of the tracer in the SACC file.\n ia_bias : str, optional\n The parameter for the intrinsic alignment amplitude.\n scale : float, optional\n The default scale for this source. Usually the default of 1.0 is\n correct.\n systematics : list of str, optional\n A list of the source-level systematics to apply to the source. The\n default of `None` implies no systematics.\n\n Attributes\n ----------\n z_orig : np.ndarray, shape (n_z,)\n The original redshifts for the photo-z distribution before any\n systematics are applied. Set after the call to `read`.\n dndz_orig : np.ndarray, shape (n_z,)\n The photo-z distribution amplitudes before any systematics are applied.\n Set after the call to `read`.\n dndz_interp : Akima1DInterpolator\n A spline interpolation of the initial photo-z distribution.\n z_ : np.ndarray, shape (n_z,)\n The array of redshifts for the photo-z distribution. Set after a call\n to `render`.\n dndz_ : np.ndarray, shape (n_z,)\n The photo-z distribution amplitudes. Set after a call to `render`.\n ia_bias_ : np.ndarray, shape (n_z,)\n The intrinsic alignment amplitude as a function of redshift. Set after\n a call to `render`. Only present in `is_bias` was non-None when the\n object was made.\n scale_ : float\n The overall scale associated with the source. Set after a call to\n `render`.\n tracer_ : `pyccl.WeakLensingTracer`\n The CCL tracer associated with this source. Set after a call to\n `render`.\n\n Methods\n -------\n render : apply systematics to this source and build the\n `pyccl.WeakLensingTracer`\n \"\"\"\n def __init__(\n self, *, sacc_tracer, ia_bias=None, scale=1.0, systematics=None):\n self.sacc_tracer = sacc_tracer\n self.ia_bias = ia_bias\n self.systematics = systematics or []\n self.scale = scale\n\n def read(self, sacc_data):\n \"\"\"Read the data for this source from the SACC file.\n\n Parameters\n ----------\n sacc_data : sacc.Sacc\n The data in the sacc format.\n \"\"\"\n tracer = sacc_data.get_tracer(self.sacc_tracer)\n z = getattr(tracer, 'z').copy().flatten()\n nz = getattr(tracer, 'nz').copy().flatten()\n inds = np.argsort(z)\n z = z[inds]\n nz = nz[inds]\n self.z_orig = z\n self.dndz_orig = nz\n self.dndz_interp = Akima1DInterpolator(self.z_orig, self.dndz_orig)\n\n def render(self, cosmo, params, systematics=None):\n \"\"\"\n Render a source by applying systematics.\n\n Parameters\n ----------\n cosmo : pyccl.Cosmology\n A pyccl.Cosmology object.\n params : dict\n A dictionary mapping parameter names to their current values.\n systematics : dict\n A dictionary mapping systematic names to their objects. The\n default of `None` corresponds to no systematics.\n \"\"\"\n systematics = systematics or {}\n\n self.z_ = self.z_orig.copy()\n self.dndz_ = self.dndz_orig.copy()\n self.scale_ = self.scale\n if self.ia_bias is not None:\n self.ia_bias_ = np.ones_like(self.z_) * params[self.ia_bias]\n\n for systematic in self.systematics:\n systematics[systematic].apply(cosmo, params, self)\n\n if self.ia_bias is not None:\n tracer = ccl.WeakLensingTracer(\n cosmo,\n dndz=(self.z_, self.dndz_),\n ia_bias=(self.z_, self.ia_bias_))\n else:\n tracer = ccl.WeakLensingTracer(\n cosmo,\n dndz=(self.z_, self.dndz_))\n self.tracer_ = tracer\n\n\nclass NumberCountsSource(Source):\n \"\"\"A CCL number counts source.\n\n Parameters\n ----------\n sacc_tracer : str\n The name of the source in the SACC file.\n bias : str\n The parameter for the bias of the source.\n has_rsd : bool, optional\n If `True`, the source has RSD terms.\n mag_bias : str, optional\n The parameter for the magnification bias of the source.\n scale : float, optional\n The default scale for this source. Usually the default of 1.0 is\n correct.\n systematics : list of str, optional\n A list of the source-level systematics to apply to the source. The\n default of `None` implies no systematics.\n\n Attributes\n ----------\n z_orig : np.ndarray, shape (n_z,)\n The original redshifts for the photo-z distribution before any\n systematics are applied. Set after the call to `read`.\n dndz_orig : np.ndarray, shape (n_z,)\n The photo-z distribution amplitudes before any systematics are applied.\n Set after the call to `read`.\n dndz_interp : Akima1DInterpolator\n A spline interpolation of the initial photo-z distribution.\n z_ : np.ndarray, shape (n_z,)\n The array of redshifts for the photo-z distribution. Set after a call\n to `render`.\n dndz_ : np.ndarray, shape (n_z,)\n The photo-z distribution amplitudes. Set after a call to `render`.\n bias_ : np.ndarray, shape (n_z,)\n The bias of the source. Set after a call to `render`.\n mag_bias_ : np.ndarray, shape (n_z,)\n The magnification bias of the source. Only used if `has_magnification`\n is `True` and only set after a call to `render`.\n scale_ : float\n The overall scale associated with the source. Set after a call to\n `render`.\n tracer_ : `pyccl.NumberCountsTracer`\n The CCL tracer associated with this source. Set after a call to\n `render`.\n\n Methods\n -------\n render : apply systematics to this source and build the\n `pyccl.NumberCountsTracer`\n \"\"\"\n def __init__(\n self, *, sacc_tracer, bias, has_rsd=False,\n mag_bias=None, scale=1.0, systematics=None):\n self.sacc_tracer = sacc_tracer\n self.bias = bias\n self.has_rsd = has_rsd\n self.mag_bias = mag_bias\n self.systematics = systematics or []\n self.scale = scale\n\n def read(self, sacc_data):\n \"\"\"Read the data for this source from the SACC file.\n\n Parameters\n ----------\n sacc_data : sacc.Sacc\n The data in the sacc format.\n \"\"\"\n tracer = sacc_data.get_tracer(self.sacc_tracer)\n z = getattr(tracer, 'z').copy().flatten()\n nz = getattr(tracer, 'nz').copy().flatten()\n inds = np.argsort(z)\n z = z[inds]\n nz = nz[inds]\n self.z_orig = z\n self.dndz_orig = nz\n self.dndz_interp = Akima1DInterpolator(self.z_orig, self.dndz_orig)\n\n def render(self, cosmo, params, systematics=None):\n \"\"\"\n Render a source by applying systematics.\n\n Parameters\n ----------\n cosmo : pyccl.Cosmology\n A pyccl.Cosmology object.\n params : dict\n A dictionary mapping parameter names to their current values.\n systematics : dict\n A dictionary mapping systematic names to their objects. The\n default of `None` corresponds to no systematics.\n \"\"\"\n systematics = systematics or {}\n\n self.z_ = self.z_orig.copy()\n self.dndz_ = self.dndz_orig.copy()\n self.scale_ = self.scale\n self.bias_ = np.ones_like(self.z_) * params[self.bias]\n\n if self.mag_bias is not None:\n self.mag_bias_ = np.ones_like(self.z_) * params[self.mag_bias]\n\n for systematic in self.systematics:\n systematics[systematic].apply(cosmo, params, self)\n\n if self.mag_bias is not None:\n tracer = ccl.NumberCountsTracer(\n cosmo,\n has_rsd=self.has_rsd,\n dndz=(self.z_, self.dndz_),\n bias=(self.z_, self.bias_),\n mag_bias=(self.z_, self.mag_bias_))\n else:\n tracer = ccl.NumberCountsTracer(\n cosmo,\n has_rsd=self.has_rsd,\n dndz=(self.z_, self.dndz_),\n bias=(self.z_, self.bias_))\n self.tracer_ = tracer\n\n\nclass ClusterSource(Source):\n \"\"\"A galaxy cluster source.\n\n Parameters\n ----------\n sacc_tracer : str\n The name of the source in the SACC file.\n systematics : list of str, optional\n A list of the source-level systematics to apply to the source. The\n default of `None` implies no systematics.\n\n Attributes\n ----------\n z_orig : np.ndarray, shape (n_z,)\n The original redshifts for the photo-z distribution before any\n systematics are applied. Set after the call to `read`.\n dndz_orig : np.ndarray, shape (n_z,)\n The photo-z distribution amplitudes before any systematics are applied.\n Set after the call to `read`.\n dndz_interp : Akima1DInterpolator\n A spline interpolation of the initial photo-z distribution.\n z_ : np.ndarray, shape (n_z,)\n The array of redshifts for the photo-z distribution. Set after a call\n to `render`.\n dndz_ : np.ndarray, shape (n_z,)\n The photo-z distribution amplitudes. Set after a call to `render`.\n dndz_interp_ : Akima1DInterpolator\n A spline interpolation of the final photo-z distribution. Set after a\n call to `render`.\n lnlam_min_orig : float\n The minimum lnlambda value read from the SACC file. Set after the call to\n `read`.\n lnlam_max_orig : float\n The maximum lnlambda value read from the SACC file. Set after the call to\n `read`.\n lnlam_min_ : float\n The minimum lnlambda value. Set after a call to `render`.\n lnlam_max_ : float\n The maximum lnlambda value. Set after a call to `render`.\n mor_ : callable\n The mass-observable relationship. This is a callable with signature\n `mor(lnmass, a)` that returns a value of the \"observable\" denoted as\n `lam` in the code. Set after a call to `render`.\n A default of the identity function is applied. Add\n systematics to the source to support more complicated models.\n inv_mor_ : callable\n The inverse of the mass-observable relationship. This is a callable with\n signature `inv_mor(lnlam, a)` that returns the `lnmass` for a given\n `lam` and scale factor `a`. Set after a call to `render`.\n A default of the identity function is applied. Add\n systematics to the source to support more complicated models.\n selfunc_ : callable\n A function with signature `selfunc(lnmass, a)` that\n gives the cluster selection function in mass and scale factor\n `\\\\int_{lnlam_min_}^{lnlam_max_} p(lnlam|lnmass, a) dlnlam`.\n Set after a call to `render`. The default is to assume `p(lnlam|lnmass, a)`\n is a Delta function `\\\\delta(lnmass - lnlam)` so that the selection function\n is a top-hat from `lnlam_min_` to `lnlam_max_` (which are in now in units\n of mass). Add systematics to the source when rendering in order to produce\n more complicated models.\n area_sr_orig : float\n The original area in steradians of the cluster sample.\n area_sr_ : float\n The (effective) area in steradians of the cluster sample.\n scale_ : float\n The overall scale associated with the source. Set after a call to\n `render`. Not currently used for anything.\n\n Methods\n -------\n render : apply systematics to this source, build the\n `pyccl.NumberCountsTracer`, and compute the linear bias\n \"\"\"\n def __init__(self, *, sacc_tracer, systematics=None):\n self.sacc_tracer = sacc_tracer\n self.systematics = systematics or []\n self.scale = 1.0\n\n def read(self, sacc_data):\n \"\"\"Read the data for this source from the SACC file.\n\n Parameters\n ----------\n sacc_data : sacc.Sacc\n The data in the sacc format.\n \"\"\"\n tracer = sacc_data.get_tracer(self.sacc_tracer)\n z = getattr(tracer, 'z').copy().flatten()\n nz = getattr(tracer, 'nz').copy().flatten()\n inds = np.argsort(z)\n z = z[inds]\n nz = nz[inds]\n self.z_orig = z\n self.dndz_orig = nz\n self.dndz_interp = Akima1DInterpolator(self.z_orig, self.dndz_orig)\n self.lnlam_min_orig = tracer.metadata['lnlam_min']\n self.lnlam_max_orig = tracer.metadata['lnlam_max']\n self.area_sr_orig = tracer.metadata['area_sd'] * (np.pi/180.0)**2\n\n def render(self, cosmo, params, systematics=None):\n \"\"\"\n Render a source by applying systematics.\n\n Parameters\n ----------\n cosmo : pyccl.Cosmology\n A pyccl.Cosmology object.\n params : dict\n A dictionary mapping parameter names to their current values.\n systematics : dict\n A dictionary mapping systematic names to their objects. The\n default of `None` corresponds to no systematics.\n \"\"\"\n systematics = systematics or {}\n\n self.z_ = self.z_orig.copy()\n self.dndz_ = self.dndz_orig.copy()\n self.scale_ = self.scale\n self.lnlam_min_ = self.lnlam_min_orig\n self.lnlam_max_ = self.lnlam_max_orig\n self.area_sr_ = self.area_sr_orig\n\n # set fiducial MOR and selection function systematics\n mor_sys = IdentityFunctionMOR()\n mor_sys.apply(cosmo, params, self)\n sel_sys = TopHatSelectionFunction()\n sel_sys.apply(cosmo, params, self)\n\n for systematic in self.systematics:\n systematics[systematic].apply(cosmo, params, self)\n\n self.dndz_interp_ = Akima1DInterpolator(self.z_, self.dndz_)\n\n\nclass CMBLSource(Source):\n \"\"\"A CCL CMB Lensing Source.\n\n Parameters\n ----------\n sacc_tracer : str\n The name of the tracer in the SACC file.\n scale : float, optional\n The default scale for this source. Usually the default of 1.0 is\n correct.\n systematics : list of str, optional\n A list of the source-level systematics to apply to the source. The\n default of `None` implies no systematics.\n\n Attributes\n ----------\n scale_ : float\n The overall scale associated with the source. Set after a call to\n `render`.\n tracer_ : `pyccl.CMBLensingTracer`\n The CCL tracer associated with this source. Set after a call to\n `render`.\n\n Methods\n -------\n render : apply systematics to this source and build the\n `pyccl.CMBLSource`\n \"\"\"\n def __init__(self, *, sacc_tracer, scale=1.0, systematics=None):\n self.sacc_tracer = sacc_tracer\n self.scale = scale\n self.systematics = systematics or []\n\n def read(self, sacc_data):\n \"\"\"\n Read the data for this source from the SACC file.\n\n Parameters\n ----------\n sacc_data : sacc.Sacc\n The data in the sacc format.\n \"\"\"\n pass\n\n def render(self, cosmo, params, systematics=None):\n \"\"\"\n Render a source by applying systematics.\n\n Parameters\n ----------\n cosmo : pyccl.Cosmology\n A pyccl.Cosmology object.\n params : dict\n A dictionary mapping parameter names to their current values.\n systematics : dict\n A dictionary mapping systematic names to their objects. The\n default of `None` corresponds to no systematics.\n \"\"\"\n systematics = systematics or {}\n\n self.scale_ = self.scale\n\n for systematic in self.systematics:\n systematics[systematic].apply(cosmo, params, self)\n\n tracer = ccl.CMBLensingTracer(cosmo, 1100.)\n self.tracer_ = tracer\n"
] |
[
[
"scipy.interpolate.Akima1DInterpolator",
"numpy.ones_like",
"numpy.argsort"
]
] |
mfrasquet/valenbisi
|
[
"1af47664bef31df7469645e83f32fd007b2f23d8"
] |
[
"plot1.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 9 19:53:39 2019\n\n@author: miguel\n\"\"\"\nimport pandas as pd\nfrom datetime import datetime\nimport matplotlib.pyplot as plt \n\n\ndata=pd.read_csv('bikes.csv', sep='\\t',index_col=False)\n\n\nweek_day=[]\nfor i in range(0,len(data)):\n week_day.append(datetime.strptime(data['date'][i],'%Y-%m-%d %H:%M:%S.%f').weekday())\n\ndata['week_day']=week_day \n\n# 0-> Monday 1->Tuesday ...\nfiltered_df = data.loc[data.week_day.eq(1)].reset_index()\n\n\nfig, ax = plt.subplots(figsize=(7,4))\nfor j in range(0,int(len(filtered_df)/72)):\n date_plot=[]\n bikes_plot=[] \n for i in range(0,72):\n date_plot.append(i)\n bikes_plot.append(filtered_df['bikesHome'][i+j*72])\n plt.scatter(date_plot, bikes_plot) \n\n#filtered_df.plot(x='date', y='bikesHome', lw=0, marker='o', figsize=(8,4)) \n\n#filtered_df['date'] = filtered_df.date.astype(np.int64)\n\n\n#plt.scatter(filtered_df['date'], filtered_df['bikesHome'])\n#filtered_df.plot(x=filtered_df['date'], y=filtered_df['bikesHome'], kind='scatter', ax=ax)\n#ax.set_xticklabels([datetime.fromtimestamp(ts / 1e9).strftime('%H:%M:%S') for ts in ax.get_xticks()])\n#ax.set_yticklabels([datetime.fromtimestamp(ts / 1e9).strftime('%H:%M:%S') for ts in ax.get_yticks()])\n#plt.show()\n#\n#data.plot(x='date', y='b', lw=0, marker='o', figsize=(8,4)) "
] |
[
[
"matplotlib.pyplot.scatter",
"pandas.read_csv",
"matplotlib.pyplot.subplots"
]
] |
BigDataArchitecture/Assignment1
|
[
"98c02762c4927cef26a17e55533e94b34671c519"
] |
[
"notebooks/eie-sevir/sevir/utils_pytorch.py"
] |
[
"import os\nimport numpy as np\nimport pandas as pd\nimport h5py\n\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\n\nos.environ[\"HDF5_USE_FILE_LOCKING\"] = 'FALSE'\nTYPES = ['vis', 'ir069', 'ir107', 'vil', 'lght']\nDEFAULT_CATALOG = '/home/gridsan/groups/EarthIntelligence/datasets/SEVIR/CATALOG.csv'\nDEFAULT_DATA_HOME = '/home/gridsan/groups/EarthIntelligence/datasets/SEVIR/data/'\nFRAME_TIMES = np.arange(-120.0, 120.0, 5) * 60\n\n# TODO : MANY!\n\n# Example function of how to create pytorch dataloader with sevir dataset\ndef get_sevir_loader(self,\n batch_size=3,\n x_img_types=['vil'],\n y_img_types=None,\n catalog=DEFAULT_CATALOG,\n start_date=None,\n end_date=None,\n datetime_filter=None,\n catalog_filter=None,\n unwrap_time=False,\n sevir_data_home=DEFAULT_DATA_HOME,\n shuffle=False,\n pin_memory=True,\n output_type=np.float32,\n normalize_x=None,\n normalize_y=None,\n num_workers=0,\n ):\n dataset = SEVIR(x_img_types,\n y_img_types,\n catalog,\n start_date,\n end_date,\n datetime_filter,\n catalog_filter,\n unwrap_time,\n sevir_data_home,\n output_type,\n normalize_x,\n normalize_y)\n return DataLoader(dataset,\n batch_size=batch_size,\n shuffle=shuffle,\n pin_memory=pin_memory,\n num_workers=num_workers)\n\n\nclass SEVIR(Dataset):\n \"\"\"\n Sequence class for generating batches from SEVIR\n\n Parameters\n ----------\n catalog str or pd.DataFrame\n name of SEVIR catalog file to be read in, or an already read in and processed catalog\n x_img_types list\n List of image types to be used as model inputs. For types, run SEVIRSequence.get_types()\n y_img_types list or None\n List of image types to be used as model targets (if None, __getitem__ returns only x_img_types )\n sevir_data_home str\n Directory path to SEVIR data\n catalog str\n Name of SEVIR catalog CSV file.\n start_date datetime\n Start time of SEVIR samples to generate\n end_date datetime\n End time of SEVIR samples to generate\n datetime_filter function\n Mask function applied to time_utc column of catalog (return true to keep the row).\n Pass function of the form lambda t : COND(t)\n Example: lambda t: np.logical_and(t.dt.hour>=13,t.dt.hour<=21) # Generate only day-time events\n catalog_filter function\n Mask function applied to entire catalog dataframe (return true to keep row).\n Pass function of the form lambda catalog: COND(catalog)\n Example: lambda c: [s[0]=='S' for s in c.id] # Generate only the 'S' events\n unwrap_time bool\n If True, single images are returned instead of image sequences\n output_type np.dtype\n dtype of generated tensors\n normalize_x list of tuple\n list the same size as x_img_types containing tuples (scale,offset) used to\n normalize data via X --> (X-offset)*scale. If None, no scaling is done\n normalize_y list of tuple\n list the same size as y_img_types containing tuples (scale,offset) used to\n normalize data via X --> (X-offset)*scale\n\n Returns\n -------\n SEVIRSequence generator\n\n Examples\n --------\n\n # Get just Radar image sequences\n vil_seq = SEVIRSequence(x_img_types=['vil'],batch_size=16)\n X = vil_seq.__getitem__(1234) # returns list the same size as x_img_types passed to constructor\n\n # Get ir satellite+lightning as X, radar for Y\n vil_ir_lght_seq = SEVIRSequence(x_img_types=['ir107','lght'],y_img_types=['vil'],batch_size=4)\n X,Y = vil_ir_lght_seq.__getitem__(420) # X,Y are lists same length as x_img_types and y_img_types\n\n # Get single images of VIL\n vil_imgs = SEVIRSequence(x_img_types=['vil'], batch_size=256, unwrap_time=True, shuffle=True)\n\n # Filter out some times\n vis_seq = SEVIRSequence(x_img_types=['vis'],batch_size=32,unwrap_time=True,\n start_date=datetime.datetime(2018,1,1),\n end_date=datetime.datetime(2019,1,1),\n datetime_filter=lambda t: np.logical_and(t.dt.hour>=13,t.dt.hour<=21))\n\n \"\"\"\n\n def __init__(self,\n x_img_types=['vil'],\n y_img_types=None,\n catalog=DEFAULT_CATALOG,\n start_date=None,\n end_date=None,\n datetime_filter=None,\n catalog_filter=None,\n unwrap_time=False,\n sevir_data_home=DEFAULT_DATA_HOME,\n output_type=np.float32,\n normalize_x=None,\n normalize_y=None\n ):\n self._samples = None\n self._hdf_files = {}\n self.x_img_types = x_img_types\n self.y_img_types = y_img_types\n if isinstance(catalog, (str,)):\n self.catalog = pd.read_csv(catalog, parse_dates=['time_utc'], low_memory=False)\n else:\n self.catalog = catalog\n\n self.datetime_filter = datetime_filter\n self.catalog_filter = catalog_filter\n self.start_date = start_date\n self.end_date = end_date\n self.unwrap_time = unwrap_time\n self.sevir_data_home = sevir_data_home\n self.output_type = output_type\n self.normalize_x = normalize_x\n self.normalize_y = normalize_y\n if normalize_x:\n assert (len(normalize_x) == len(x_img_types))\n if normalize_y:\n assert (len(normalize_y) == len(y_img_types))\n\n if self.start_date:\n self.catalog = self.catalog[self.catalog.time_utc > self.start_date]\n if self.end_date:\n self.catalog = self.catalog[self.catalog.time_utc <= self.end_date]\n if self.datetime_filter:\n self.catalog = self.catalog[self.datetime_filter(self.catalog.time_utc)]\n\n if self.catalog_filter:\n self.catalog = self.catalog[self.catalog_filter(self.catalog)]\n\n self._compute_samples()\n self._open_files()\n\n def _compute_samples(self):\n \"\"\"\n Computes the list of samples in catalog to be used. This sets\n self._samples\n\n \"\"\"\n # locate all events containing colocated x_img_types and y_img_types\n imgt = self.x_img_types\n if self.y_img_types:\n imgt = list(set(imgt + self.y_img_types)) # remove duplicates\n imgts = set(imgt)\n filtcat = self.catalog[np.logical_or.reduce([self.catalog.img_type == i for i in imgt])]\n # remove rows missing one or more requested img_types\n filtcat = filtcat.groupby('id').filter(lambda x: imgts.issubset(set(x['img_type'])))\n # If there are repeated IDs, remove them (this is a bug in SEVIR)\n filtcat = filtcat.groupby('id').filter(lambda x: x.shape[0] == len(imgt))\n self._samples = filtcat.groupby('id').apply(lambda df: df_to_series(df, imgt, unwrap_time=self.unwrap_time))\n\n def _open_files(self):\n \"\"\"\n Opens HDF files\n \"\"\"\n imgt = self.x_img_types\n if self.y_img_types:\n imgt = list(set(imgt + self.y_img_types)) # remove duplicates\n hdf_filenames = []\n for t in imgt:\n hdf_filenames += list(np.unique(self._samples[f'{t}_filename'].values))\n self._hdf_files = {}\n for f in hdf_filenames:\n print('Opening HDF5 file for reading', f)\n self._hdf_files[f] = h5py.File(self.sevir_data_home + '/' + f, 'r')\n\n def __getitem__(self, idx):\n \"\"\"\n batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size]\n batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size]\n\n return np.array([\n resize(imread(file_name), (200, 200))\n for file_name in batch_x]), np.array(batch_y)\n \"\"\"\n data = {}\n data = read_data(self._samples.iloc[idx], data, self._hdf_files, self.unwrap_time)\n X = [data[t].astype(self.output_type) for t in self.x_img_types]\n if self.normalize_x:\n X = [normalize(X[k], s[0], s[1]) for k, s in enumerate(self.normalize_x)]\n if self.y_img_types is not None:\n Y = [data[t].astype(self.output_type) for t in self.y_img_types]\n if self.normalize_y:\n Y = [normalize(Y[k], s[0], s[1]) for k, s in enumerate(self.normalize_y)]\n return X, Y\n else:\n return X\n\n\ndef read_data(row, data, hdf_files, unwrap_time=False):\n \"\"\"\n Reads data from data object\n :param row: series with fields IMGTYPE_filename IMGTYPE_index, IMGTYPE_time_index\n :param data: data object\n :param hdf_files: hdf_file handles to read from\n :param unwrap_time: boolean for unwrapping time field\n :return:\n \"\"\"\n image_types = np.unique([x.split('_')[0] for x in list(row.keys())])\n for t in image_types:\n f_name = row[f'{t}_filename']\n idx = row[f'{t}_index']\n if unwrap_time:\n time_idx = row[f'{t}_time_index']\n t_slice = slice(time_idx, time_idx + 1)\n else:\n t_slice = slice(0, None)\n # Need to bin lght counts into grid\n if t == 'lght':\n lightning_data = hdf_files[f_name][idx][:]\n data_i = lightning_to_hist(lightning_data, t_slice)\n else:\n data_i = hdf_files[f_name][t][idx:idx + 1, :, :, t_slice]\n data[t] = np.concatenate((data[t], data_i), axis=0) if (t in data) else data_i\n return data\n\n\ndef lightning_to_hist(data, t_slice=slice(0, None)):\n \"\"\"\n Converts Nx5 lightning data matrix into a XYT histogram\n :param data: lightning event data\n :param t_slice: temporal dimension\n :return: XYT histogram of lightning data\n \"\"\"\n\n out_size = (48, 48, len(FRAME_TIMES)) if t_slice.stop is None else (48, 48, 1)\n if data.shape[0] == 0:\n return np.zeros((1,) + out_size, dtype=np.float32)\n\n # filter out points outside the grid\n x, y = data[:, 3], data[:, 4]\n m = np.logical_and.reduce([x >= 0, x < out_size[0], y >= 0, y < out_size[1]])\n data = data[m, :]\n if data.shape[0] == 0:\n return np.zeros((1,) + out_size, dtype=np.float32)\n\n # Filter/separate times\n t = data[:, 0]\n if t_slice.stop is not None: # select only one time bin\n if t_slice.stop > 0:\n tm = np.logical_and(t >= FRAME_TIMES[t_slice.stop - 1],\n t < FRAME_TIMES[t_slice.stop])\n else: # special case: frame 0 uses lightning from frame 1\n tm = np.logical_and(t >= FRAME_TIMES[0], t < FRAME_TIMES[1])\n data = data[tm, :]\n z = np.zeros(data.shape[0], dtype=np.int64)\n else: # compute z coordinate based on bin location times\n z = np.digitize(t, FRAME_TIMES) - 1\n z[z == -1] = 0 # special case: frame 0 uses lightning from frame 1\n\n x = data[:, 3].astype(np.int64)\n y = data[:, 4].astype(np.int64)\n\n k = np.ravel_multi_index(np.array([y, x, z]), out_size)\n n = np.bincount(k, minlength=np.prod(out_size))\n return np.reshape(n, out_size).astype(np.float32)[np.newaxis, :]\n\n\ndef normalize(x, scale, offset, reverse=False):\n \"\"\"\n Normalize data or reverse normalization\n :param x: data array\n :param scale: const scaling value\n :param offset: const offset value\n :param reverse: boolean undo normalization\n :return: normalized x array\n \"\"\"\n if reverse:\n return x / scale + offset\n else:\n return (x-offset) * scale\n\n\ndef df_to_series(df, image_types, n_frames=49, unwrap_time=False):\n \"\"\"\n This looks like it takes a data frame and turns it into a sequence like data frame\n :param df: pandas data frame\n :param image_types: image types to extract\n :param n_frames: number of frames to extract\n :param unwrap_time: boolean for whether or not to set time index\n :return: sequence data frame\n \"\"\"\n d = {}\n df = df.set_index('img_type')\n for i in image_types:\n s = df.loc[i]\n idx = s.file_index if i != 'lght' else s.id\n if unwrap_time:\n d.update({f'{i}_filename': [s.file_name] * n_frames,\n f'{i}_index': [idx] * n_frames,\n f'{i}_time_index': range(n_frames)})\n else:\n d.update({f'{i}_filename': [s.file_name],\n f'{i}_index': [idx]})\n return pd.DataFrame(d)\n"
] |
[
[
"numpy.concatenate",
"numpy.array",
"numpy.reshape",
"numpy.zeros",
"pandas.DataFrame",
"numpy.logical_and",
"numpy.digitize",
"numpy.prod",
"numpy.arange",
"torch.utils.data.DataLoader",
"numpy.logical_or.reduce",
"numpy.logical_and.reduce",
"numpy.unique",
"pandas.read_csv"
]
] |
siduojiang/BERTVision
|
[
"01519bea0882fa72e86a1b62f2d0d52d22c26dfc"
] |
[
"code/torch/common/trainers/H5_glue_trainer.py"
] |
[
"# packages\nimport os, sys, datetime\nsys.path.append(\"C:/BERTVision/code/torch\")\nfrom common.evaluators.H5_glue_evaluator import H5_GLUE_Evaluator\nfrom utils.collate import collate_H5_GLUE\nfrom torch.cuda.amp import autocast\nimport torch\nfrom torch.utils.data import DataLoader\nfrom tqdm.auto import tqdm\nfrom tqdm.notebook import trange\nimport numpy as np\n\nclass H5_GLUE_Trainer(object):\n '''\n This class handles the training of 1-epoch tuned QA embeddings from BERT\n\n Parameters\n ----------\n model : object\n A compression model; see compress_utils.py\n\n criterion : loss function\n A loss function\n\n optimizer: object\n A compatible Torch optimizer\n\n processor: object\n A Torch Dataset processor that emits data\n\n scheduler: object\n The learning rate decreases linearly from the initial lr set\n\n args: object\n A argument parser object; see args.py\n\n scaler: object\n A gradient scaler object to use FP16\n\n Operations\n -------\n This trainer:\n (1) Trains the weights\n (2) Generates dev set loss\n (3) Creates start and end logits and collects their original index for scoring\n (4) Writes their results and saves the file as a checkpoint\n\n\n '''\n def __init__(self, model, criterion, optimizer, processor, scheduler, args, scaler, logger):\n # pull in objects\n self.args = args\n self.model = model\n self.criterion = criterion\n self.optimizer = optimizer\n self.processor = processor\n self.scheduler = scheduler\n self.scaler = scaler\n self.logger = logger\n\n # specify training data set\n self.train_examples = processor(type='train', args=self.args)\n\n # create a timestamp for the checkpoints\n timestamp = datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n\n # create a location to save the files\n self.snapshot_path = os.path.join(args.save_path, args.checkpoint, args.model, '%s.pt' % timestamp)\n self.make_path = os.path.join(self.args.save_path, self.args.checkpoint, self.args.model)\n os.makedirs(self.make_path, exist_ok=True)\n\n # determine the number of optimization steps\n self.num_train_optimization_steps = int(\n len(self.train_examples) / args.batch_size) * args.epochs\n\n # create placeholders for model metrics and early stopping if desired\n self.iterations, self.nb_tr_steps, self.tr_loss = 0, 0, 0\n self.best_dev_f1, self.unimproved_iters, self.dev_loss = 0, 0, np.inf\n self.pearson_score = 0\n self.early_stop = False\n\n def train_epoch(self, criterion, train_dataloader):\n # set the model to train\n self.model.train()\n # pull data from data loader\n for step, batch in enumerate(tqdm(train_dataloader, desc=\"Training\")):\n # and sent it to the GPU\n embeddings, labels, indices = (\n batch['embeddings'].to(self.args.device),\n batch['labels'].to(self.args.device),\n batch['idx'].to(self.args.device)\n )\n\n # FP16\n with autocast():\n # forward\n logits = self.model(embeddings)\n\n # get loss\n if self.args.num_labels == 1:\n loss = criterion(logits.view(-1), labels.view(-1))\n else:\n loss = criterion(logits, labels)\n\n # multi-gpu loss\n if self.args.n_gpu > 1:\n raise NotImplementedError\n\n # backward\n self.scaler.scale(loss).backward()\n self.scaler.step(self.optimizer)\n self.scaler.update()\n self.scheduler.step()\n self.optimizer.zero_grad()\n\n # update metrics\n self.tr_loss += loss.item()\n self.nb_tr_steps += 1\n\n # gen. loss\n avg_loss = self.tr_loss / self.nb_tr_steps\n\n # print end of trainig results\n self.logger.info(f\"Training complete! Loss: {avg_loss}\")\n\n def train(self):\n '''\n This function handles the entirety of the training, dev, and scoring.\n '''\n # tell the user general metrics\n self.logger.info(f\"Number of examples: {len(self.train_examples)}\")\n self.logger.info(f\"Batch size: {self.args.batch_size}\")\n self.logger.info(f\"Number of optimization steps: {self.num_train_optimization_steps}\")\n\n # instantiate dataloader\n train_dataloader = DataLoader(self.train_examples,\n batch_size=self.args.batch_size,\n shuffle=True,\n num_workers=self.args.num_workers,\n drop_last=False,\n collate_fn=collate_H5_GLUE)\n # for each epoch\n for epoch in trange(int(self.args.epochs), desc=\"Epoch\"):\n\n # check model\n if any([self.args.model == 'AP_SST',\n self.args.model == 'AP_MSR',\n self.args.model == 'AP_RTE',\n self.args.model == 'AP_QNLI',\n self.args.model == 'AP_QQP',\n self.args.model == 'AP_WNLI'\n ]):\n\n # train\n self.train_epoch(self.criterion, train_dataloader)\n # get metrics\n dev_acc, dev_precision, dev_recall, dev_f1, dev_loss = H5_GLUE_Evaluator(self.model, self.criterion, self.processor, self.args, self.logger).get_loss(type='dev')\n self.dev_acc = dev_acc\n # print validation results\n self.logger.info(\"Epoch {0: d}, Dev/Acc {1: 0.3f}, Dev/Pr. {2: 0.3f}, Dev/Re. {3: 0.3f}, Dev/F1 {4: 0.3f}, Dev/Loss {5: 0.3f}\",\n epoch+1, dev_acc, dev_precision, dev_recall, dev_f1, dev_loss)\n\n # update validation results\n if dev_loss < self.dev_loss:\n self.unimproved_iters = 0\n self.dev_loss = dev_loss\n torch.save(self.model, self.snapshot_path)\n\n else:\n # stop training with early stopping\n self.unimproved_iters += 1\n if self.unimproved_iters >= self.args.patience:\n self.early_stop = True\n self.logger.info(f\"Early Stopping. Epoch: {epoch}, Best Dev Loss: {self.dev_loss}\")\n break\n\n # get dev loss\n elif all([self.args.num_labels > 1, self.args.model == 'AP_MNLI']):\n\n # train\n self.train_epoch(self.criterion, train_dataloader)\n # get metrics\n dev_acc, dev_precision, dev_recall, dev_f1, dev_loss = H5_GLUE_Evaluator(self.model, self.criterion, self.processor, self.args, self.logger).get_loss(type='dev_matched')\n self.dev_acc = dev_acc\n # print validation results\n self.logger.info(\"Epoch {0: d}, Dev/Acc {1: 0.3f}, Dev/Pr. {2: 0.3f}, Dev/Re. {3: 0.3f}, Dev/F1 {4: 0.3f}, Dev/Loss {5: 0.3f}\",\n epoch+1, dev_acc, dev_precision, dev_recall, dev_f1, dev_loss)\n\n # update validation results\n if dev_loss < self.dev_loss:\n self.unimproved_iters = 0\n self.dev_loss = dev_loss\n torch.save(self.model, self.snapshot_path)\n\n else:\n # stop training with early stopping\n self.unimproved_iters += 1\n if self.unimproved_iters >= self.args.patience:\n self.early_stop = True\n self.logger.info(f\"Early Stopping. Epoch: {epoch}, Best Dev Loss: {self.dev_loss}\")\n break\n\n # get metrics\n dev_acc, dev_precision, dev_recall, dev_f1, dev_loss = H5_GLUE_Evaluator(self.model, self.criterion, self.processor, self.args, self.logger).get_loss(type='dev_mismatched')\n self.dev_acc = dev_acc\n # print validation results\n self.logger.info(\"Epoch {0: d}, Dev/Acc {1: 0.3f}, Dev/Pr. {2: 0.3f}, Dev/Re. {3: 0.3f}, Dev/F1 {4: 0.3f}, Dev/Loss {5: 0.3f}\",\n epoch+1, dev_acc, dev_precision, dev_recall, dev_f1, dev_loss)\n\n # update validation results\n if dev_loss < self.dev_loss:\n self.unimproved_iters = 0\n self.dev_loss = dev_loss\n torch.save(self.model, self.snapshot_path)\n\n else:\n # stop training with early stopping\n self.unimproved_iters += 1\n if self.unimproved_iters >= self.args.patience:\n self.early_stop = True\n self.logger.info(f\"Early Stopping. Epoch: {epoch}, Best Dev Loss: {self.dev_loss}\")\n break\n\n elif all([self.args.num_labels == 1 and self.args.model == 'AP_STSB']):\n\n # train\n self.train_epoch(self.criterion, train_dataloader)\n\n # get metrics\n pearson, spearman, dev_loss = H5_GLUE_Evaluator(self.model, self.criterion, self.processor, self.args, self.logger).get_loss(type='dev')\n\n # print validation results\n self.logger.info(\"Epoch {0: d}, Dev/Pearson {1: 0.3f}, Dev/Spearman {2: 0.3f}, Dev/Loss {3: 0.3f}\",\n epoch+1, pearson, spearman, dev_loss)\n\n # update validation results\n if dev_loss < self.dev_loss:\n self.unimproved_iters = 0\n self.dev_loss = dev_loss\n torch.save(self.model, self.snapshot_path)\n\n else:\n # stop training with early stopping\n self.unimproved_iters += 1\n if self.unimproved_iters >= self.args.patience:\n self.early_stop = True\n self.logger.info(f\"Early Stopping. Epoch: {epoch}, Best Dev Loss: {self.dev_loss}\")\n break\n\n elif self.args.model == 'AP_CoLA':\n\n # train\n self.train_epoch(self.criterion, train_dataloader)\n\n # get metrics\n matthews, dev_loss = H5_GLUE_Evaluator(self.model, self.criterion, self.processor, self.args, self.logger).get_loss(type='dev')\n self.dev_acc = matthews\n # print validation results\n self.logger.info(\"Epoch {0: d}, Dev/Matthews {1: 0.3f}, Dev/Loss {2: 0.3f}\",\n epoch+1, matthews, dev_loss)\n\n # update validation results\n if dev_loss < self.dev_loss:\n self.unimproved_iters = 0\n self.dev_loss = dev_loss\n torch.save(self.model, self.snapshot_path)\n\n else:\n # stop training with early stopping\n self.unimproved_iters += 1\n if self.unimproved_iters >= self.args.patience:\n self.early_stop = True\n self.logger.info(f\"Early Stopping. Epoch: {epoch}, Best Dev Loss: {self.dev_loss}\")\n break\n\n#\n"
] |
[
[
"torch.save",
"torch.cuda.amp.autocast",
"torch.utils.data.DataLoader"
]
] |
mkitti/napari
|
[
"4e954d30b5a1b70c5e495db1b8f48a3bdda1ff86",
"4e954d30b5a1b70c5e495db1b8f48a3bdda1ff86"
] |
[
"napari/layers/points/_tests/test_points.py",
"napari/conftest.py"
] |
[
"from copy import copy\nfrom itertools import cycle, islice\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom vispy.color import get_colormap\n\nfrom napari._tests.utils import check_layer_world_data_extent\nfrom napari.layers import Points\nfrom napari.layers.points._points_utils import points_to_squares\nfrom napari.utils.colormaps.standardize_color import transform_color\n\n\ndef _make_cycled_properties(values, length):\n \"\"\"Helper function to make property values\n\n Parameters\n ----------\n values\n The values to be cycled.\n length : int\n The length of the resulting property array\n\n Returns\n -------\n cycled_properties : np.ndarray\n The property array comprising the cycled values.\n \"\"\"\n cycled_properties = np.array(list(islice(cycle(values), 0, length)))\n return cycled_properties\n\n\ndef test_empty_points():\n pts = Points()\n assert pts.data.shape == (0, 2)\n\n\ndef test_empty_points_with_properties():\n \"\"\" Test instantiating an empty Points layer with properties\n\n See: https://github.com/napari/napari/pull/1069\n \"\"\"\n properties = {\n 'label': np.array(['label1', 'label2']),\n 'cont_prop': np.array([0], dtype=np.float),\n }\n pts = Points(properties=properties)\n current_props = {k: v[0] for k, v in properties.items()}\n np.testing.assert_equal(pts.current_properties, current_props)\n\n # verify the property datatype is correct\n assert pts.properties['cont_prop'].dtype == np.float\n\n # add two points and verify the default property was applied\n pts.add([10, 10])\n pts.add([20, 20])\n props = {\n 'label': np.array(['label1', 'label1']),\n 'cont_prop': np.array([0, 0], dtype=np.float),\n }\n np.testing.assert_equal(pts.properties, props)\n\n\ndef test_empty_points_with_properties_list():\n \"\"\" Test instantiating an empty Points layer with properties\n stored in a list\n\n See: https://github.com/napari/napari/pull/1069\n \"\"\"\n properties = {'label': ['label1', 'label2'], 'cont_prop': [0]}\n pts = Points(properties=properties)\n current_props = {k: np.asarray(v[0]) for k, v in properties.items()}\n np.testing.assert_equal(pts.current_properties, current_props)\n\n # add two points and verify the default property was applied\n pts.add([10, 10])\n pts.add([20, 20])\n props = {\n 'label': np.array(['label1', 'label1']),\n 'cont_prop': np.array([0, 0], dtype=np.float),\n }\n np.testing.assert_equal(pts.properties, props)\n\n\ndef test_empty_layer_with_face_colorap():\n \"\"\" Test creating an empty layer where the face color is a colormap\n See: https://github.com/napari/napari/pull/1069\n \"\"\"\n default_properties = {'point_type': np.array([1.5], dtype=np.float)}\n layer = Points(\n properties=default_properties,\n face_color='point_type',\n face_colormap='gray',\n )\n\n assert layer.face_color_mode == 'colormap'\n\n # verify the current_face_color is correct\n face_color = np.array([1, 1, 1, 1])\n assert np.all(layer._current_face_color == face_color)\n\n\ndef test_empty_layer_with_edge_colormap():\n \"\"\" Test creating an empty layer where the face color is a colormap\n See: https://github.com/napari/napari/pull/1069\n \"\"\"\n default_properties = {'point_type': np.array([1.5], dtype=np.float)}\n layer = Points(\n properties=default_properties,\n edge_color='point_type',\n edge_colormap='gray',\n )\n\n assert layer.edge_color_mode == 'colormap'\n\n # verify the current_face_color is correct\n edge_color = np.array([1, 1, 1, 1])\n assert np.all(layer._current_edge_color == edge_color)\n\n\ndef test_random_points():\n \"\"\"Test instantiating Points layer with random 2D data.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n assert np.all(layer.data == data)\n assert layer.ndim == shape[1]\n assert layer._view_data.ndim == 2\n assert len(layer.data) == 10\n assert len(layer.selected_data) == 0\n\n\ndef test_integer_points():\n \"\"\"Test instantiating Points layer with integer data.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = np.random.randint(20, size=(10, 2))\n layer = Points(data)\n assert np.all(layer.data == data)\n assert layer.ndim == shape[1]\n assert layer._view_data.ndim == 2\n assert len(layer.data) == 10\n\n\ndef test_negative_points():\n \"\"\"Test instantiating Points layer with negative data.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape) - 10\n layer = Points(data)\n assert np.all(layer.data == data)\n assert layer.ndim == shape[1]\n assert layer._view_data.ndim == 2\n assert len(layer.data) == 10\n\n\ndef test_empty_points_array():\n \"\"\"Test instantiating Points layer with empty array.\"\"\"\n shape = (0, 2)\n data = np.empty(shape)\n layer = Points(data)\n assert np.all(layer.data == data)\n assert layer.ndim == shape[1]\n assert layer._view_data.ndim == 2\n assert len(layer.data) == 0\n\n\ndef test_3D_points():\n \"\"\"Test instantiating Points layer with random 3D data.\"\"\"\n shape = (10, 3)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n assert np.all(layer.data == data)\n assert layer.ndim == shape[1]\n assert layer._view_data.ndim == 2\n assert len(layer.data) == 10\n\n\ndef test_4D_points():\n \"\"\"Test instantiating Points layer with random 4D data.\"\"\"\n shape = (10, 4)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n assert np.all(layer.data == data)\n assert layer.ndim == shape[1]\n assert layer._view_data.ndim == 2\n assert len(layer.data) == 10\n\n\ndef test_changing_points():\n \"\"\"Test changing Points data.\"\"\"\n shape_a = (10, 2)\n shape_b = (20, 2)\n np.random.seed(0)\n data_a = 20 * np.random.random(shape_a)\n data_b = 20 * np.random.random(shape_b)\n layer = Points(data_a)\n layer.data = data_b\n assert np.all(layer.data == data_b)\n assert layer.ndim == shape_b[1]\n assert layer._view_data.ndim == 2\n assert len(layer.data) == 20\n\n\ndef test_selecting_points():\n \"\"\"Test selecting points.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n layer.mode = 'select'\n data_to_select = {1, 2}\n layer.selected_data = data_to_select\n assert layer.selected_data == data_to_select\n\n # test switching to 3D\n layer._slice_dims(ndisplay=3)\n assert layer.selected_data == data_to_select\n\n # select different points while in 3D mode\n other_data_to_select = {0}\n layer.selected_data = other_data_to_select\n assert layer.selected_data == other_data_to_select\n\n # selection should persist when going back to 2D mode\n layer._slice_dims(ndisplay=2)\n assert layer.selected_data == other_data_to_select\n\n # selection should persist when switching between between select and pan_zoom\n layer.mode = 'pan_zoom'\n assert layer.selected_data == other_data_to_select\n layer.mode = 'select'\n assert layer.selected_data == other_data_to_select\n\n # add mode should clear the selection\n layer.mode = 'add'\n assert layer.selected_data == set()\n\n\ndef test_adding_points():\n \"\"\"Test adding Points data.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n assert len(layer.data) == 10\n\n coord = [20, 20]\n layer.add(coord)\n assert len(layer.data) == 11\n assert np.all(layer.data[10] == coord)\n # the added point should be selected\n assert layer.selected_data == {10}\n\n # test adding multiple points\n coords = [[10, 10], [15, 15]]\n layer.add(coords)\n assert len(layer.data) == 13\n assert np.all(layer.data[11:, :] == coords)\n\n # test that the last added points can be deleted\n layer.remove_selected()\n np.testing.assert_equal(layer.data, np.vstack((data, coord)))\n\n\ndef test_adding_points_to_empty():\n \"\"\"Test adding Points data to empty.\"\"\"\n shape = (0, 2)\n data = np.empty(shape)\n layer = Points(data)\n assert len(layer.data) == 0\n\n coord = [20, 20]\n layer.add(coord)\n assert len(layer.data) == 1\n assert np.all(layer.data[0] == coord)\n\n\ndef test_removing_selected_points():\n \"\"\"Test selecting points.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n\n # With nothing selected no points should be removed\n layer.remove_selected()\n assert len(layer.data) == shape[0]\n\n # Select two points and remove them\n layer.selected_data = {0, 3}\n layer.remove_selected()\n assert len(layer.data) == shape[0] - 2\n assert len(layer.selected_data) == 0\n keep = [1, 2] + list(range(4, 10))\n assert np.all(layer.data == data[keep])\n\n # Select another point and remove it\n layer.selected_data = {4}\n layer.remove_selected()\n assert len(layer.data) == shape[0] - 3\n\n\ndef test_move():\n \"\"\"Test moving points.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n unmoved = copy(data)\n layer = Points(data)\n\n # Move one point relative to an initial drag start location\n layer._move([0], [0, 0])\n layer._move([0], [10, 10])\n layer._drag_start = None\n assert np.all(layer.data[0] == unmoved[0] + [10, 10])\n assert np.all(layer.data[1:] == unmoved[1:])\n\n # Move two points relative to an initial drag start location\n layer._move([1, 2], [2, 2])\n layer._move([1, 2], np.add([2, 2], [-3, 4]))\n assert np.all(layer.data[1:2] == unmoved[1:2] + [-3, 4])\n\n\ndef test_changing_modes():\n \"\"\"Test changing modes.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n assert layer.mode == 'pan_zoom'\n assert layer.interactive is True\n\n layer.mode = 'add'\n assert layer.mode == 'add'\n assert layer.interactive is False\n\n layer.mode = 'select'\n assert layer.mode == 'select'\n assert layer.interactive is False\n\n layer.mode = 'pan_zoom'\n assert layer.mode == 'pan_zoom'\n assert layer.interactive is True\n\n with pytest.raises(ValueError):\n layer.mode = 'not_a_mode'\n\n\ndef test_name():\n \"\"\"Test setting layer name.\"\"\"\n np.random.seed(0)\n data = 20 * np.random.random((10, 2))\n layer = Points(data)\n assert layer.name == 'Points'\n\n layer = Points(data, name='random')\n assert layer.name == 'random'\n\n layer.name = 'pts'\n assert layer.name == 'pts'\n\n\ndef test_visiblity():\n \"\"\"Test setting layer visibility.\"\"\"\n np.random.seed(0)\n data = 20 * np.random.random((10, 2))\n layer = Points(data)\n assert layer.visible is True\n\n layer.visible = False\n assert layer.visible is False\n\n layer = Points(data, visible=False)\n assert layer.visible is False\n\n layer.visible = True\n assert layer.visible is True\n\n\ndef test_opacity():\n \"\"\"Test setting layer opacity.\"\"\"\n np.random.seed(0)\n data = 20 * np.random.random((10, 2))\n layer = Points(data)\n assert layer.opacity == 1.0\n\n layer.opacity = 0.5\n assert layer.opacity == 0.5\n\n layer = Points(data, opacity=0.6)\n assert layer.opacity == 0.6\n\n layer.opacity = 0.3\n assert layer.opacity == 0.3\n\n\ndef test_blending():\n \"\"\"Test setting layer blending.\"\"\"\n np.random.seed(0)\n data = 20 * np.random.random((10, 2))\n layer = Points(data)\n assert layer.blending == 'translucent'\n\n layer.blending = 'additive'\n assert layer.blending == 'additive'\n\n layer = Points(data, blending='additive')\n assert layer.blending == 'additive'\n\n layer.blending = 'opaque'\n assert layer.blending == 'opaque'\n\n\ndef test_symbol():\n \"\"\"Test setting symbol.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n assert layer.symbol == 'disc'\n\n layer.symbol = 'cross'\n assert layer.symbol == 'cross'\n\n layer = Points(data, symbol='star')\n assert layer.symbol == 'star'\n\n\nproperties_array = {'point_type': _make_cycled_properties(['A', 'B'], 10)}\nproperties_list = {'point_type': list(_make_cycled_properties(['A', 'B'], 10))}\n\n\n@pytest.mark.parametrize(\"properties\", [properties_array, properties_list])\ndef test_properties(properties):\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data, properties=copy(properties))\n np.testing.assert_equal(layer.properties, properties)\n\n current_prop = {'point_type': np.array(['B'])}\n assert layer.current_properties == current_prop\n\n # test removing points\n layer.selected_data = {0, 1}\n layer.remove_selected()\n remove_properties = properties['point_type'][2::]\n assert len(layer.properties['point_type']) == (shape[0] - 2)\n assert np.all(layer.properties['point_type'] == remove_properties)\n\n # test selection of properties\n layer.selected_data = {0}\n selected_annotation = layer.current_properties['point_type']\n assert len(selected_annotation) == 1\n assert selected_annotation[0] == 'A'\n\n # test adding points with properties\n layer.add([10, 10])\n add_annotations = np.concatenate((remove_properties, ['A']), axis=0)\n assert np.all(layer.properties['point_type'] == add_annotations)\n\n # test copy/paste\n layer.selected_data = {0, 1}\n layer._copy_data()\n assert np.all(layer._clipboard['properties']['point_type'] == ['A', 'B'])\n\n layer._paste_data()\n paste_annotations = np.concatenate((add_annotations, ['A', 'B']), axis=0)\n assert np.all(layer.properties['point_type'] == paste_annotations)\n\n\n@pytest.mark.parametrize(\"attribute\", ['edge', 'face'])\ndef test_adding_properties(attribute):\n \"\"\"Test adding properties to an existing layer\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n\n # add properties\n properties = {'point_type': _make_cycled_properties(['A', 'B'], shape[0])}\n layer.properties = properties\n np.testing.assert_equal(layer.properties, properties)\n\n # add properties as a dataframe\n properties_df = pd.DataFrame(properties)\n layer.properties = properties_df\n np.testing.assert_equal(layer.properties, properties)\n\n # add properties as a dictionary with list values\n properties_list = {\n 'point_type': list(_make_cycled_properties(['A', 'B'], shape[0]))\n }\n layer.properties = properties_list\n assert isinstance(layer.properties['point_type'], np.ndarray)\n\n # removing a property that was the _*_color_property should give a warning\n setattr(layer, f'_{attribute}_color_property', 'vector_type')\n properties_2 = {\n 'not_vector_type': _make_cycled_properties(['A', 'B'], shape[0])\n }\n with pytest.warns(RuntimeWarning):\n layer.properties = properties_2\n\n\ndef test_properties_dataframe():\n \"\"\"Test if properties can be provided as a DataFrame\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n properties = {'point_type': _make_cycled_properties(['A', 'B'], shape[0])}\n properties_df = pd.DataFrame(properties)\n properties_df = properties_df.astype(properties['point_type'].dtype)\n layer = Points(data, properties=properties_df)\n np.testing.assert_equal(layer.properties, properties)\n\n\ndef test_add_points_with_properties_as_list():\n # test adding points initialized with properties as list\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n properties = {\n 'point_type': list(_make_cycled_properties(['A', 'B'], shape[0]))\n }\n layer = Points(data, properties=copy(properties))\n\n coord = [18, 18]\n layer.add(coord)\n new_prop = {'point_type': np.append(properties['point_type'], 'B')}\n np.testing.assert_equal(layer.properties, new_prop)\n\n\ndef test_updating_points_properties():\n # test adding points initialized with properties\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n properties = {'point_type': _make_cycled_properties(['A', 'B'], shape[0])}\n layer = Points(data, properties=copy(properties))\n\n layer.mode = 'select'\n layer.selected_data = [len(data) - 1]\n layer.current_properties = {'point_type': np.array(['A'])}\n\n updated_properties = properties\n updated_properties['point_type'][-1] = 'A'\n np.testing.assert_equal(layer.properties, updated_properties)\n\n\nproperties_array = {'point_type': _make_cycled_properties(['A', 'B'], 10)}\nproperties_list = {'point_type': list(_make_cycled_properties(['A', 'B'], 10))}\n\n\n@pytest.mark.parametrize(\"properties\", [properties_array, properties_list])\ndef test_text_from_property_value(properties):\n \"\"\"Test setting text from a property value\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data, properties=copy(properties), text='point_type')\n\n np.testing.assert_equal(layer.text.values, properties['point_type'])\n\n\n@pytest.mark.parametrize(\"properties\", [properties_array, properties_list])\ndef test_text_from_property_fstring(properties):\n \"\"\"Test setting text with an f-string from the property value\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(\n data, properties=copy(properties), text='type: {point_type}'\n )\n\n expected_text = ['type: ' + v for v in properties['point_type']]\n np.testing.assert_equal(layer.text.values, expected_text)\n\n # test updating the text\n layer.text = 'type-ish: {point_type}'\n expected_text_2 = ['type-ish: ' + v for v in properties['point_type']]\n np.testing.assert_equal(layer.text.values, expected_text_2)\n\n # copy/paste\n layer.selected_data = {0}\n layer._copy_data()\n layer._paste_data()\n expected_text_3 = expected_text_2 + ['type-ish: A']\n np.testing.assert_equal(layer.text.values, expected_text_3)\n\n # add point\n layer.selected_data = {0}\n new_shape = np.random.random((1, 2))\n layer.add(new_shape)\n expected_text_4 = expected_text_3 + ['type-ish: A']\n np.testing.assert_equal(layer.text.values, expected_text_4)\n\n\n@pytest.mark.parametrize(\"properties\", [properties_array, properties_list])\ndef test_set_text_with_kwarg_dict(properties):\n text_kwargs = {\n 'text': 'type: {point_type}',\n 'color': [0, 0, 0, 1],\n 'rotation': 10,\n 'translation': [5, 5],\n 'anchor': 'upper_left',\n 'size': 10,\n 'visible': True,\n }\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data, properties=copy(properties), text=text_kwargs)\n\n expected_text = ['type: ' + v for v in properties['point_type']]\n np.testing.assert_equal(layer.text.values, expected_text)\n\n for property, value in text_kwargs.items():\n if property == 'text':\n continue\n layer_value = getattr(layer._text, property)\n np.testing.assert_equal(layer_value, value)\n\n\n@pytest.mark.parametrize(\"properties\", [properties_array, properties_list])\ndef test_text_error(properties):\n \"\"\"creating a layer with text as the wrong type should raise an error\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n # try adding text as the wrong type\n with pytest.raises(TypeError):\n Points(data, properties=copy(properties), text=123)\n\n\ndef test_refresh_text():\n \"\"\"Test refreshing the text after setting new properties\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n properties = {'point_type': ['A'] * shape[0]}\n layer = Points(data, properties=copy(properties), text='point_type')\n\n new_properties = {'point_type': ['B'] * shape[0]}\n layer.properties = new_properties\n np.testing.assert_equal(layer.text.values, new_properties['point_type'])\n\n\ndef test_points_errors():\n shape = (3, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n\n # try adding properties with the wrong number of properties\n with pytest.raises(ValueError):\n annotations = {'point_type': np.array(['A', 'B'])}\n Points(data, properties=copy(annotations))\n\n\ndef test_is_color_mapped():\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n annotations = {'point_type': _make_cycled_properties(['A', 'B'], shape[0])}\n layer = Points(data, properties=annotations)\n\n # giving the name of an annotation should return True\n assert layer._is_color_mapped('point_type')\n\n # giving a list should return false (i.e., could be an RGBA color)\n assert not layer._is_color_mapped([1, 1, 1, 1])\n\n # giving an ndarray should return false (i.e., could be an RGBA color)\n assert not layer._is_color_mapped(np.array([1, 1, 1, 1]))\n\n # give an invalid color argument\n with pytest.raises(ValueError):\n layer._is_color_mapped((123, 323))\n\n\ndef test_edge_width():\n \"\"\"Test setting edge width.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n assert layer.edge_width == 1\n\n layer.edge_width = 2\n assert layer.edge_width == 2\n\n layer = Points(data, edge_width=3)\n assert layer.edge_width == 3\n\n\ndef test_n_dimensional():\n \"\"\"Test setting n_dimensional flag for 2D and 4D data.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n assert layer.n_dimensional is False\n\n layer.n_dimensional = True\n assert layer.n_dimensional is True\n\n layer = Points(data, n_dimensional=True)\n assert layer.n_dimensional is True\n\n shape = (10, 4)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n assert layer.n_dimensional is False\n\n layer.n_dimensional = True\n assert layer.n_dimensional is True\n\n layer = Points(data, n_dimensional=True)\n assert layer.n_dimensional is True\n\n\n@pytest.mark.filterwarnings(\"ignore:elementwise comparison fail:FutureWarning\")\n@pytest.mark.parametrize(\"attribute\", ['edge', 'face'])\ndef test_switch_color_mode(attribute):\n \"\"\"Test switching between color modes\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n # create a continuous property with a known value in the last element\n continuous_prop = np.random.random((shape[0],))\n continuous_prop[-1] = 1\n properties = {\n 'point_truthiness': continuous_prop,\n 'point_type': _make_cycled_properties(['A', 'B'], shape[0]),\n }\n initial_color = [1, 0, 0, 1]\n color_cycle = ['red', 'blue']\n color_kwarg = f'{attribute}_color'\n colormap_kwarg = f'{attribute}_colormap'\n color_cycle_kwarg = f'{attribute}_color_cycle'\n args = {\n color_kwarg: initial_color,\n colormap_kwarg: 'gray',\n color_cycle_kwarg: color_cycle,\n }\n layer = Points(data, properties=properties, **args)\n\n layer_color_mode = getattr(layer, f'{attribute}_color_mode')\n layer_color = getattr(layer, f'{attribute}_color')\n assert layer_color_mode == 'direct'\n np.testing.assert_allclose(\n layer_color, np.repeat([initial_color], shape[0], axis=0)\n )\n\n # there should not be an edge_color_property\n color_property = getattr(layer, f'_{attribute}_color_property')\n assert color_property == ''\n\n # transitioning to colormap should raise a warning\n # because there isn't an edge color property yet and\n # the first property in points.properties is being automatically selected\n with pytest.warns(UserWarning):\n setattr(layer, f'{attribute}_color_mode', 'colormap')\n color_property = getattr(layer, f'_{attribute}_color_property')\n assert color_property == next(iter(properties))\n layer_color = getattr(layer, f'{attribute}_color')\n np.testing.assert_allclose(layer_color[-1], [1, 1, 1, 1])\n\n # switch to color cycle\n setattr(layer, f'{attribute}_color_mode', 'cycle')\n setattr(layer, f'{attribute}_color', 'point_type')\n color = getattr(layer, f'{attribute}_color')\n layer_color = transform_color(color_cycle * int((shape[0] / 2)))\n np.testing.assert_allclose(color, layer_color)\n\n # switch back to direct, edge_colors shouldn't change\n setattr(layer, f'{attribute}_color_mode', 'direct')\n new_edge_color = getattr(layer, f'{attribute}_color')\n np.testing.assert_allclose(new_edge_color, color)\n\n\n@pytest.mark.parametrize(\"attribute\", ['edge', 'face'])\ndef test_colormap_without_properties(attribute):\n \"\"\"Setting the colormode to colormap should raise an exception\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n\n with pytest.raises(ValueError):\n setattr(layer, f'{attribute}_color_mode', 'colormap')\n\n\n@pytest.mark.parametrize(\"attribute\", ['edge', 'face'])\ndef test_colormap_with_categorical_properties(attribute):\n \"\"\"Setting the colormode to colormap should raise an exception\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n properties = {'point_type': _make_cycled_properties(['A', 'B'], shape[0])}\n layer = Points(data, properties=properties)\n\n with pytest.raises(TypeError):\n with pytest.warns(UserWarning):\n setattr(layer, f'{attribute}_color_mode', 'colormap')\n\n\n@pytest.mark.parametrize(\"attribute\", ['edge', 'face'])\ndef test_add_colormap(attribute):\n \"\"\"Test directly adding a vispy Colormap object\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n annotations = {'point_type': _make_cycled_properties([0, 1.5], shape[0])}\n color_kwarg = f'{attribute}_color'\n colormap_kwarg = f'{attribute}_colormap'\n args = {color_kwarg: 'point_type', colormap_kwarg: 'viridis'}\n layer = Points(data, properties=annotations, **args)\n\n setattr(layer, f'{attribute}_colormap', get_colormap('gray'))\n layer_colormap = getattr(layer, f'{attribute}_colormap')\n assert 'unnamed colormap' in layer_colormap.name\n\n\n@pytest.mark.parametrize(\"attribute\", ['edge', 'face'])\ndef test_color_direct(attribute: str):\n \"\"\"Test setting colors directly\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer_kwargs = {f'{attribute}_color': 'black'}\n layer = Points(data, **layer_kwargs)\n color_array = transform_color(['black'] * shape[0])\n current_color = getattr(layer, f'current_{attribute}_color')\n layer_color = getattr(layer, f'{attribute}_color')\n assert current_color == 'black'\n assert len(layer.edge_color) == shape[0]\n np.testing.assert_allclose(color_array, layer_color)\n\n # With no data selected changing color has no effect\n setattr(layer, f'current_{attribute}_color', 'blue')\n current_color = getattr(layer, f'current_{attribute}_color')\n assert current_color == 'blue'\n np.testing.assert_allclose(color_array, layer_color)\n\n # Select data and change edge color of selection\n selected_data = {0, 1}\n layer.selected_data = {0, 1}\n current_color = getattr(layer, f'current_{attribute}_color')\n assert current_color == 'black'\n setattr(layer, f'current_{attribute}_color', 'green')\n colorarray_green = transform_color(['green'] * len(layer.selected_data))\n color_array[list(selected_data)] = colorarray_green\n layer_color = getattr(layer, f'{attribute}_color')\n np.testing.assert_allclose(color_array, layer_color)\n\n # Add new point and test its color\n coord = [18, 18]\n layer.selected_data = {}\n setattr(layer, f'current_{attribute}_color', 'blue')\n layer.add(coord)\n color_array = np.vstack([color_array, transform_color('blue')])\n layer_color = getattr(layer, f'{attribute}_color')\n assert len(layer_color) == shape[0] + 1\n np.testing.assert_allclose(color_array, layer_color)\n\n # Check removing data adjusts colors correctly\n layer.selected_data = {0, 2}\n layer.remove_selected()\n assert len(layer.data) == shape[0] - 1\n\n layer_color = getattr(layer, f'{attribute}_color')\n assert len(layer_color) == shape[0] - 1\n np.testing.assert_allclose(\n layer_color, np.vstack((color_array[1], color_array[3:])),\n )\n\n\ncolor_cycle_str = ['red', 'blue']\ncolor_cycle_rgb = [[1, 0, 0], [0, 0, 1]]\ncolor_cycle_rgba = [[1, 0, 0, 1], [0, 0, 1, 1]]\n\n\n@pytest.mark.parametrize(\"attribute\", ['edge', 'face'])\n@pytest.mark.parametrize(\n \"color_cycle\", [color_cycle_str, color_cycle_rgb, color_cycle_rgba],\n)\ndef test_color_cycle(attribute, color_cycle):\n \"\"\"Test setting edge/face color with a color cycle list\"\"\"\n # create Points using list color cycle\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n properties = {'point_type': _make_cycled_properties(['A', 'B'], shape[0])}\n points_kwargs = {\n 'properties': properties,\n f'{attribute}_color': 'point_type',\n f'{attribute}_color_cycle': color_cycle,\n }\n layer = Points(data, **points_kwargs)\n\n assert layer.properties == properties\n color_array = transform_color(\n list(islice(cycle(color_cycle), 0, shape[0]))\n )\n layer_color = getattr(layer, f'{attribute}_color')\n np.testing.assert_allclose(layer_color, color_array)\n\n # Add new point and test its color\n coord = [18, 18]\n layer.selected_data = {0}\n layer.add(coord)\n layer_color = getattr(layer, f'{attribute}_color')\n assert len(layer_color) == shape[0] + 1\n np.testing.assert_allclose(\n layer_color, np.vstack((color_array, transform_color('red'))),\n )\n\n # Check removing data adjusts colors correctly\n layer.selected_data = {0, 2}\n layer.remove_selected()\n assert len(layer.data) == shape[0] - 1\n\n layer_color = getattr(layer, f'{attribute}_color')\n assert len(layer_color) == shape[0] - 1\n np.testing.assert_allclose(\n layer_color,\n np.vstack((color_array[1], color_array[3:], transform_color('red'))),\n )\n\n # refresh colors\n layer.refresh_colors(update_color_mapping=True)\n\n # test adding a point with a new property value\n layer.selected_data = {}\n current_properties = layer.current_properties\n current_properties['point_type'] = np.array(['new'])\n layer.current_properties = current_properties\n layer.add([10, 10])\n color_cycle_map = getattr(layer, f'{attribute}_color_cycle_map')\n\n assert 'new' in color_cycle_map\n np.testing.assert_allclose(\n color_cycle_map['new'], np.squeeze(transform_color(color_cycle[0]))\n )\n\n\n@pytest.mark.parametrize(\"attribute\", ['edge', 'face'])\ndef test_add_color_cycle_to_empty_layer(attribute):\n \"\"\" Test adding a point to an empty layer when edge/face color is a color cycle\n\n See: https://github.com/napari/napari/pull/1069\n \"\"\"\n default_properties = {'point_type': np.array(['A'])}\n color_cycle = ['red', 'blue']\n points_kwargs = {\n 'properties': default_properties,\n f'{attribute}_color': 'point_type',\n f'{attribute}_color_cycle': color_cycle,\n }\n layer = Points(**points_kwargs)\n\n # verify the current_edge_color is correct\n expected_color = transform_color(color_cycle[0])\n current_color = getattr(layer, f'_current_{attribute}_color')\n np.testing.assert_allclose(current_color, expected_color)\n\n # add a point\n layer.add([10, 10])\n props = {'point_type': np.array(['A'])}\n expected_color = np.array([[1, 0, 0, 1]])\n np.testing.assert_equal(layer.properties, props)\n attribute_color = getattr(layer, f'{attribute}_color')\n np.testing.assert_allclose(attribute_color, expected_color)\n\n # add a point with a new property\n layer.selected_data = []\n layer.current_properties = {'point_type': np.array(['B'])}\n layer.add([12, 12])\n new_color = np.array([0, 0, 1, 1])\n expected_color = np.vstack((expected_color, new_color))\n new_properties = {'point_type': np.array(['A', 'B'])}\n attribute_color = getattr(layer, f'{attribute}_color')\n np.testing.assert_allclose(attribute_color, expected_color)\n np.testing.assert_equal(layer.properties, new_properties)\n\n\n@pytest.mark.parametrize(\"attribute\", ['edge', 'face'])\ndef test_adding_value_color_cycle(attribute):\n \"\"\" Test that adding values to properties used to set a color cycle\n and then calling Points.refresh_colors() performs the update and adds the\n new value to the face/edge_color_cycle_map.\n\n See: https://github.com/napari/napari/issues/988\n \"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n properties = {'point_type': _make_cycled_properties(['A', 'B'], shape[0])}\n color_cycle = ['red', 'blue']\n points_kwargs = {\n 'properties': properties,\n f'{attribute}_color': 'point_type',\n f'{attribute}_color_cycle': color_cycle,\n }\n layer = Points(data, **points_kwargs)\n\n # make point 0 point_type C\n point_types = layer.properties['point_type']\n point_types[0] = 'C'\n layer.properties['point_type'] = point_types\n layer.refresh_colors(update_color_mapping=False)\n\n color_cycle_map = getattr(layer, f'{attribute}_color_cycle_map')\n color_map_keys = [*color_cycle_map]\n assert 'C' in color_map_keys\n\n\n@pytest.mark.parametrize(\"attribute\", ['edge', 'face'])\ndef test_color_colormap(attribute):\n \"\"\"Test setting edge/face color with a colormap\"\"\"\n # create Points using with a colormap\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n properties = {'point_type': _make_cycled_properties([0, 1.5], shape[0])}\n points_kwargs = {\n 'properties': properties,\n f'{attribute}_color': 'point_type',\n f'{attribute}_colormap': 'gray',\n }\n layer = Points(data, **points_kwargs)\n assert layer.properties == properties\n color_mode = getattr(layer, f'{attribute}_color_mode')\n assert color_mode == 'colormap'\n color_array = transform_color(['black', 'white'] * int((shape[0] / 2)))\n attribute_color = getattr(layer, f'{attribute}_color')\n assert np.all(attribute_color == color_array)\n\n # change the color cycle - face_color should not change\n setattr(layer, f'{attribute}_color_cycle', ['red', 'blue'])\n attribute_color = getattr(layer, f'{attribute}_color')\n assert np.all(attribute_color == color_array)\n\n # Add new point and test its color\n coord = [18, 18]\n layer.selected_data = {0}\n layer.add(coord)\n attribute_color = getattr(layer, f'{attribute}_color')\n assert len(attribute_color) == shape[0] + 1\n np.testing.assert_allclose(\n attribute_color, np.vstack((color_array, transform_color('black'))),\n )\n\n # Check removing data adjusts colors correctly\n layer.selected_data = {0, 2}\n layer.remove_selected()\n assert len(layer.data) == shape[0] - 1\n attribute_color = getattr(layer, f'{attribute}_color')\n assert len(attribute_color) == shape[0] - 1\n np.testing.assert_allclose(\n attribute_color,\n np.vstack(\n (color_array[1], color_array[3:], transform_color('black'),)\n ),\n )\n\n # adjust the clims\n setattr(layer, f'{attribute}_contrast_limits', (0, 3))\n layer.refresh_colors(update_color_mapping=False)\n attribute_color = getattr(layer, f'{attribute}_color')\n np.testing.assert_allclose(attribute_color[-2], [0.5, 0.5, 0.5, 1])\n\n # change the colormap\n new_colormap = 'viridis'\n setattr(layer, f'{attribute}_colormap', new_colormap)\n attribute_colormap = getattr(layer, f'{attribute}_colormap')\n assert attribute_colormap.name == new_colormap\n\n\ndef test_size():\n \"\"\"Test setting size with scalar.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n assert layer.current_size == 10\n assert layer.size.shape == shape\n assert np.unique(layer.size)[0] == 10\n\n # Add a new point, it should get current size\n coord = [17, 17]\n layer.add(coord)\n assert layer.size.shape == (11, 2)\n assert np.unique(layer.size)[0] == 10\n\n # Setting size affects newly added points not current points\n layer.current_size = 20\n assert layer.current_size == 20\n assert layer.size.shape == (11, 2)\n assert np.unique(layer.size)[0] == 10\n\n # Add new point, should have new size\n coord = [18, 18]\n layer.add(coord)\n assert layer.size.shape == (12, 2)\n assert np.unique(layer.size[:11])[0] == 10\n assert np.all(layer.size[11] == [20, 20])\n\n # Select data and change size\n layer.selected_data = {0, 1}\n assert layer.current_size == 10\n layer.current_size = 16\n assert layer.size.shape == (12, 2)\n assert np.unique(layer.size[2:11])[0] == 10\n assert np.unique(layer.size[:2])[0] == 16\n\n # Select data and size changes\n layer.selected_data = {11}\n assert layer.current_size == 20\n\n\ndef test_size_with_arrays():\n \"\"\"Test setting size with arrays.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n sizes = 5 * np.random.random(shape)\n layer.size = sizes\n assert np.all(layer.size == sizes)\n\n # Test broadcasting of sizes\n sizes = [5, 5]\n layer.size = sizes\n assert np.all(layer.size[0] == sizes)\n\n # Test broadcasting of transposed sizes\n sizes = np.random.randint(low=1, high=5, size=shape[::-1])\n layer.size = sizes\n np.testing.assert_equal(layer.size, sizes.T)\n\n # Un-broadcastable array should raise an exception\n bad_sizes = np.random.randint(low=1, high=5, size=(3, 8))\n with pytest.raises(ValueError):\n layer.size = bad_sizes\n\n # Create new layer with new size array data\n sizes = 5 * np.random.random(shape)\n layer = Points(data, size=sizes)\n assert layer.current_size == 10\n assert layer.size.shape == shape\n assert np.all(layer.size == sizes)\n\n # Create new layer with new size array data\n sizes = [5, 5]\n layer = Points(data, size=sizes)\n assert layer.current_size == 10\n assert layer.size.shape == shape\n assert np.all(layer.size[0] == sizes)\n\n # Add new point, should have new size\n coord = [18, 18]\n layer.current_size = 13\n layer.add(coord)\n assert layer.size.shape == (11, 2)\n assert np.unique(layer.size[:10])[0] == 5\n assert np.all(layer.size[10] == [13, 13])\n\n # Select data and change size\n layer.selected_data = {0, 1}\n assert layer.current_size == 5\n layer.current_size = 16\n assert layer.size.shape == (11, 2)\n assert np.unique(layer.size[2:10])[0] == 5\n assert np.unique(layer.size[:2])[0] == 16\n\n # Check removing data adjusts colors correctly\n layer.selected_data = {0, 2}\n layer.remove_selected()\n assert len(layer.data) == 9\n assert len(layer.size) == 9\n assert np.all(layer.size[0] == [16, 16])\n assert np.all(layer.size[1] == [5, 5])\n\n\ndef test_size_with_3D_arrays():\n \"\"\"Test setting size with 3D arrays.\"\"\"\n shape = (10, 3)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n data[:2, 0] = 0\n layer = Points(data)\n assert layer.current_size == 10\n assert layer.size.shape == shape\n assert np.unique(layer.size)[0] == 10\n\n sizes = 5 * np.random.random(shape)\n layer.size = sizes\n assert np.all(layer.size == sizes)\n\n # Test broadcasting of sizes\n sizes = [1, 5, 5]\n layer.size = sizes\n assert np.all(layer.size[0] == sizes)\n\n # Create new layer with new size array data\n sizes = 5 * np.random.random(shape)\n layer = Points(data, size=sizes)\n assert layer.current_size == 10\n assert layer.size.shape == shape\n assert np.all(layer.size == sizes)\n\n # Create new layer with new size array data\n sizes = [1, 5, 5]\n layer = Points(data, size=sizes)\n assert layer.current_size == 10\n assert layer.size.shape == shape\n assert np.all(layer.size[0] == sizes)\n\n # Add new point, should have new size in last dim only\n coord = [4, 18, 18]\n layer.current_size = 13\n layer.add(coord)\n assert layer.size.shape == (11, 3)\n assert np.unique(layer.size[:10, 1:])[0] == 5\n assert np.all(layer.size[10] == [1, 13, 13])\n\n # Select data and change size\n layer.selected_data = {0, 1}\n assert layer.current_size == 5\n layer.current_size = 16\n assert layer.size.shape == (11, 3)\n assert np.unique(layer.size[2:10, 1:])[0] == 5\n assert np.all(layer.size[0] == [16, 16, 16])\n\n # Create new 3D layer with new 2D points size data\n sizes = [0, 5, 5]\n layer = Points(data, size=sizes)\n assert layer.current_size == 10\n assert layer.size.shape == shape\n assert np.all(layer.size[0] == sizes)\n\n # Add new point, should have new size only in last 2 dimensions\n coord = [4, 18, 18]\n layer.current_size = 13\n layer.add(coord)\n assert layer.size.shape == (11, 3)\n assert np.all(layer.size[10] == [0, 13, 13])\n\n # Select data and change size\n layer.selected_data = {0, 1}\n assert layer.current_size == 5\n layer.current_size = 16\n assert layer.size.shape == (11, 3)\n assert np.unique(layer.size[2:10, 1:])[0] == 5\n assert np.all(layer.size[0] == [0, 16, 16])\n\n\ndef test_copy_and_paste():\n \"\"\"Test copying and pasting selected points.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n layer = Points(data)\n # Clipboard starts empty\n assert layer._clipboard == {}\n\n # Pasting empty clipboard doesn't change data\n layer._paste_data()\n assert len(layer.data) == 10\n\n # Copying with nothing selected leave clipboard empty\n layer._copy_data()\n assert layer._clipboard == {}\n\n # Copying and pasting with two points selected adds to clipboard and data\n layer.selected_data = {0, 1}\n layer._copy_data()\n layer._paste_data()\n assert len(layer._clipboard.keys()) > 0\n assert len(layer.data) == shape[0] + 2\n assert np.all(layer.data[:2] == layer.data[-2:])\n\n # Pasting again adds two more points to data\n layer._paste_data()\n assert len(layer.data) == shape[0] + 4\n assert np.all(layer.data[:2] == layer.data[-2:])\n\n # Unselecting everything and copying and pasting will empty the clipboard\n # and add no new data\n layer.selected_data = {}\n layer._copy_data()\n layer._paste_data()\n assert layer._clipboard == {}\n assert len(layer.data) == shape[0] + 4\n\n\ndef test_value():\n \"\"\"Test getting the value of the data at the current coordinates.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n data[-1] = [0, 0]\n layer = Points(data)\n value = layer.get_value()\n assert layer.coordinates == (0, 0)\n assert value == 9\n\n layer.data = layer.data + 20\n value = layer.get_value()\n assert value is None\n\n\ndef test_message():\n \"\"\"Test converting value and coords to message.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n data[-1] = [0, 0]\n layer = Points(data)\n msg = layer.get_message()\n assert type(msg) == str\n\n\ndef test_thumbnail():\n \"\"\"Test the image thumbnail for square data.\"\"\"\n shape = (10, 2)\n np.random.seed(0)\n data = 20 * np.random.random(shape)\n data[0] = [0, 0]\n data[-1] = [20, 20]\n layer = Points(data)\n layer._update_thumbnail()\n assert layer.thumbnail.shape == layer._thumbnail_shape\n\n\ndef test_thumbnail_with_n_points_greater_than_max():\n \"\"\"Test thumbnail generation with n_points > _max_points_thumbnail\n\n see: https://github.com/napari/napari/pull/934\n \"\"\"\n # 2D\n max_points = Points._max_points_thumbnail * 2\n bigger_data = np.random.randint(10, 100, (max_points, 2))\n big_layer = Points(bigger_data)\n big_layer._update_thumbnail()\n assert big_layer.thumbnail.shape == big_layer._thumbnail_shape\n\n # #3D\n bigger_data_3d = np.random.randint(10, 100, (max_points, 3))\n bigger_layer_3d = Points(bigger_data_3d)\n bigger_layer_3d._slice_dims(ndisplay=3)\n bigger_layer_3d._update_thumbnail()\n assert bigger_layer_3d.thumbnail.shape == bigger_layer_3d._thumbnail_shape\n\n\ndef test_view_data():\n coords = np.array([[0, 1, 1], [0, 2, 2], [1, 3, 3], [3, 3, 3]])\n layer = Points(coords)\n\n layer._slice_dims([0, slice(None), slice(None)])\n assert np.all(\n layer._view_data == coords[np.ix_([0, 1], layer.dims.displayed)]\n )\n\n layer._slice_dims([1, slice(None), slice(None)])\n assert np.all(\n layer._view_data == coords[np.ix_([2], layer.dims.displayed)]\n )\n\n layer._slice_dims([1, slice(None), slice(None)], ndisplay=3)\n assert np.all(layer._view_data == coords)\n\n\ndef test_view_size():\n coords = np.array([[0, 1, 1], [0, 2, 2], [1, 3, 3], [3, 3, 3]])\n sizes = np.array([[3, 5, 5], [3, 5, 5], [3, 3, 3], [2, 2, 3]])\n layer = Points(coords, size=sizes, n_dimensional=False)\n\n layer._slice_dims([0, slice(None), slice(None)])\n assert np.all(\n layer._view_size == sizes[np.ix_([0, 1], layer.dims.displayed)]\n )\n\n layer._slice_dims([1, slice(None), slice(None)])\n assert np.all(layer._view_size == sizes[np.ix_([2], layer.dims.displayed)])\n\n layer.n_dimensional = True\n assert len(layer._view_size) == 3\n\n # test a slice with no points\n layer.n_dimensional = False\n layer._slice_dims([2, slice(None), slice(None)])\n assert np.all(layer._view_size == [])\n\n\ndef test_view_colors():\n coords = [[0, 1, 1], [0, 2, 2], [1, 3, 3], [3, 3, 3]]\n face_color = np.array(\n [[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 1, 1]]\n )\n edge_color = np.array(\n [[0, 0, 1, 1], [1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]]\n )\n\n layer = Points(coords, face_color=face_color, edge_color=edge_color)\n layer._slice_dims([0, slice(None), slice(None)])\n assert np.all(layer._view_face_color == face_color[[0, 1]])\n assert np.all(layer._view_edge_color == edge_color[[0, 1]])\n\n layer._slice_dims([1, slice(None), slice(None)])\n assert np.all(layer._view_face_color == face_color[[2]])\n assert np.all(layer._view_edge_color == edge_color[[2]])\n\n # view colors should return empty array if there are no points\n layer._slice_dims([2, slice(None), slice(None)])\n assert len(layer._view_face_color) == 0\n assert len(layer._view_edge_color) == 0\n\n\ndef test_interaction_box():\n \"\"\"Test the boxes calculated for selected points\"\"\"\n data = [[3, 3]]\n size = 2\n layer = Points(data, size=size)\n\n # get a box with no points selected\n index = []\n box = layer.interaction_box(index)\n assert box is None\n\n # get a box with a point selected\n index = [0]\n expected_box = points_to_squares(data, size)\n box = layer.interaction_box(index)\n np.all([np.isin(p, expected_box) for p in box])\n\n\ndef test_world_data_extent():\n \"\"\"Test extent after applying transforms.\"\"\"\n data = [(7, -5, 0), (-2, 0, 15), (4, 30, 12)]\n min_val = (-2, -5, 0)\n max_val = (7, 30, 15)\n layer = Points(data)\n extent = np.array((min_val, max_val))\n check_layer_world_data_extent(layer, extent, (3, 1, 1), (10, 20, 5))\n",
"import warnings\nfrom functools import partial\nfrom typing import List\n\nimport numpy as np\nimport pytest\nfrom qtpy.QtWidgets import QApplication\n\nfrom napari import Viewer\nfrom napari.components import LayerList\nfrom napari.layers import Image, Labels, Points, Shapes, Vectors\nfrom napari.plugins._builtins import (\n napari_write_image,\n napari_write_labels,\n napari_write_points,\n napari_write_shapes,\n)\nfrom napari.utils import io\n\ntry:\n from skimage.data import image_fetcher\nexcept ImportError:\n import os\n\n from skimage.data import data_dir\n\n class image_fetcher:\n def fetch(data_name):\n if data_name.startswith(\"data/\"):\n data_name = data_name[5:]\n path = os.path.join(data_dir, data_name)\n if not os.path.exists(path):\n raise ValueError(\n f\"Legacy skimage image_fetcher cannot find file: {path}\"\n )\n return path\n\n\ndef pytest_addoption(parser):\n \"\"\"Add napari specific command line options.\n\n --show-viewer\n Show viewers during tests, they are hidden by default. Showing viewers\n decreases test speed by around 20%.\n\n --perfmon-only\n Run only perfmon test.\n\n Notes\n -----\n Due to the placement of this conftest.py file, you must specifically name\n the napari folder such as \"pytest napari --show-viewer\"\n\n For --perfmon-only must also enable perfmon with env var:\n NAPARI_PERFMON=1 pytest napari --perfmon-only\n \"\"\"\n parser.addoption(\n \"--show-viewer\",\n action=\"store_true\",\n default=False,\n help=\"don't show viewer during tests\",\n )\n\n parser.addoption(\n \"--perfmon-only\",\n action=\"store_true\",\n default=False,\n help=\"run only perfmon tests\",\n )\n\n\n@pytest.fixture\ndef qtbot(qtbot):\n \"\"\"A modified qtbot fixture that makes sure no widgets have been leaked.\"\"\"\n initial = QApplication.topLevelWidgets()\n yield qtbot\n QApplication.processEvents()\n leaks = set(QApplication.topLevelWidgets()).difference(initial)\n # still not sure how to clean up some of the remaining vispy\n # vispy.app.backends._qt.CanvasBackendDesktop widgets...\n if any([n.__class__.__name__ != 'CanvasBackendDesktop' for n in leaks]):\n raise AssertionError(f'Widgets leaked!: {leaks}')\n if leaks:\n warnings.warn(f'Widgets leaked!: {leaks}')\n\n\n@pytest.fixture(scope=\"function\")\ndef make_test_viewer(qtbot, request):\n viewers: List[Viewer] = []\n\n def actual_factory(*model_args, **model_kwargs):\n model_kwargs['show'] = model_kwargs.pop(\n 'show', request.config.getoption(\"--show-viewer\")\n )\n viewer = Viewer(*model_args, **model_kwargs)\n viewers.append(viewer)\n return viewer\n\n yield actual_factory\n\n for viewer in viewers:\n viewer.close()\n\n\n@pytest.fixture(\n params=['image', 'labels', 'points', 'points-with-properties', 'shapes']\n)\ndef layer_writer_and_data(request):\n \"\"\"Fixture that supplies layer io utilities for tests.\n\n Parameters\n ----------\n request : _pytest.fixtures.SubRequest\n The pytest request object\n\n Returns\n -------\n tuple\n ``(writer, layer_data, extension, reader, Layer)``\n\n - writer: a function that can write layerdata to a path\n - layer_data: the layerdata tuple for this layer\n - extension: an appropriate extension for this layer type\n - reader: a function that can read this layer type from a path and\n returns a ``(data, meta)`` tuple.\n - Layer: the Layer class\n \"\"\"\n if request.param == 'image':\n data = np.random.rand(20, 20)\n Layer = Image\n layer = Image(data)\n writer = napari_write_image\n extension = '.tif'\n\n def reader(path):\n return (io.imread(path), {}, 'image') # metadata\n\n elif request.param == 'labels':\n data = np.random.randint(0, 16000, (32, 32), 'uint64')\n Layer = Labels\n layer = Labels(data)\n writer = napari_write_labels\n extension = '.tif'\n\n def reader(path):\n return (io.imread(path), {}, 'labels') # metadata\n\n elif request.param == 'points':\n data = np.random.rand(20, 2)\n Layer = Points\n layer = Points(data)\n writer = napari_write_points\n extension = '.csv'\n reader = partial(io.csv_to_layer_data, require_type='points')\n elif request.param == 'points-with-properties':\n data = np.random.rand(20, 2)\n Layer = Points\n layer = Points(data, properties={'values': np.random.rand(20)})\n writer = napari_write_points\n extension = '.csv'\n reader = partial(io.csv_to_layer_data, require_type='points')\n elif request.param == 'shapes':\n np.random.seed(0)\n data = [\n np.random.rand(2, 2),\n np.random.rand(2, 2),\n np.random.rand(6, 2),\n np.random.rand(6, 2),\n np.random.rand(2, 2),\n ]\n shape_type = ['ellipse', 'line', 'path', 'polygon', 'rectangle']\n Layer = Shapes\n layer = Shapes(data, shape_type=shape_type)\n writer = napari_write_shapes\n extension = '.csv'\n reader = partial(io.csv_to_layer_data, require_type='shapes')\n else:\n return None, None, None, None, None\n\n layer_data = layer.as_layer_data_tuple()\n return writer, layer_data, extension, reader, Layer\n\n\n@pytest.fixture\ndef layer_data_and_types():\n \"\"\"Fixture that provides some layers and filenames\n\n Returns\n -------\n tuple\n ``layers, layer_data, layer_types, filenames``\n\n - layers: some image and points layers\n - layer_data: same as above but in LayerData form\n - layer_types: list of strings with type of layer\n - filenames: the expected filenames with extensions for the layers.\n \"\"\"\n layers = [\n Image(np.random.rand(20, 20), name='ex_img'),\n Image(np.random.rand(20, 20)),\n Points(np.random.rand(20, 2), name='ex_pts'),\n Points(\n np.random.rand(20, 2), properties={'values': np.random.rand(20)}\n ),\n ]\n extensions = ['.tif', '.tif', '.csv', '.csv']\n layer_data = [layer.as_layer_data_tuple() for layer in layers]\n layer_types = [layer._type_string for layer in layers]\n filenames = [layer.name + e for layer, e in zip(layers, extensions)]\n return layers, layer_data, layer_types, filenames\n\n\n@pytest.fixture(\n params=[\n 'image',\n 'labels',\n 'points',\n 'shapes',\n 'shapes-rectangles',\n 'vectors',\n ]\n)\ndef layer(request):\n \"\"\"Parameterized fixture that supplies a layer for testing.\n\n Parameters\n ----------\n request : _pytest.fixtures.SubRequest\n The pytest request object\n\n Returns\n -------\n napari.layers.Layer\n The desired napari Layer.\n \"\"\"\n np.random.seed(0)\n if request.param == 'image':\n data = np.random.rand(20, 20)\n return Image(data)\n elif request.param == 'labels':\n data = np.random.randint(10, size=(20, 20))\n return Labels(data)\n elif request.param == 'points':\n data = np.random.rand(20, 2)\n return Points(data)\n elif request.param == 'shapes':\n data = [\n np.random.rand(2, 2),\n np.random.rand(2, 2),\n np.random.rand(6, 2),\n np.random.rand(6, 2),\n np.random.rand(2, 2),\n ]\n shape_type = ['ellipse', 'line', 'path', 'polygon', 'rectangle']\n return Shapes(data, shape_type=shape_type)\n elif request.param == 'shapes-rectangles':\n data = np.random.rand(7, 4, 2)\n return Shapes(data)\n elif request.param == 'vectors':\n data = np.random.rand(20, 2, 2)\n return Vectors(data)\n else:\n return None\n\n\n@pytest.fixture()\ndef layers():\n \"\"\"Fixture that supplies a layers list for testing.\n\n Returns\n -------\n napari.components.LayerList\n The desired napari LayerList.\n \"\"\"\n np.random.seed(0)\n list_of_layers = [\n Image(np.random.rand(20, 20)),\n Labels(np.random.randint(10, size=(20, 2))),\n Points(np.random.rand(20, 2)),\n Shapes(np.random.rand(10, 2, 2)),\n Vectors(np.random.rand(10, 2, 2)),\n ]\n return LayerList(list_of_layers)\n\n\n@pytest.fixture\ndef two_pngs():\n return [image_fetcher.fetch(f'data/{n}.png') for n in ('moon', 'camera')]\n\n\n@pytest.fixture\ndef rgb_png():\n return [image_fetcher.fetch('data/astronaut.png')]\n\n\n@pytest.fixture\ndef single_png():\n return [image_fetcher.fetch('data/camera.png')]\n\n\n@pytest.fixture\ndef irregular_images():\n return [image_fetcher.fetch(f'data/{n}.png') for n in ('camera', 'coins')]\n\n\n@pytest.fixture\ndef single_tiff():\n return [image_fetcher.fetch('data/multipage.tif')]\n\n\n@pytest.fixture(autouse=True)\ndef perfmon_only(request):\n \"\"\"If flag is set, only run the perfmon tests.\"\"\"\n perfmon_flag = request.config.getoption(\"--perfmon-only\")\n perfmon_test = request.node.get_closest_marker('perfmon')\n if perfmon_flag and not perfmon_test:\n pytest.skip(\"running with --perfmon-only\")\n if not perfmon_flag and perfmon_test:\n pytest.skip(\"not running with --perfmon-only\")\n"
] |
[
[
"numpy.concatenate",
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.add",
"numpy.empty",
"numpy.asarray",
"numpy.repeat",
"numpy.testing.assert_equal",
"numpy.random.seed",
"pandas.DataFrame",
"numpy.ix_",
"numpy.random.randint",
"numpy.unique",
"numpy.append",
"numpy.all",
"numpy.random.random",
"numpy.vstack",
"numpy.isin"
],
[
"numpy.random.seed",
"numpy.random.randint",
"numpy.random.rand"
]
] |
culebron/erde
|
[
"9bbaaa1df46629a182c355413a120aa33dc6b377"
] |
[
"tests/utils/test_utils.py"
] |
[
"import geopandas as gpd\nimport pytest\nfrom erde import utils, read_df\nfrom erde.op import sjoin, buffer\nfrom shapely import wkt\nfrom shapely.geometry import LineString\n\npl1 = wkt.loads('LINESTRING (82.956142 55.050099,83.174036 54.923359,83.019111 54.845166,82.801218 54.963546,82.913163 55.043800,83.124060 54.926231,83.008117 54.879681,82.861188 54.966989)')\n\npl2 = wkt.loads('LINESTRING (83.53793 56.10852, 86.04281 55.34134, 87.18539 53.78736, 83.75766 53.36991, 73.5184 55.01512)')\n\npts = read_df('tests/sjoin/points.geojson')\npolys = read_df('tests/sjoin/polys.geojson')\n\nhouses = read_df('tests/utils/houses.csv')\nhouses.crs = 4326\nschools = read_df('tests/utils/schools.csv')\nschools.crs = 4326\n\ndef test_polyline():\n\tassert utils.encode_poly(pl1) == 'c~~nI{jiyNbwW{pi@tgNhg]{bVxpi@qtNszTx}Uceh@|aHrsUu`Phu['\n\n\tl2 = utils.decode_poly('gumuIa_{|NzytCofhNjonHcd~E`ppAhn|Sqi`Ijzn}@')\n\n\tassert isinstance(l2, LineString)\n\tassert l2.equals(pl2)\n\n\ndef test_linestring_between():\n\t# error: index1 not equal index2\n\twith pytest.raises(ValueError):\n\t\tutils.linestring_between(pts.geometry, polys.geometry)\n\n\ths = sjoin.sjfull(houses, schools, right_on=buffer.main(schools.geometry, 500))\n\n\tassert 'geometry_right' in hs and 'geometry' in hs\n\tlines = utils.linestring_between(hs['geometry'], hs['geometry_right'])\n\tassert isinstance(lines, gpd.GeoSeries)\n\tassert lines.index.equals(hs['geometry'].index)\n\n\tfor i, v in hs['geometry'].items():\n\t\tassert LineString([v, hs['geometry_right'].loc[i]]).equals(lines.loc[i])\n\n\t# index is a part of other index => error\n\twith pytest.raises(ValueError):\n\t\tutils.linestring_between(hs['geometry'], hs[hs.index < 100]['geometry_right'])\n\n\tlst1 = hs['geometry'].tolist()\n\tlst2 = hs['geometry_right'].tolist()\n\tlines2 = utils.linestring_between(lst1, lst2)\n\tassert isinstance(lines2, list)\n\tfor a, b, c in zip(lst1, lst2, lines2):\n\t\tassert LineString([a, b]) == c\n\n\t# different lengths => error\n\twith pytest.raises(ValueError):\n\t\tutils.linestring_between(lst1, lst2[:-3])\n\n\ndef test_coslat():\n\timport numpy as np\n\timport pandas as pd\n\n\tfor df in (schools, houses, pts):\n\t\tgeom = df.geometry\n\t\tif any(geom.geom_type != 'Point'):\n\t\t\tgeom = geom.to_crs(3857).centroid.to_crs(4326)\n\n\t\tcoslat1 = geom.apply(lambda g: np.cos(np.radians(g.y)))\n\t\tcoslat2 = utils.coslat(df.geometry)\n\t\tassert isinstance(coslat2, pd.Series)\n\t\tassert all(coslat1 - coslat2 < .000000001)\n\n\ndef test_crossjoin():\n\timport pandas as pd\n\tdf1 = pd.DataFrame({'a': list(range(5)), 'b': list(range(5, 10))})\n\tdf2 = pd.DataFrame({'c': list(range(10, 17))})\n\n\tcj = utils.crossjoin(df1, df2)\n\tassert len(cj) == len(df1) * len(df2)\n\tfor a, g in cj.groupby('a'):\n\t\tassert set(g['c']) == set(range(10, 17))\n\n\tassert '_tmpkey' not in cj\n\n\ndef test_lonlat2gdf():\n\th = houses.copy()\n\n\tfor x, y in (('lon', 'lat'), ('lng', 'lat'), ('long', 'lat'), ('longitude', 'latitude'), ('x', 'y'), ('X', 'Y')):\n\t\th[x] = h.geometry.x\n\t\th[y] = h.geometry.y\n\n\t\tres = utils.lonlat2gdf(h[[x, y]].copy()) # copy to avoid SettingWithCopyWarning\n\t\tassert h.geometry.equals(res.geometry)\n\n\th['tst1'] = h.geometry.x\n\th['tst2'] = h.geometry.y\n\twith pytest.raises(ValueError):\n\t\tutils.lonlat2gdf(h[['tst1', 'tst2']])\n\n\ndef test_transform():\n\th2 = houses[:10]\n\tfrom functools import partial\n\tg3857 = h2.geometry.apply(partial(utils.transform, crs_from=4326, crs_to=3857))\n\tg3857.crs = 3857 # to avoid CRS mismatch warning\n\n\tassert all(h2.to_crs(3857).geometry.geom_almost_equals(g3857))\n"
] |
[
[
"numpy.radians"
]
] |
akern40/pyro
|
[
"8633b7136946ab2ae2e16062503fe51c2aac8c38"
] |
[
"pyro/distributions/transforms/planar.py"
] |
[
"# Copyright (c) 2017-2019 Uber Technologies, Inc.\n# SPDX-License-Identifier: Apache-2.0\n\nimport math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.distributions import Transform, constraints\n\nfrom pyro.distributions.conditional import ConditionalTransformModule\nfrom pyro.distributions.torch_transform import TransformModule\nfrom pyro.distributions.util import copy_docs_from\nfrom pyro.nn import DenseNN\n\n\n@copy_docs_from(Transform)\nclass ConditionedPlanar(Transform):\n domain = constraints.real\n codomain = constraints.real\n bijective = True\n event_dim = 1\n\n def __init__(self, bias=None, u=None, w=None):\n super().__init__(cache_size=1)\n self.bias = bias\n self.u = u\n self.w = w\n self._cached_logDetJ = None\n\n # This method ensures that torch(u_hat, w) > -1, required for invertibility\n def u_hat(self, u, w):\n alpha = torch.matmul(u.unsqueeze(-2), w.unsqueeze(-1)).squeeze(-1)\n a_prime = -1 + F.softplus(alpha)\n return u + (a_prime - alpha) * w.div(w.pow(2).sum(dim=-1, keepdim=True))\n\n def _call(self, x):\n \"\"\"\n :param x: the input into the bijection\n :type x: torch.Tensor\n Invokes the bijection x => y; in the prototypical context of a\n :class:`~pyro.distributions.TransformedDistribution` `x` is a sample from\n the base distribution (or the output of a previous transform)\n \"\"\"\n\n # x ~ (batch_size, dim_size, 1)\n # w ~ (batch_size, 1, dim_size)\n # bias ~ (batch_size, 1)\n act = torch.tanh(torch.matmul(self.w.unsqueeze(-2), x.unsqueeze(-1)).squeeze(-1) + self.bias)\n u_hat = self.u_hat(self.u, self.w)\n y = x + u_hat * act\n\n psi_z = (1. - act.pow(2)) * self.w\n self._cached_logDetJ = torch.log(\n torch.abs(1 + torch.matmul(psi_z.unsqueeze(-2), u_hat.unsqueeze(-1)).squeeze(-1).squeeze(-1)))\n\n return y\n\n def _inverse(self, y):\n \"\"\"\n :param y: the output of the bijection\n :type y: torch.Tensor\n Inverts y => x. As noted above, this implementation is incapable of\n inverting arbitrary values `y`; rather it assumes `y` is the result of a\n previously computed application of the bijector to some `x` (which was\n cached on the forward call)\n \"\"\"\n\n raise KeyError(\"ConditionedPlanar object expected to find key in intermediates cache but didn't\")\n\n def log_abs_det_jacobian(self, x, y):\n \"\"\"\n Calculates the elementwise determinant of the log Jacobian\n \"\"\"\n x_old, y_old = self._cached_x_y\n if x is not x_old or y is not y_old:\n # This call to the parent class Transform will update the cache\n # as well as calling self._call and recalculating y and log_detJ\n self(x)\n\n return self._cached_logDetJ\n\n\n@copy_docs_from(ConditionedPlanar)\nclass Planar(ConditionedPlanar, TransformModule):\n \"\"\"\n A 'planar' bijective transform with equation,\n\n :math:`\\\\mathbf{y} = \\\\mathbf{x} + \\\\mathbf{u}\\\\tanh(\\\\mathbf{w}^T\\\\mathbf{z}+b)`\n\n where :math:`\\\\mathbf{x}` are the inputs, :math:`\\\\mathbf{y}` are the outputs,\n and the learnable parameters are :math:`b\\\\in\\\\mathbb{R}`,\n :math:`\\\\mathbf{u}\\\\in\\\\mathbb{R}^D`, :math:`\\\\mathbf{w}\\\\in\\\\mathbb{R}^D` for\n input dimension :math:`D`. For this to be an invertible transformation, the\n condition :math:`\\\\mathbf{w}^T\\\\mathbf{u}>-1` is enforced.\n\n Together with :class:`~pyro.distributions.TransformedDistribution` this provides\n a way to create richer variational approximations.\n\n Example usage:\n\n >>> base_dist = dist.Normal(torch.zeros(10), torch.ones(10))\n >>> transform = Planar(10)\n >>> pyro.module(\"my_transform\", transform) # doctest: +SKIP\n >>> flow_dist = dist.TransformedDistribution(base_dist, [transform])\n >>> flow_dist.sample() # doctest: +SKIP\n\n The inverse of this transform does not possess an analytical solution and is\n left unimplemented. However, the inverse is cached when the forward operation is\n called during sampling, and so samples drawn using the planar transform can be\n scored.\n\n :param input_dim: the dimension of the input (and output) variable.\n :type input_dim: int\n\n References:\n\n [1] Danilo Jimenez Rezende, Shakir Mohamed. Variational Inference with\n Normalizing Flows. [arXiv:1505.05770]\n\n \"\"\"\n\n domain = constraints.real\n codomain = constraints.real\n bijective = True\n event_dim = 1\n\n def __init__(self, input_dim):\n super().__init__()\n\n self.bias = nn.Parameter(torch.Tensor(1,))\n self.u = nn.Parameter(torch.Tensor(input_dim,))\n self.w = nn.Parameter(torch.Tensor(input_dim,))\n self.input_dim = input_dim\n self.reset_parameters()\n\n def reset_parameters(self):\n stdv = 1. / math.sqrt(self.u.size(0))\n self.w.data.uniform_(-stdv, stdv)\n self.u.data.uniform_(-stdv, stdv)\n self.bias.data.zero_()\n\n\n@copy_docs_from(ConditionalTransformModule)\nclass ConditionalPlanar(ConditionalTransformModule):\n \"\"\"\n A conditional 'planar' bijective transform using the equation,\n\n :math:`\\\\mathbf{y} = \\\\mathbf{x} + \\\\mathbf{u}\\\\tanh(\\\\mathbf{w}^T\\\\mathbf{z}+b)`\n\n where :math:`\\\\mathbf{x}` are the inputs with dimension :math:`D`,\n :math:`\\\\mathbf{y}` are the outputs, and the pseudo-parameters\n :math:`b\\\\in\\\\mathbb{R}`, :math:`\\\\mathbf{u}\\\\in\\\\mathbb{R}^D`, and\n :math:`\\\\mathbf{w}\\\\in\\\\mathbb{R}^D` are the output of a function, e.g. a NN,\n with input :math:`z\\\\in\\\\mathbb{R}^{M}` representing the context variable to\n condition on. For this to be an invertible transformation, the condition\n :math:`\\\\mathbf{w}^T\\\\mathbf{u}>-1` is enforced.\n\n Together with :class:`~pyro.distributions.ConditionalTransformedDistribution`\n this provides a way to create richer variational approximations.\n\n Example usage:\n\n >>> from pyro.nn.dense_nn import DenseNN\n >>> input_dim = 10\n >>> context_dim = 5\n >>> batch_size = 3\n >>> base_dist = dist.Normal(torch.zeros(input_dim), torch.ones(input_dim))\n >>> param_dims = [1, input_dim, input_dim]\n >>> hypernet = DenseNN(context_dim, [50, 50], param_dims)\n >>> transform = ConditionalPlanar(hypernet)\n >>> z = torch.rand(batch_size, context_dim)\n >>> flow_dist = dist.ConditionalTransformedDistribution(base_dist,\n ... [transform]).condition(z)\n >>> flow_dist.sample(sample_shape=torch.Size([batch_size])) # doctest: +SKIP\n\n The inverse of this transform does not possess an analytical solution and is\n left unimplemented. However, the inverse is cached when the forward operation is\n called during sampling, and so samples drawn using the planar transform can be\n scored.\n\n :param nn: a function inputting the context variable and outputting a triplet of\n real-valued parameters of dimensions :math:`(1, D, D)`.\n :type nn: callable\n\n References:\n [1] Variational Inference with Normalizing Flows [arXiv:1505.05770]\n Danilo Jimenez Rezende, Shakir Mohamed\n\n \"\"\"\n\n domain = constraints.real\n codomain = constraints.real\n bijective = True\n event_dim = 1\n\n def __init__(self, nn):\n super().__init__()\n self.nn = nn\n\n def condition(self, context):\n bias, u, w = self.nn(context)\n return ConditionedPlanar(bias, u, w)\n\n\ndef planar(input_dim):\n \"\"\"\n A helper function to create a :class:`~pyro.distributions.transforms.Planar`\n object for consistency with other helpers.\n\n :param input_dim: Dimension of input variable\n :type input_dim: int\n\n \"\"\"\n\n return Planar(input_dim)\n\n\ndef conditional_planar(input_dim, context_dim, hidden_dims=None):\n \"\"\"\n A helper function to create a\n :class:`~pyro.distributions.transforms.ConditionalPlanar` object that takes care\n of constructing a dense network with the correct input/output dimensions.\n\n :param input_dim: Dimension of input variable\n :type input_dim: int\n :param context_dim: Dimension of context variable\n :type context_dim: int\n :param hidden_dims: The desired hidden dimensions of the dense network. Defaults\n to using [input_dim * 10, input_dim * 10]\n :type hidden_dims: list[int]\n\n \"\"\"\n\n if hidden_dims is None:\n hidden_dims = [input_dim * 10, input_dim * 10]\n nn = DenseNN(context_dim, hidden_dims, param_dims=[1, input_dim, input_dim])\n return ConditionalPlanar(nn)\n"
] |
[
[
"torch.Tensor",
"torch.nn.functional.softplus"
]
] |
ahjeongseo/MASN---Attend-What-You-Need-Motion-Appearance-Synergistic-Networks-for-Video-Question-Answering
|
[
"5ca3fc80cf37f7b6124070b1aae5bc599db8fa29"
] |
[
"embed_loss.py"
] |
[
"# --------------------------------------------------------\n# This code is modified from Jumpin2's repository.\n# https://github.com/Jumpin2/HGA\n# --------------------------------------------------------\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n# __all__ = ['MultipleChoiceLoss', 'CountLoss']\n\n\nclass MultipleChoiceLoss(nn.Module):\n\n def __init__(self, num_option=5, margin=1, size_average=True):\n super(MultipleChoiceLoss, self).__init__()\n self.margin = margin\n self.num_option = num_option\n self.size_average = size_average\n\n # score is N x C\n\n def forward(self, score, target):\n N = score.size(0)\n C = score.size(1)\n assert self.num_option == C\n\n loss = torch.tensor(0.0).cuda()\n zero = torch.tensor(0.0).cuda()\n\n cnt = 0\n #print(N,C)\n for b in range(N):\n # loop over incorrect answer, check if correct answer's score larger than a margin\n c0 = target[b]\n for c in range(C):\n if c == c0:\n continue\n\n # right class and wrong class should have score difference larger than a margin\n # see formula under paper Eq(4)\n loss += torch.max(zero, 1.0 + score[b, c] - score[b, c0])\n cnt += 1\n\n if cnt == 0:\n return loss\n\n return loss / cnt if self.size_average else loss\n"
] |
[
[
"torch.tensor",
"torch.max"
]
] |
ZivonZhang/mmdetection
|
[
"81272a42e606e5ab9d2ec13e91a39e31f78a61b4"
] |
[
"mmdet/apis/inference.py"
] |
[
"import mmcv\nimport numpy as np\nimport pycocotools.mask as maskUtils\nimport torch\n\nfrom mmdet.core import get_classes\nfrom mmdet.datasets import to_tensor\nfrom mmdet.datasets.transforms import ImageTransform\n\n\ndef _prepare_data(img, img_transform, cfg, device):\n ori_shape = img.shape\n img, img_shape, pad_shape, scale_factor = img_transform(\n img,\n scale=cfg.data.test.img_scale,\n keep_ratio=cfg.data.test.get('resize_keep_ratio', True))\n img = to_tensor(img).to(device).unsqueeze(0)\n img_meta = [\n dict(\n ori_shape=ori_shape,\n img_shape=img_shape,\n pad_shape=pad_shape,\n scale_factor=scale_factor,\n flip=False)\n ]\n return dict(img=[img], img_meta=[img_meta])\n\n\ndef _inference_single(model, img, img_transform, cfg, device):\n img = mmcv.imread(img)\n data = _prepare_data(img, img_transform, cfg, device)\n with torch.no_grad():\n result = model(return_loss=False, rescale=True, **data)\n return result\n\n\ndef _inference_generator(model, imgs, img_transform, cfg, device):\n for img in imgs:\n yield _inference_single(model, img, img_transform, cfg, device)\n\n\ndef inference_detector(model, imgs, cfg, device='cuda:0'):\n img_transform = ImageTransform(\n size_divisor=cfg.data.test.size_divisor, **cfg.img_norm_cfg)\n model = model.to(device)\n model.eval()\n\n if not isinstance(imgs, list):\n return _inference_single(model, imgs, img_transform, cfg, device)\n else:\n return _inference_generator(model, imgs, img_transform, cfg, device)\n\n\ndef show_result(img, result, dataset='coco', score_thr=0.3, out_file=None):\n img = mmcv.imread(img)\n class_names = get_classes(dataset)\n if isinstance(result, tuple):\n bbox_result, segm_result = result\n else:\n bbox_result, segm_result = result, None\n bboxes = np.vstack(bbox_result)\n # draw segmentation masks\n if segm_result is not None:\n segms = mmcv.concat_list(segm_result)\n inds = np.where(bboxes[:, -1] > score_thr)[0]\n for i in inds:\n color_mask = np.random.randint(\n 0, 256, (1, 3), dtype=np.uint8)\n mask = maskUtils.decode(segms[i]).astype(np.bool)\n img[mask] = img[mask] * 0.5 + color_mask * 0.5\n # draw bounding boxes\n labels = [\n np.full(bbox.shape[0], i, dtype=np.int32)\n for i, bbox in enumerate(bbox_result)\n ]\n labels = np.concatenate(labels)\n mmcv.imshow_det_bboxes(\n img.copy(),\n bboxes,\n labels,\n class_names=class_names,\n score_thr=score_thr,\n show=out_file is None,\n out_file=out_file)\n"
] |
[
[
"numpy.concatenate",
"numpy.full",
"torch.no_grad",
"numpy.where",
"numpy.random.randint",
"numpy.vstack"
]
] |
RaphaelDELAIR/traffic
|
[
"47591f39f83e22aff65ae06987bce238cd2dd353",
"47591f39f83e22aff65ae06987bce238cd2dd353",
"47591f39f83e22aff65ae06987bce238cd2dd353"
] |
[
"traffic/core/traffic.py",
"traffic/core/flight.py",
"traffic/algorithms/navigation.py"
] |
[
"import logging\nimport warnings\nfrom datetime import timedelta\nfrom pathlib import Path\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Callable,\n Dict,\n Iterable,\n Iterator,\n List,\n Optional,\n Set,\n Type,\n TypeVar,\n Union,\n overload,\n)\n\nimport pandas as pd\nimport pyproj\nfrom shapely.geometry import Polygon, base\n\nfrom ..algorithms.clustering import Clustering, centroid\nfrom ..algorithms.cpa import closest_point_of_approach\nfrom ..core.cache import property_cache\nfrom ..core.time import time_or_delta, timelike, to_datetime\nfrom .flight import Flight, attrgetter_duration\nfrom .lazy import LazyTraffic, lazy_evaluation\nfrom .mixins import GeographyMixin, HBoxMixin, PointMixin\nfrom .sv import StateVectors\n\nif TYPE_CHECKING:\n from cartopy import crs\n from cartopy.mpl.geoaxes import GeoAxesSubplot\n from matplotlib.artist import Artist\n\n from ..algorithms.clustering import ( # noqa: F401\n ClusteringProtocol,\n TransformerProtocol,\n )\n from ..algorithms.cpa import CPA # noqa: F401\n from .airspace import Airspace # noqa: F401\n\n\n# https://github.com/python/mypy/issues/2511\nTrafficTypeVar = TypeVar(\"TrafficTypeVar\", bound=\"Traffic\")\n\n# The thing is that Iterable[str] causes issue sometimes...\nIterStr = Union[List[str], Set[str]]\n\n\nclass Traffic(HBoxMixin, GeographyMixin):\n \"\"\"\n\n Traffic is the abstraction representing a collection of `Flights\n <traffic.core.flight.html>`_. When Flight objects are summed up, the\n resulting structure is a Traffic.\n\n Data is all flattened into one single pandas DataFrame and methods are\n provided to properly access (with the bracket notation) and iterate on each\n Flight in the structure.\n\n On top of basic methods and properties (`aircraft\n <traffic.core.Traffic.aircraft>`_, `callsigns\n <traffic.core.Traffic.callsigns>`_, `flight_ids\n <traffic.core.Traffic.flight_ids>`_, `start_time\n <traffic.core.Traffic.start_time>`_, `end_time\n <traffic.core.Traffic.end_time>`_) and data preprocessing (most methods\n available on Flight), more complex algorithms like `closest point of\n approach <#traffic.core.Traffic.closest_point_of_approach>`_ and\n `clustering <#traffic.core.Traffic.clustering>`_ (more to come) are\n available.\n\n .. note::\n\n When methods need to be chained on each trajectory contained in the\n collection, **lazy iteration and evaluation** is in place. This means\n that applying such a method on a Traffic structure will only stack\n operations without evaluating them.\n\n .. autoclass:: traffic.core.lazy.LazyTraffic()\n :members: eval\n\n .. tip::\n Sample traffic structures are provided for testing purposes in module\n ``traffic.data.samples``\n\n \"\"\"\n\n __slots__ = (\"data\",)\n\n @classmethod\n def from_flights(\n cls, flights: Iterable[Optional[Flight]]\n ) -> Optional[\"Traffic\"]:\n \"\"\"\n Creates a Traffic structure from all flights passed as an\n iterator or iterable.\n \"\"\"\n cumul = [flight.data for flight in flights if flight is not None]\n if len(cumul) == 0:\n return None\n return cls(pd.concat(cumul, sort=False))\n\n @classmethod\n def from_file(\n cls: Type[TrafficTypeVar], filename: Union[Path, str], **kwargs\n ) -> Optional[TrafficTypeVar]:\n\n tentative = super().from_file(filename, **kwargs)\n\n if tentative is not None:\n rename_columns = {\n \"time\": \"timestamp\",\n \"lat\": \"latitude\",\n \"lon\": \"longitude\",\n \"lng\": \"longitude\",\n \"long\": \"longitude\",\n # speeds\n \"velocity\": \"groundspeed\",\n \"ground_speed\": \"groundspeed\",\n \"ias\": \"IAS\",\n \"tas\": \"TAS\",\n \"mach\": \"Mach\",\n # vertical rate\n \"vertrate\": \"vertical_rate\",\n \"vertical_speed\": \"vertical_rate\",\n \"roc\": \"vertical_rate\",\n # let's just make baroaltitude the altitude by default\n \"baro_altitude\": \"altitude\",\n \"baroaltitude\": \"altitude\",\n \"geo_altitude\": \"geoaltitude\",\n # synonyms\n \"departure\": \"origin\",\n \"arrival\": \"destination\",\n }\n\n if (\n \"baroaltitude\" in tentative.data.columns\n or \"baro_altitude\" in tentative.data.columns\n ):\n # for retrocompatibility\n rename_columns[\"altitude\"] = \"geoaltitude\"\n\n if (\n \"heading\" in tentative.data.columns\n and \"track\" not in tentative.data.columns\n ):\n # that's a common confusion in data, let's assume that\n rename_columns[\"heading\"] = \"track\"\n\n return tentative.rename(columns=rename_columns)\n\n path = Path(filename)\n logging.warning(f\"{path.suffixes} extension is not supported\")\n return None\n\n # --- Special methods ---\n # operators + (union), & (intersection), - (difference), ^ (xor)\n\n def __add__(self, other) -> \"Traffic\":\n # useful for compatibility with sum() function\n if other == 0:\n return self\n return self.__class__(pd.concat([self.data, other.data], sort=False))\n\n def __radd__(self, other) -> \"Traffic\":\n return self + other\n\n def __and__(self, other: \"Traffic\") -> Optional[\"Traffic\"]:\n if not isinstance(other, Traffic):\n raise RuntimeError(\n \"Operator `&` is only applicable between Traffic structures.\"\n )\n list_id = other.flight_ids\n if list_id is None or self.flight_ids is None:\n raise RuntimeError(\n \"No flight_id is provided in the given Traffic structures.\"\n )\n df = self.data.query(\"flight_id in @list_id\")\n if df.shape[0] == 0:\n return None\n return self.__class__(df)\n\n def __sub__(self, other: \"Traffic\") -> Optional[\"Traffic\"]:\n # set difference based on flight_id\n if not isinstance(other, Traffic):\n raise RuntimeError(\n \"Operator `-` is only applicable between Traffic structures.\"\n )\n list_id = other.flight_ids\n if list_id is None or self.flight_ids is None:\n raise RuntimeError(\n \"No flight_id is provided in the given Traffic structures.\"\n )\n df = self.data.query(\"flight_id not in @list_id\")\n if df.shape[0] == 0:\n return None\n return self.__class__(df)\n\n def __xor__(self, other: \"Traffic\") -> Optional[\"Traffic\"]:\n left = self - other\n right = other - self\n if left is None:\n return right\n if right is None:\n return left\n return right + left\n\n def _getSeries(self, index: pd.Series) -> Optional[Flight]:\n\n p_callsign = hasattr(index, \"callsign\")\n p_icao24 = hasattr(index, \"icao24\")\n\n if p_callsign or p_icao24:\n query = []\n if p_callsign:\n query.append(f\"callsign == '{index.callsign}'\")\n if p_icao24:\n query.append(f\"icao24 == '{index.icao24}'\")\n\n df = self.data.query(\n query[0] if len(query) == 1 else \" and \".join(query)\n )\n if df.shape[0] == 0:\n return None\n\n flight: Optional[Flight] = Flight(df)\n\n if flight is not None and hasattr(index, \"firstSeen\"):\n # refers to OpenSky REST API\n flight = flight.after(index.firstSeen)\n if flight is not None and hasattr(index, \"lastSeen\"):\n # refers to OpenSky REST API\n flight = flight.before(index.lastSeen)\n\n if flight is not None and hasattr(index, \"start\"): # more natural\n flight = flight.after(index.start)\n if flight is not None and hasattr(index, \"stop\"): # more natural\n flight = flight.before(index.stop)\n\n return flight\n\n return None\n\n @overload\n def __getitem__(self, index: int) -> Optional[Flight]:\n ...\n\n @overload\n def __getitem__(self, index: str) -> Optional[Flight]: # noqa: F811\n ...\n\n @overload\n def __getitem__(self, index: slice) -> Optional[\"Traffic\"]: # noqa: F811\n ...\n\n @overload\n def __getitem__(self, index: IterStr) -> Optional[\"Traffic\"]: # noqa: F811\n ...\n\n def __getitem__( # noqa: F811\n self, index\n ) -> Union[None, Flight, \"Traffic\"]:\n\n if isinstance(index, pd.Series):\n return self._getSeries(index)\n\n if isinstance(index, pd.DataFrame):\n return self.__class__.from_flights(\n flight for flight in self.iterate(by=index)\n )\n\n if isinstance(index, int):\n for i, flight in enumerate(self.iterate()):\n if i == index:\n return flight\n return None\n\n if isinstance(index, slice):\n max_size = index.stop if index.stop is not None else len(self)\n indices = list(range(max_size)[index])\n return self.__class__.from_flights(\n flight\n for i, flight in enumerate(self.iterate())\n if i in indices\n )\n\n if not isinstance(index, str): # List[str], Set[str], Iterable[str]\n logging.debug(\"Selecting flights from a list of identifiers\")\n subset = repr(list(index))\n query_str = f\"callsign in {subset} or icao24 in {subset}\"\n if \"flight_id\" in self.data.columns:\n return self.query(f\"flight_id in {subset} or \" + query_str)\n else:\n return self.query(query_str)\n\n query_str = f\"callsign == '{index}' or icao24 == '{index}'\"\n if \"flight_id\" in self.data.columns:\n df = self.data.query(f\"flight_id == '{index}' or \" + query_str)\n else:\n df = self.data.query(query_str)\n\n if df.shape[0] > 0:\n return Flight(df)\n\n return None\n\n def _ipython_key_completions_(self) -> Set[str]:\n if self.flight_ids is not None:\n return self.flight_ids\n return {*self.aircraft, *self.callsigns}\n\n def iterate(\n self,\n by: Union[str, pd.DataFrame, None] = None,\n nb_flights: Optional[int] = None,\n ) -> Iterator[Flight]:\n \"\"\"\n Iterates over Flights contained in the Traffic structure.\n\n Default iteration calls this method with default arguments:\n\n >>> for flight in t:\n ... pass\n\n is equivalent to:\n\n >>> for flight in t.iterate():\n ... pass\n\n However the it may be beneficial to specify the `by` parameter:\n\n - as a pandas DataFrame with callsign and or icao24 columns, it\n defines a subset of Flights to select.\n - as a a string, `by` defines the minimum time range without\n data for a flight.\n \"\"\"\n\n if isinstance(by, pd.DataFrame):\n for i, (_, line) in enumerate(by.iterrows()):\n if nb_flights is None or i < nb_flights:\n flight = self[line]\n if flight is not None:\n yield flight\n return\n\n if \"flight_id\" in self.data.columns:\n for i, (_, df) in enumerate(self.data.groupby(\"flight_id\")):\n if nb_flights is None or i < nb_flights:\n yield Flight(df)\n else:\n for i, (_, df) in enumerate(\n self.data.sort_values(\"timestamp\").groupby(\n [\"icao24\", \"callsign\"]\n )\n ):\n if nb_flights is None or i < nb_flights:\n yield from Flight(df).split(\n by if by is not None else \"10 minutes\"\n )\n\n def iterate_lazy(\n self,\n iterate_kw: Optional[Dict[str, Any]] = None,\n tqdm_kw: Optional[Dict[str, Any]] = None,\n ) -> LazyTraffic:\n \"\"\"\n Triggers a lazy iteration on the Traffic structure.\n\n Default iteration calls this method with default arguments:\n\n >>> t.filter()\n\n is equivalent to:\n\n >>> t.iterate_lazy().filter()\n\n However the it may be beneficial to specify the `by` parameter:\n\n - as a pandas DataFrame with callsign and or icao24 columns, it\n defines a subset of Flights to select.\n - as a a string, `by` defines the minimum time range without\n data for a flight.\n\n You may also select parameters to pass to a tentative tqdm\n progressbar.\n \"\"\"\n if iterate_kw is None:\n iterate_kw = {}\n if tqdm_kw is None:\n tqdm_kw = {}\n return LazyTraffic(self, [], iterate_kw=iterate_kw, tqdm_kw=tqdm_kw)\n\n def __iter__(self) -> Iterator[Flight]:\n yield from self.iterate()\n\n @property_cache\n def length(self):\n ids_ = self.flight_ids\n if ids_ is not None:\n return len(ids_)\n return sum(1 for _ in self)\n\n def __len__(self):\n return self.length\n\n def __repr__(self) -> str:\n basic_stats = self.basic_stats\n shape = basic_stats.shape[0]\n if shape > 10:\n # stylers are not efficient on big dataframes...\n basic_stats = basic_stats.head(10)\n return basic_stats.__repr__()\n\n def _repr_html_(self) -> str:\n basic_stats = self.basic_stats\n shape = basic_stats.shape[0]\n if shape > 10:\n # stylers are not efficient on big dataframes...\n basic_stats = basic_stats.head(10)\n styler = basic_stats.style.bar(align=\"mid\", color=\"#5fba7d\")\n rep = f\"<b>Traffic with {shape} identifiers</b>\"\n return rep + styler._repr_html_()\n\n def aircraft_data(self) -> \"Traffic\":\n \"\"\"\n Add registration and aircraft typecode based on the `aircraft database\n <aircraft.html>`_.\n\n \"\"\"\n from ..data import aircraft\n\n return self.merge(\n aircraft.data[[\"icao24\", \"registration\", \"typecode\"]]\n .query('typecode != \"\"')\n .drop_duplicates(\"icao24\"),\n on=\"icao24\",\n how=\"left\",\n )\n\n # -- Methods for lazy evaluation, delegated to Flight --\n\n @lazy_evaluation()\n def filter_if(self, *args, **kwargs):\n ...\n\n @lazy_evaluation()\n def has(self, *args, **kwargs):\n ...\n\n @lazy_evaluation()\n def all(self, *args, **kwargs):\n ...\n\n @lazy_evaluation()\n def next(self, *args, **kwargs):\n ...\n\n @lazy_evaluation()\n def final(self, *args, **kwargs):\n ...\n\n @lazy_evaluation()\n def resample(self, rule: Union[str, int] = \"1s\"):\n ...\n\n @lazy_evaluation()\n def filter(\n self,\n strategy: Callable[\n [pd.DataFrame], pd.DataFrame\n ] = lambda x: x.bfill().ffill(),\n **kwargs,\n ):\n ...\n\n @lazy_evaluation()\n def filter_position(self, cascades: int = 2):\n ...\n\n @lazy_evaluation()\n def unwrap(self, features: Union[None, str, List[str]] = None):\n ...\n\n @lazy_evaluation(idx_name=\"idx\")\n def assign_id(self, name: str = \"{self.callsign}_{idx:>03}\", idx: int = 0):\n \"\"\"Assigns a `flight_id` to trajectories present in the structure.\n\n The heuristics with iterate on flights based on ``flight_id`` (if the\n feature is present) or of ``icao24``, ``callsign`` and intervals of time\n without recorded data.\n\n The flight_id is created according to a pattern passed in parameter,\n by default based on the callsign and an incremented index.\n \"\"\"\n ...\n\n @lazy_evaluation()\n def clip(self, shape: Union[\"Airspace\", base.BaseGeometry]):\n ...\n\n @lazy_evaluation()\n def intersects(self, shape: Union[\"Airspace\", base.BaseGeometry]) -> bool:\n ...\n\n @lazy_evaluation()\n def simplify(\n self,\n tolerance: float,\n altitude: Optional[str] = None,\n z_factor: float = 3.048,\n ):\n ...\n\n @lazy_evaluation()\n def query_opensky(self):\n ...\n\n @lazy_evaluation()\n def query_ehs(self, data, failure_mode, propressbar):\n ...\n\n @lazy_evaluation()\n def first(self, **kwargs):\n ...\n\n @lazy_evaluation()\n def last(self, **kwargs):\n ...\n\n @lazy_evaluation()\n def feature_gt(\n self,\n feature: Union[str, Callable[[\"Flight\"], Any]],\n value: Any,\n strict: bool = True,\n ):\n ...\n\n @lazy_evaluation()\n def feature_lt(\n self,\n feature: Union[str, Callable[[\"Flight\"], Any]],\n value: Any,\n strict: bool = True,\n ):\n ...\n\n @lazy_evaluation()\n def shorter_than(\n self, value: Union[str, timedelta, pd.Timedelta], strict: bool = True\n ):\n ...\n\n @lazy_evaluation()\n def longer_than(\n self, value: Union[str, timedelta, pd.Timedelta], strict: bool = True\n ):\n ...\n\n @lazy_evaluation()\n def max_split(\n self,\n value: Union[int, str] = \"10T\",\n unit: Optional[str] = None,\n key: Callable[[Optional[\"Flight\"]], Any] = attrgetter_duration,\n ):\n ...\n\n @lazy_evaluation()\n def diff(self, features: Union[str, List[str]], **kwargs):\n ...\n\n @lazy_evaluation()\n def apply_segments(\n self, fun: Callable[..., \"LazyTraffic\"], name: str, *args, **kwargs\n ):\n ...\n\n @lazy_evaluation()\n def apply_time(self, freq=\"1T\", merge=True, **kwargs):\n ...\n\n @lazy_evaluation()\n def agg_time(self, freq=\"1T\", merge=True, **kwargs):\n ...\n\n @lazy_evaluation()\n def cumulative_distance(\n self, compute_gs: bool = True, compute_track: bool = True, **kwargs\n ):\n ...\n\n @lazy_evaluation()\n def compute_wind(self):\n ...\n\n @lazy_evaluation()\n def bearing(\n self,\n other: Union[PointMixin],\n column_name: str = \"bearing\",\n ):\n ...\n\n @lazy_evaluation()\n def distance(\n self,\n other: Union[\"Airspace\", Polygon, PointMixin],\n column_name: str = \"distance\",\n ):\n ...\n\n @lazy_evaluation()\n def landing_at(self, airport: str) -> bool:\n ...\n\n @lazy_evaluation()\n def takeoff_from(self, airport: str) -> bool:\n ...\n\n # -- Methods with a Traffic implementation, otherwise delegated to Flight\n\n @lazy_evaluation(default=True)\n def before(self, ts: timelike, strict: bool = True) -> Optional[\"Traffic\"]:\n return self.between(self.start_time, ts, strict)\n\n @lazy_evaluation(default=True)\n def after(self, ts: timelike, strict: bool = True) -> Optional[\"Traffic\"]:\n return self.between(ts, self.end_time, strict)\n\n @lazy_evaluation(default=True)\n def between(\n self, start: timelike, stop: time_or_delta, strict: bool = True\n ) -> Optional[\"Traffic\"]:\n\n # Corner cases when start or stop are None or NaT\n if start is None or start != start:\n return self.before(stop, strict=strict)\n\n if stop is None or stop != stop:\n return self.after(start, strict=strict)\n\n start = to_datetime(start)\n\n if isinstance(stop, timedelta):\n stop = start + stop\n else:\n stop = to_datetime(stop)\n\n # full call is necessary to keep @before and @after as local variables\n # return self.query('@before < timestamp < @after') => not valid\n if strict:\n df = self.data.query(\"@start < timestamp < @stop\")\n else:\n df = self.data.query(\"@start <= timestamp <= @stop\")\n\n if df.shape[0] == 0:\n return None\n\n return self.__class__(df)\n\n @lazy_evaluation(default=True)\n def airborne(self) -> Optional[\"Traffic\"]:\n \"\"\"Returns the airborne part of the Traffic.\n\n The airborne part is determined by an ``onground`` flag or null values\n in the altitude column.\n \"\"\"\n if \"onground\" in self.data.columns and self.data.onground.dtype == bool:\n return self.query(\"not onground and altitude == altitude\")\n else:\n return self.query(\"altitude == altitude\")\n\n @lazy_evaluation(default=True)\n def onground(self) -> Optional[\"Traffic\"]:\n if \"altitude\" not in self.data.columns:\n return self\n if \"onground\" in self.data.columns and self.data.onground.dtype == bool:\n return self.query(\"onground or altitude != altitude\")\n else:\n return self.query(\"altitude != altitude\")\n\n # --- Properties ---\n\n @property_cache\n def start_time(self) -> pd.Timestamp:\n \"\"\"Returns the earliest timestamp in the DataFrame.\"\"\"\n return self.data.timestamp.min()\n\n @property_cache\n def end_time(self) -> pd.Timestamp:\n \"\"\"Returns the latest timestamp in the DataFrame.\"\"\"\n return self.data.timestamp.max()\n\n @property_cache\n def callsigns(self) -> Set[str]:\n \"\"\"Return all the different callsigns in the DataFrame\"\"\"\n sub = self.data.query(\"callsign == callsign\")\n if sub.shape[0] == 0:\n return set()\n return set(sub.callsign)\n\n @property_cache\n def aircraft(self) -> Set[str]:\n \"\"\"Return all the different icao24 aircraft ids in the DataFrame\"\"\"\n logging.warning(\"Use .icao24\", DeprecationWarning)\n return set(self.data.icao24)\n\n @property_cache\n def icao24(self) -> Set[str]:\n \"\"\"Return all the different icao24 aircraft ids in the DataFrame\"\"\"\n return set(self.data.icao24)\n\n @property_cache\n def flight_ids(self) -> Optional[List[str]]:\n \"\"\"Return all the different flight_id in the DataFrame\"\"\"\n if \"flight_id\" in self.data.columns:\n return list(flight.flight_id for flight in self) # type: ignore\n return None\n\n # --- Easy work ---\n\n def at(self, time: Optional[timelike] = None) -> \"StateVectors\":\n if time is not None:\n time = to_datetime(time)\n list_flights = [\n flight.at(time)\n for flight in self\n if flight.start <= time <= flight.stop\n ]\n else:\n list_flights = [flight.at() for flight in self]\n return StateVectors(\n pd.DataFrame.from_records(\n [s for s in list_flights if s is not None]\n ).assign(\n # attribute 'name' refers to the index, i.e. 'timestamp'\n timestamp=[s.name for s in list_flights if s is not None]\n )\n )\n\n @property_cache\n def basic_stats(self) -> pd.DataFrame:\n key = [\"icao24\", \"callsign\"] if self.flight_ids is None else \"flight_id\"\n return (\n self.data.groupby(key)[[\"timestamp\"]]\n .count()\n .sort_values(\"timestamp\", ascending=False)\n .rename(columns={\"timestamp\": \"count\"})\n )\n\n def summary(\n self,\n attributes: List[str],\n iterate_kw: Optional[Dict[str, Any]] = None,\n ) -> pd.DataFrame:\n \"\"\"Returns a summary of the current Traffic structure containing\n featured attributes.\n\n Example usage:\n\n >>> t.summary(['icao24', 'start', 'stop', 'duration'])\n\n Consider monkey-patching properties to the Flight class if you need more\n information in your summary DataFrame.\n\n \"\"\"\n if iterate_kw is None:\n iterate_kw = dict()\n return pd.DataFrame.from_records(\n dict((key, getattr(flight, key)) for key in attributes)\n for flight in self.iterate(**iterate_kw)\n )\n\n def geoencode(self, *args, **kwargs):\n \"\"\"\n .. danger::\n This method is not implemented.\n \"\"\"\n raise NotImplementedError\n\n def plot(\n self, ax: \"GeoAxesSubplot\", nb_flights: Optional[int] = None, **kwargs\n ) -> None: # coverage: ignore\n \"\"\"Plots each trajectory on a Matplotlib axis.\n\n Each Flight supports Cartopy axis as well with automatic projection. If\n no projection is provided, a default `PlateCarree\n <https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#platecarree>`_\n is applied.\n\n Example usage:\n\n >>> from traffic.drawing import EuroPP\n >>> fig, ax = plt.subplots(1, subplot_kw=dict(projection=EuroPP()))\n >>> t.plot(ax, alpha=.5)\n\n \"\"\"\n params: Dict[str, Any] = {}\n if nb_flights is not None:\n warnings.warn(\n \"nb_flights will disappear in future versions. \"\n \"Use indexing [:nb_flights] before plotting instead\",\n DeprecationWarning,\n )\n if sum(1 for _ in zip(range(8), self)) == 8:\n params[\"color\"] = \"#aaaaaa\"\n params[\"linewidth\"] = 1\n params[\"alpha\"] = 0.8\n kwargs = {**params, **kwargs} # precedence of kwargs over params\n for i, flight in enumerate(self):\n if nb_flights is None or i < nb_flights:\n flight.plot(ax, **kwargs)\n\n def agg_latlon(\n self, resolution: Union[Dict[str, float], None] = None, **kwargs\n ) -> pd.DataFrame:\n \"\"\"Aggregates values of a traffic over a grid of lat/lon.\n\n The resolution of the grid is passed as a dictionary parameter.\n By default, the grid is made by rounding latitudes and longitudes to\n the nearest integer values. ``dict(latitude=2, longitude=4)``\n will take 2 values per integer latitude intervals (43, 43.5, 44, ...)\n and 4 values per integer longitude intervals (1, 1.25, 1.5, 1.75, ...).\n\n The kwargs specifies how to aggregate values:\n\n - ``altitude=\"mean\"`` would average all values in the given cell;\n - ``timestamp=\"count\"`` would return the number of samples per cell;\n - ``icao24=\"nunique\"`` would return the number of different aircraft\n int the given cell.\n\n The returned pandas DataFrame is indexed over latitude and longitude\n values. It is conveniently chainable with the ``.to_xarray()`` method\n in order to plot density heatmaps.\n\n Example usage:\n\n .. code:: python\n\n switzerland.agg_latlon(\n resolution=dict(latitude=10, longitude=10),\n vertical_rate=\"mean\",\n timestamp=\"count\"\n )\n\n See how to make `flight density heatmaps </scenarios/heatmaps.html>`_\n \"\"\"\n warnings.warn(\n \"agg_latlon will disappear in future versions. \"\n \"Use agg_xy instead\",\n DeprecationWarning,\n )\n\n if resolution is None:\n resolution = dict(latitude=1, longitude=1)\n\n if len(kwargs) is None:\n raise ValueError(\n \"Specify parameters to aggregate, \"\n \"e.g. altitude='mean' or icao24='nunique'\"\n )\n\n r_lat = resolution.get(\"latitude\", None)\n r_lon = resolution.get(\"longitude\", None)\n\n if r_lat is None or r_lon is None:\n raise ValueError(\"Specify a resolution for latitude and longitude\")\n\n data = (\n self.assign(\n latitude=lambda x: ((r_lat * x.latitude).round() / r_lat),\n longitude=lambda x: ((r_lon * x.longitude).round() / r_lon),\n )\n .groupby([\"latitude\", \"longitude\"])\n .agg(kwargs)\n )\n return data\n\n def windfield(\n self, resolution: Union[Dict[str, float], None] = None\n ) -> pd.DataFrame:\n\n if any(w not in self.data.columns for w in [\"wind_u\", \"wind_v\"]):\n raise RuntimeError(\n \"No wind data in trajectory. Consider Traffic.compute_wind()\"\n )\n\n return self.agg_latlon(\n resolution=resolution,\n wind_u=\"mean\",\n wind_v=\"mean\",\n timestamp=\"count\",\n )\n\n def plot_wind(\n self,\n ax: \"GeoAxesSubplot\",\n resolution: Union[Dict[str, float], None] = None,\n threshold: int = 10,\n filtered: bool = False,\n **kwargs,\n ) -> List[\"Artist\"]: # coverage: ignore\n \"\"\"Plots the wind field seen by the aircraft on a Matplotlib axis.\n\n The Flight supports Cartopy axis as well with automatic projection. If\n no projection is provided, a default `PlateCarree\n <https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#platecarree>`_\n is applied.\n\n The `resolution` argument may be:\n\n - a dictionary, e.g dict(latitude=4, longitude=4), if you\n want a grid with a resolution of 4 points per latitude and\n longitude degree.\n - None (default) for dict(latitude=1, longitude=1)\n\n Example usage:\n\n >>> from traffic.drawing import Mercator\n >>> fig, ax = plt.subplots(1, subplot_kw=dict(projection=Mercator()))\n >>> (\n ... traffic\n ... .resample(\"1s\")\n ... .query('altitude > 10000')\n ... .compute_wind()\n ... .eval()\n ... .plot_wind(ax, alpha=.5)\n ... )\n\n \"\"\"\n\n from cartopy import crs\n\n if \"projection\" in ax.__dict__ and \"transform\" not in kwargs:\n kwargs[\"transform\"] = crs.PlateCarree()\n\n if any(w not in self.data.columns for w in [\"wind_u\", \"wind_v\"]):\n raise RuntimeError(\n \"No wind data in trajectory. Consider Traffic.compute_wind()\"\n )\n\n data = (\n (\n self.iterate_lazy()\n .filter(roll=17)\n .query(\"roll.abs() < .5\")\n .filter(wind_u=17, wind_v=17)\n .eval(desc=\"\")\n )\n if filtered\n else self\n )\n\n windfield = (\n data.windfield(resolution)\n .query(f\"timestamp > {threshold}\")\n .reset_index()\n )\n\n return ax.barbs(\n windfield.longitude.values,\n windfield.latitude.values,\n windfield.wind_u.values,\n windfield.wind_v.values,\n **kwargs,\n )\n\n # --- Real work ---\n\n def clean_invalid(self, threshold: int = 10) -> \"Traffic\":\n \"\"\"Removes irrelevant data from the Traffic DataFrame.\n\n Data that has been downloaded from the OpenSky Impala shell often\n contains faulty data, esp. because of faulty callsigns (wrongly decoded?\n faulty crc?) and of automatically repeated positions (see\n `last_position`).\n\n This methods is an attempt to automatically clean this data.\n\n Data uncleaned could result in the following count of messages\n associated to aircraft icao24 `02008b` which could be easily removed.\n\n .. parsed-literal::\n count\n icao24 callsign\n 02008b 0 221 8\n 2AM2R1 4\n 2N D 1\n 3DYCI 1\n 3N I8 1\n 3Q G9 E 1\n 6 V X 1\n [...]\n\n \"\"\"\n\n if \"last_position\" not in self.data.columns:\n return self\n\n return self.__class__(\n self.data.groupby([\"icao24\", \"callsign\"]).filter(\n lambda x: x.drop_duplicates(\"last_position\").count().max()\n > threshold\n )\n )\n\n def closest_point_of_approach(\n self,\n lateral_separation: float,\n vertical_separation: float,\n projection: Union[pyproj.Proj, \"crs.Projection\", None] = None,\n round_t: str = \"d\",\n max_workers: int = 4,\n ) -> Optional[\"CPA\"]:\n \"\"\"\n Computes a Closest Point of Approach (CPA) dataframe for all pairs of\n trajectories candidates for being separated by less than\n lateral_separation in vertical_separation.\n\n The problem of iterating over pairs of trajectories is of unreasonable\n complexity O(n**2). Therefore, instead of computing the CPA between all\n pairs of trajectory, we do it for all pairs of trajectories coming\n closer than a given ``lateral_separation`` and ``vertical_separation``.\n\n lateral_separation: float (in **meters**)\n Depending on your application, you could start with 10 * 1852 (for\n 10 nautical miles)\n\n vertical_separation: float (in ft)\n Depending on your application, you could start with 1500 (feet)\n\n projection: pyproj.Proj, crs.Projection, None\n a first filtering is applied on the bounding boxes of trajectories,\n expressed in meters. You need to provide a decent projection able to\n approximate distances by Euclide formula. By default, EuroPP()\n projection is considered, but a non explicit argument will raise a\n warning.\n\n round_t: str\n an additional column will be added in the DataFrame to group\n trajectories by relevant time frames. Distance computations will be\n considered only between trajectories flown in the same time frame.\n By default, the 'd' pandas freq parameter is considered, to group\n trajectories by day, but other ways of splitting ('h') may be more\n relevant and impact performance.\n\n max_workers: int\n distance computations are spread over a given number of\n processors.\n\n Returns a CPA DataFrame wrapper.\n\n \"\"\"\n\n return closest_point_of_approach(\n self,\n lateral_separation,\n vertical_separation,\n projection,\n round_t,\n max_workers,\n )\n\n def clustering(\n self,\n clustering: \"ClusteringProtocol\",\n nb_samples: Optional[int],\n features: Optional[List[str]] = None,\n *args,\n projection: Union[None, \"crs.Projection\", pyproj.Proj] = None,\n transform: Optional[\"TransformerProtocol\"] = None,\n max_workers: int = 1,\n return_traffic: bool = True,\n ) -> Clustering:\n \"\"\"\n Computes a clustering of the trajectories, add labels in a column\n ``cluster``.\n\n The method:\n\n - resamples all trajectories with the same number of samples\n ``nb_samples`` (no default value);\n - *if need be,* computes x and y coordinates based on ``projection``\n through a call to `compute_xy()\n <#traffic.core.Traffic.compute_xy>`_ (no default value);\n - *if need be,* apply a transformer to the resulting `X` matrix.\n You may want to consider `StandardScaler()\n <https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html>`_;\n - generates the appropriate structure for a call to the usual\n `sklearn API\n <https://scikit-learn.org/stable/modules/clustering.html#clustering>`_\n that is a class with a ``fit()`` method and a ``predict()`` method\n or a ``labels_`` attribute;\n - returns a Clustering object, on which to call fit(), predict() or\n fit_predict() methods. Predicting methods return the original\n Traffic DataFrame with an additional ``cluster`` column.\n\n Example usage:\n\n >>> from traffic.core.projection import EuroPP\n >>> from sklearn.cluster import DBSCAN\n >>> from sklearn.preprocessing import StandardScaler\n >>>\n >>> t_dbscan = traffic.clustering(\n ... nb_samples=15,\n ... projection=EuroPP(),\n ... clustering=DBSCAN(eps=1.5, min_samples=10),\n ... transform=StandardScaler(),\n ... ).fit_predict()\n >>> t_dbscan.groupby([\"cluster\"]).agg({\"flight_id\": \"nunique\"})\n\n .. parsed-literal::\n flight_id\n cluster\n -1 15\n 0 29\n 1 13\n 2 24\n 3 24\n\n \"\"\"\n\n if features is None:\n features = [\"x\", \"y\"]\n\n return Clustering(\n self,\n clustering,\n nb_samples,\n features,\n projection=projection,\n transform=transform,\n )\n\n def centroid(\n self,\n nb_samples: Optional[int],\n features: Optional[List[str]] = None,\n projection: Union[None, \"crs.Projection\", pyproj.Proj] = None,\n transformer: Optional[\"TransformerProtocol\"] = None,\n max_workers: int = 1,\n *args,\n **kwargs,\n ) -> \"Flight\":\n \"\"\"\n Returns the trajectory in the Traffic that is the closest to all other\n trajectories.\n\n .. warning::\n Remember the time and space complexity of this method is in O(n^2).\n\n *args and **kwargs are passed as is to `scipy.spatial.pdist\n <https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html#scipy.spatial.distance.pdist>`_\n\n \"\"\"\n\n if features is None:\n features = [\"x\", \"y\"]\n\n return centroid(\n self,\n nb_samples,\n features,\n projection,\n transformer,\n max_workers,\n *args,\n **kwargs,\n )\n",
"import logging\nimport warnings\nfrom datetime import datetime, timedelta, timezone\nfrom operator import attrgetter\nfrom pathlib import Path\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Callable,\n Dict,\n Iterable,\n Iterator,\n List,\n Optional,\n Set,\n Tuple,\n Type,\n TypeVar,\n Union,\n cast,\n overload,\n)\n\nimport numpy as np\nimport pandas as pd\nimport pyproj\nfrom pandas.core.internals import DatetimeTZBlock\nfrom shapely.geometry import LineString, MultiPoint, Point, Polygon, base\nfrom shapely.ops import transform\n\nfrom ..algorithms.douglas_peucker import douglas_peucker\nfrom ..algorithms.navigation import NavigationFeatures\nfrom ..algorithms.phases import FuzzyLogic\nfrom . import geodesy as geo\nfrom .iterator import FlightIterator, flight_iterator\nfrom .mixins import GeographyMixin, HBoxMixin, PointMixin, ShapelyMixin\nfrom .time import deltalike, time_or_delta, timelike, to_datetime, to_timedelta\n\nif TYPE_CHECKING:\n import altair as alt # noqa: F401\n from cartopy.mpl.geoaxes import GeoAxesSubplot # noqa: F401\n from matplotlib.artist import Artist # noqa: F401\n from matplotlib.axes._subplots import Axes # noqa: F401\n\n from ..data.adsb.raw_data import RawData # noqa: F401\n from .airspace import Airspace # noqa: F401\n from .lazy import LazyTraffic # noqa: F401\n from .traffic import Traffic # noqa: F401\n\n\nT = TypeVar(\"T\", bound=\"Flight\")\n\nif str(pd.__version__) < \"1.3\":\n\n def _tz_interpolate(data, *args, **kwargs):\n return data.astype(int).interpolate(*args, **kwargs).astype(data.dtype)\n\n DatetimeTZBlock.interpolate = _tz_interpolate\n\nelse:\n # - with version 1.3.0, interpolate returns a list\n # - Windows require \"int64\" as \"int\" may be interpreted as \"int32\" and raise\n # an error (was not raised before 1.3.0)\n\n def _tz_interpolate(data, *args, **kwargs):\n coerced = data.coerce_to_target_dtype(\"int64\")\n interpolated, *_ = coerced.interpolate(*args, **kwargs)\n return interpolated\n\n DatetimeTZBlock.interpolate = _tz_interpolate\n\n\ndef _split(\n data: pd.DataFrame, value: Union[str, int], unit: Optional[str]\n) -> Iterator[pd.DataFrame]:\n # This method helps splitting a flight into several.\n if data.shape[0] < 2:\n return\n diff = data.timestamp.diff().values\n if unit is None:\n delta = pd.Timedelta(value).to_timedelta64()\n else:\n delta = np.timedelta64(value, unit)\n # There seems to be a change with numpy >= 1.18\n # max() now may return NaN, therefore the following fix\n max_ = np.nanmax(diff)\n if max_ > delta:\n # np.nanargmax seems bugged with timestamps\n argmax = np.where(diff == max_)[0][0]\n yield from _split(data.iloc[:argmax], value, unit)\n yield from _split(data.iloc[argmax:], value, unit) # noqa\n else:\n yield data\n\n\n# flake B008\nattrgetter_duration = attrgetter(\"duration\")\n\n# flake B006\ndefault_angle_features = [\"track\", \"heading\"]\n\n\nclass Position(PointMixin, pd.core.series.Series):\n def plot(\n self, ax: \"Axes\", text_kw=None, shift=None, **kwargs\n ) -> List[\"Artist\"]: # coverage: ignore\n\n from ..drawing.markers import aircraft as aircraft_marker\n from ..drawing.markers import rotate_marker\n\n visualdict = dict(s=300)\n if hasattr(self, \"track\"):\n visualdict[\"marker\"] = rotate_marker(aircraft_marker, self.track)\n\n if text_kw is None:\n text_kw = dict()\n else:\n # since we may modify it, let's make a copy\n text_kw = {**text_kw}\n\n if \"s\" not in text_kw and hasattr(self, \"callsign\"):\n text_kw[\"s\"] = self.callsign\n\n return super().plot(ax, text_kw, shift, **{**visualdict, **kwargs})\n\n\nclass MetaFlight(type):\n def __getattr__(cls, name):\n if name.startswith(\"aligned_on_\"):\n return lambda flight: cls.aligned_on_ils(flight, name[11:])\n if name.startswith(\"takeoff_runway_\"):\n return lambda flight: cls.takeoff_from_runway(flight, name[15:])\n if name.startswith(\"on_parking_\"):\n return lambda flight: cls.on_parking_position(flight, name[11:])\n if name.startswith(\"pushback_\"):\n return lambda flight: cls.pushback(flight, name[9:])\n if name.startswith(\"landing_at_\"):\n return lambda flight: cls.landing_at(flight, name[11:])\n if name.startswith(\"takeoff_from_\"):\n return lambda flight: cls.takeoff_from(flight, name[13:])\n raise AttributeError\n\n\nclass Flight(\n HBoxMixin,\n GeographyMixin,\n ShapelyMixin,\n NavigationFeatures,\n FuzzyLogic,\n metaclass=MetaFlight,\n):\n \"\"\"Flight is the most basic class associated to a trajectory.\n Flights are the building block of all processing methods, built on top of\n pandas DataFrame. The minimum set of required features are:\n\n - ``icao24``: the ICAO transponder ID of an aircraft;\n - ``callsign``: an identifier which may be associated with the\n registration of an aircraft, with its mission (VOR calibration,\n firefighting) or with a route (for a commercial aircraft);\n - ``timestamp``: timezone aware timestamps are preferable.\n Some methods may work with timezone naive timestamps but the behaviour\n is not guaranteed;\n - ``latitude``, ``longitude``: in degrees, WGS84 (EPSG:4326);\n - ``altitude``: in feet.\n\n .. note::\n The ``flight_id`` (identifier for a trajectory) may be used in place of\n a pair of (``icao24``, ``callsign``). More features may also be provided\n for further processing, e.g. ``groundspeed``, ``vertical_rate``,\n ``track``, ``heading``, ``IAS`` (indicated airspeed) or ``squawk``.\n\n .. note::\n\n All navigation related methods are described more in depth on a\n `dedicated page <navigation.html>`_.\n\n **Abridged contents:**\n\n - properties:\n `callsign <#traffic.core.Flight.callsign>`_,\n `flight_id <#traffic.core.Flight.flight_id>`_,\n `icao24 <#traffic.core.Flight.icao24>`_,\n `number <#traffic.core.Flight.number>`_,\n `registration <#traffic.core.Flight.registration>`_,\n `start <#traffic.core.Flight.start>`_,\n `stop <#traffic.core.Flight.stop>`_,\n `typecode <#traffic.core.Flight.typecode>`_\n - time related methods:\n `after() <#traffic.core.Flight.after>`_,\n `at() <#traffic.core.Flight.at>`_,\n `at_ratio() <#traffic.core.Flight.at_ratio>`_,\n `before() <#traffic.core.Flight.before>`_,\n `between() <#traffic.core.Flight.between>`_,\n `first() <#traffic.core.Flight.first>`_,\n `last() <#traffic.core.Flight.last>`_,\n `skip() <#traffic.core.Flight.skip>`_,\n `shorten() <#traffic.core.Flight.shorten>`_\n - geometry related methods:\n `airborne() <#traffic.core.Flight.airborne>`_,\n `clip() <#traffic.core.Flight.clip>`_,\n `compute_wind() <#traffic.core.Flight.compute_wind>`_,\n `compute_xy() <#traffic.core.Flight.compute_xy>`_,\n `distance() <#traffic.core.Flight.distance>`_,\n `inside_bbox() <#traffic.core.Flight.inside_bbox>`_,\n `intersects() <#traffic.core.Flight.intersects>`_,\n `project_shape() <#traffic.core.Flight.project_shape>`_,\n `simplify() <#traffic.core.Flight.simplify>`_,\n `unwrap() <#traffic.core.Flight.unwrap>`_\n - filtering and resampling methods:\n `comet() <#traffic.core.Flight.comet>`_,\n `filter() <#traffic.core.Flight.filter>`_,\n `resample() <#traffic.core.Flight.resample>`_,\n - visualisation with altair:\n `chart() <#traffic.core.Flight.chart>`_,\n `geoencode() <#traffic.core.Flight.geoencode>`_\n - visualisation with leaflet: `map_leaflet() <leaflet.html>`_\n - visualisation with Matplotlib:\n `plot() <#traffic.core.Flight.plot>`_,\n `plot_time() <#traffic.core.Flight.plot_time>`_\n\n .. tip::\n Sample flights are provided for testing purposes in module\n ``traffic.data.samples``\n\n \"\"\"\n\n __slots__ = (\"data\",)\n\n # --- Special methods ---\n\n def __add__(self, other) -> \"Traffic\":\n \"\"\"\n As Traffic is thought as a collection of Flights, the sum of two Flight\n objects returns a Traffic object\n \"\"\"\n # keep import here to avoid recursion\n from .traffic import Traffic # noqa: F811\n\n if other == 0:\n # useful for compatibility with sum() function\n return Traffic(self.data)\n\n # This just cannot return None in this case.\n return Traffic.from_flights([self, other]) # type: ignore\n\n def __radd__(self, other) -> \"Traffic\":\n \"\"\"\n As Traffic is thought as a collection of Flights, the sum of two Flight\n objects returns a Traffic object\n \"\"\"\n return self + other\n\n def __len__(self) -> int:\n \"\"\"Number of samples associated to a trajectory.\n\n The basic behaviour is to return the number of lines in the underlying\n DataFrame. However in some cases, as positions may be wrongly repeated\n in some database systems (e.g. OpenSky Impala shell), we take the\n `last_position` field into account for counting the number of unique\n detected positions.\n\n Note that when an aircraft is onground, `last_position` is a more\n relevant criterion than (`latitude`, `longitude`) since a grounded\n aircraft may be repeatedly emitting the same position.\n \"\"\"\n\n if \"last_position\" in self.data.columns:\n return self.data.drop_duplicates(\"last_position\").shape[0]\n else:\n return self.data.shape[0]\n\n def _info_html(self) -> str:\n title = f\"<b>Flight {self.title}</b>\"\n title += \"<ul>\"\n title += f\"<li><b>aircraft:</b> {self.aircraft}</li>\"\n if self.origin is not None:\n title += f\"<li><b>from:</b> {self.origin} ({self.start})</li>\"\n else:\n title += f\"<li><b>from:</b> {self.start}</li>\"\n if self.destination is not None:\n title += f\"<li><b>to:</b> {self.destination} ({self.stop})</li>\"\n else:\n title += f\"<li><b>to:</b> {self.stop}</li>\"\n if self.diverted is not None:\n title += f\"<li><b>diverted to: {self.diverted}</b></li>\"\n title += \"</ul>\"\n return title\n\n def _repr_html_(self) -> str:\n title = self._info_html()\n no_wrap_div = '<div style=\"white-space: nowrap\">{}</div>'\n return title + no_wrap_div.format(self._repr_svg_())\n\n def _repr_svg_(self):\n # even 25m should be enough to limit the size of resulting notebooks!\n if self.shape is None:\n return None\n\n if len(self.shape.coords) < 1000:\n return super()._repr_svg_()\n\n return super(\n Flight,\n # cast should be useless but return type of simplify() is Union\n cast(Flight, self.resample(\"1s\").simplify(25)),\n )._repr_svg_()\n\n def __repr__(self) -> str:\n output = f\"Flight {self.title}\"\n output += f\"\\naircraft: {self.aircraft}\"\n if self.origin is not None:\n output += f\"\\norigin: {self.origin} ({self.start})\"\n else:\n output += f\"\\norigin: {self.start}\"\n if self.destination is not None:\n output += f\"\\ndestination: {self.destination} ({self.stop})\"\n else:\n output += f\"\\ndestination: {self.stop}\"\n return output\n\n def __getattr__(self, name: str):\n \"\"\"Helper to facilitate method chaining without lambda.\n\n Example usage:\n\n flight.altitude_max\n => flight.max('altitude')\n flight.vertical_rate_std\n => flight.std('vertical_rate')\n\n Flight.feature_gt(\"altitude_max\", 10000)\n => lambda f: f.max('altitude') > 10000\n \"\"\"\n msg = f\"'{self.__class__.__name__}' has no attribute '{name}'\"\n if \"_\" not in name:\n raise AttributeError(msg)\n *name_split, agg = name.split(\"_\")\n feature = \"_\".join(name_split)\n if feature not in self.data.columns:\n raise AttributeError(msg)\n return getattr(self.data[feature], agg)()\n\n def filter_if(self, test: Callable[[\"Flight\"], bool]) -> Optional[\"Flight\"]:\n # TODO deprecate if pipe() does a good job?\n return self if test(self) else None\n\n def has(\n self, method: Union[str, Callable[[\"Flight\"], Iterator[\"Flight\"]]]\n ) -> bool:\n \"\"\"Returns True if flight.method() returns a non-empty iterator.\n\n Example usage:\n\n >>> flight.has(\"go_around\")\n >>> flight.has(\"runway_change\")\n >>> flight.has(lambda f: f.aligned_on_ils(\"LFBO\"))\n \"\"\"\n return self.next(method) is not None # noqa: B305\n\n def sum(\n self, method: Union[str, Callable[[\"Flight\"], Iterator[\"Flight\"]]]\n ) -> int:\n \"\"\"Returns the number of segments returns by flight.method().\n\n Example usage:\n\n >>> flight.sum(\"go_around\")\n >>> flight.sum(\"runway_change\")\n >>> flight.sum(lambda f: f.aligned_on_ils(\"LFBO\"))\n \"\"\"\n fun = (\n getattr(self.__class__, method)\n if isinstance(method, str)\n else method\n )\n return sum(1 for _ in fun(self))\n\n def all(\n self, method: Union[str, Callable[[\"Flight\"], Iterator[\"Flight\"]]]\n ) -> Optional[\"Flight\"]:\n \"\"\"Returns the concatenation of segments returns by flight.method().\n\n Example usage:\n\n >>> flight.all(\"go_around\")\n >>> flight.all(\"runway_change\")\n >>> flight.all(lambda f: f.aligned_on_ils(\"LFBO\"))\n \"\"\"\n fun = (\n getattr(self.__class__, method)\n if isinstance(method, str)\n else method\n )\n t = sum(flight.assign(index_=i) for i, flight in enumerate(fun(self)))\n if t == 0:\n return None\n return Flight(t.data) # type: ignore\n\n def next(\n self,\n method: Union[str, Callable[[\"Flight\"], Iterator[\"Flight\"]]],\n ) -> Optional[\"Flight\"]:\n \"\"\"\n Returns the first segment of trajectory yielded by flight.method()\n\n >>> flight.next(\"go_around\")\n >>> flight.next(\"runway_change\")\n >>> flight.next(lambda f: f.aligned_on_ils(\"LFBO\"))\n \"\"\"\n fun = (\n getattr(self.__class__, method)\n if isinstance(method, str)\n else method\n )\n return next(fun(self), None)\n\n def final(\n self,\n method: Union[str, Callable[[\"Flight\"], Iterator[\"Flight\"]]],\n ) -> Optional[\"Flight\"]:\n \"\"\"\n Returns the final (last) segment of trajectory yielded by\n flight.method()\n\n >>> flight.final(\"go_around\")\n >>> flight.final(\"runway_change\")\n >>> flight.final(lambda f: f.aligned_on_ils(\"LFBO\"))\n \"\"\"\n fun = (\n getattr(self.__class__, method)\n if isinstance(method, str)\n else method\n )\n segment = None\n for segment in fun(self):\n continue\n return segment\n\n # --- Iterators ---\n\n @property\n def timestamp(self) -> Iterator[pd.Timestamp]:\n yield from self.data.timestamp\n\n @property\n def coords(self) -> Iterator[Tuple[float, float, float]]:\n data = self.data.query(\"longitude == longitude\")\n if \"altitude\" not in data.columns:\n data = data.assign(altitude=0)\n yield from zip(data[\"longitude\"], data[\"latitude\"], data[\"altitude\"])\n\n def coords4d(\n self, delta_t: bool = False\n ) -> Iterator[Tuple[float, float, float, float]]:\n data = self.data.query(\"longitude == longitude\")\n if delta_t:\n time = (data.timestamp - data.timestamp.min()).dt.total_seconds()\n else:\n time = data[\"timestamp\"]\n\n yield from zip(\n time, data[\"longitude\"], data[\"latitude\"], data[\"altitude\"]\n )\n\n @property\n def xy_time(self) -> Iterator[Tuple[float, float, float]]:\n self_filtered = self.query(\"longitude == longitude\")\n if self_filtered is None:\n return None\n iterator = iter(zip(self_filtered.coords, self_filtered.timestamp))\n while True:\n next_ = next(iterator, None)\n if next_ is None:\n return\n coords, time = next_\n yield (coords[0], coords[1], time.to_pydatetime().timestamp())\n\n # --- Properties (and alike) ---\n\n def min(self, feature: str):\n \"\"\"Returns the minimum value of given feature.\n\n >>> flight.min('altitude') # dummy example\n 24000\n \"\"\"\n return self.data[feature].min()\n\n def max(self, feature: str):\n \"\"\"Returns the maximum value of given feature.\n\n >>> flight.max('altitude') # dummy example\n 35000\n \"\"\"\n return self.data[feature].max()\n\n def mean(self, feature: str):\n \"\"\"Returns the average value of given feature.\n\n >>> flight.mean('vertical_rate') # dummy example\n -1000\n \"\"\"\n return self.data[feature].mean()\n\n def feature_gt(\n self,\n feature: Union[str, Callable[[\"Flight\"], Any]],\n value: Any,\n strict: bool = True,\n ) -> bool:\n \"\"\"Returns True if feature(flight) is greater than value.\n\n This is fully equivalent to `f.longer_than(\"1 minute\")`:\n\n >>> f.feature_gt(\"duration\", pd.Timedelta('1 minute'))\n True\n\n This is equivalent to `f.max('altitude') > 35000`:\n\n >>> f.feature_gt(lambda f: f.max(\"altitude\"), 35000)\n True\n\n The second one can be useful for stacking operations during\n lazy evaluation.\n \"\"\"\n if isinstance(feature, str):\n feature = attrgetter(feature)\n attribute = feature(self)\n if strict:\n return attribute > value\n return attribute >= value\n\n def feature_lt(\n self,\n feature: Union[str, Callable[[\"Flight\"], Any]],\n value: Any,\n strict: bool = True,\n ) -> bool:\n \"\"\"Returns True if feature(flight) is less than value.\n\n This is fully equivalent to `f.shorter_than(\"1 minute\")`:\n\n >>> f.feature_lt(\"duration\", pd.Timedelta('1 minute'))\n True\n\n This is equivalent to `f.max('altitude') < 35000`:\n\n >>> f.feature_lt(lambda f: f.max(\"altitude\"), 35000)\n True\n\n The second one can be useful for stacking operations during\n lazy evaluation.\n \"\"\"\n if isinstance(feature, str):\n feature = attrgetter(feature)\n attribute = feature(self)\n if strict:\n return attribute < value\n return attribute <= value\n\n def shorter_than(\n self, value: Union[str, timedelta, pd.Timedelta], strict: bool = True\n ) -> bool:\n \"\"\"Returns True if flight duration is shorter than value.\"\"\"\n if isinstance(value, str):\n value = pd.Timedelta(value)\n return self.feature_lt(attrgetter(\"duration\"), value, strict)\n\n def longer_than(\n self, value: Union[str, timedelta, pd.Timedelta], strict: bool = True\n ) -> bool:\n \"\"\"Returns True if flight duration is longer than value.\"\"\"\n if isinstance(value, str):\n value = pd.Timedelta(value)\n return self.feature_gt(attrgetter(\"duration\"), value, strict)\n\n def abs(self, features: Union[str, List[str]], **kwargs) -> \"Flight\":\n \"\"\"Assign absolute versions of features to new columns.\n\n >>> flight.abs(\"track\")\n\n The two following commands are equivalent:\n\n >>> flight.abs([\"track\", \"heading\"])\n >>> flight.abs(track=\"track_abs\", heading=\"heading_abs\")\n\n \"\"\"\n assign_dict = dict()\n if isinstance(features, str):\n features = [features]\n if isinstance(features, Iterable):\n for feature in features:\n assign_dict[feature + \"_abs\"] = self.data[feature].abs()\n for key, value in kwargs.items():\n assign_dict[value] = self.data[key].abs()\n return self.assign(**assign_dict)\n\n def diff(self, features: Union[str, List[str]], **kwargs) -> \"Flight\":\n \"\"\"Assign differential versions of features to new columns.\n\n >>> flight.diff(\"track\")\n\n The two following commands are equivalent:\n\n >>> flight.diff([\"track\", \"heading\"])\n >>> flight.diff(track=\"track_diff\", heading=\"heading_diff\")\n\n \"\"\"\n assign_dict = dict()\n if isinstance(features, str):\n features = [features]\n if isinstance(features, Iterable):\n for feature in features:\n assign_dict[feature + \"_diff\"] = self.data[feature].diff()\n for key, value in kwargs.items():\n assign_dict[value] = self.data[key].diff()\n return self.assign(**assign_dict)\n\n @property\n def start(self) -> pd.Timestamp:\n \"\"\"Returns the minimum value of timestamp.\"\"\"\n return self.min(\"timestamp\")\n\n @property\n def stop(self) -> pd.Timestamp:\n \"\"\"Returns the maximum value of timestamp.\"\"\"\n return self.max(\"timestamp\")\n\n @property\n def duration(self) -> pd.Timedelta:\n \"\"\"Returns the duration of the flight.\"\"\"\n return self.stop - self.start\n\n def _get_unique(\n self, field: str, warn: bool = True\n ) -> Union[str, Set[str], None]:\n if field not in self.data.columns:\n return None\n tmp = self.data[field].unique()\n if len(tmp) == 1:\n return tmp[0]\n if warn:\n logging.warning(\n f\"Several {field}s for one flight, consider splitting\"\n )\n return set(tmp)\n\n @property\n def callsign(self) -> Union[str, Set[str], None]:\n \"\"\"Returns the unique callsign value(s) associated to the Flight.\n\n A callsign is an identifier sent by an aircraft during its flight. It\n may be associated with the registration of an aircraft, its mission or\n with a route for a commercial aircraft.\n \"\"\"\n callsign = self._get_unique(\"callsign\")\n if callsign != callsign:\n raise ValueError(\"NaN appearing in callsign field\")\n return callsign\n\n @property\n def number(self) -> Union[str, Set[str], None]:\n \"\"\"Returns the unique number value(s) associated to the Flight.\n\n This field is reserved for the commercial number of the flight, prefixed\n by the two letter code of the airline.\n For instance, AFR292 is the callsign and AF292 is the flight number.\n\n Callsigns are often more complicated as they are designed to limit\n confusion on the radio: hence DLH02X can be the callsign associated\n to flight number LH1100.\n \"\"\"\n return self._get_unique(\"number\")\n\n @property\n def flight_id(self) -> Union[str, Set[str], None]:\n \"\"\"Returns the unique flight_id value(s) of the DataFrame.\n\n Neither the icao24 (the aircraft) nor the callsign (the route) is a\n reliable way to identify trajectories. You can either use an external\n source of data to assign flight ids (for example DDR files by\n Eurocontrol, identifiers by FlightRadar24, etc.) or assign a flight_id\n by yourself (see ``Flight.assign_id(name: str)`` method).\n\n The ``Traffic.assign_id()`` method uses a heuristic based on the\n timestamps associated to callsign/icao24 pairs to automatically assign a\n ``flight_id`` and separate flights.\n\n \"\"\"\n return self._get_unique(\"flight_id\")\n\n @property\n def title(self) -> str:\n title = str(self.callsign)\n number = self.number\n flight_id = self.flight_id\n\n if number is not None:\n title += f\" – {number}\"\n\n if flight_id is not None:\n title += f\" ({flight_id})\"\n\n return title\n\n @property\n def origin(self) -> Union[str, Set[str], None]:\n \"\"\"Returns the unique origin value(s),\n None if not available in the DataFrame.\n\n The origin airport is usually represented as a ICAO or a IATA code.\n\n The ICAO code of an airport is represented by 4 letters (e.g. EHAM for\n Amsterdam Schiphol International Airport) and the IATA code is\n represented by 3 letters and more familiar to the public (e.g. AMS for\n Amsterdam)\n\n \"\"\"\n return self._get_unique(\"origin\")\n\n @property\n def destination(self) -> Union[str, Set[str], None]:\n \"\"\"Returns the unique destination value(s),\n None if not available in the DataFrame.\n\n The destination airport is usually represented as a ICAO or a IATA code.\n\n The ICAO code of an airport is represented by 4 letters (e.g. EHAM for\n Amsterdam Schiphol International Airport) and the IATA code is\n represented by 3 letters and more familiar to the public (e.g. AMS for\n Amsterdam)\n\n \"\"\"\n return self._get_unique(\"destination\")\n\n @property\n def diverted(self) -> Union[str, Set[str], None]:\n \"\"\"Returns the unique diverted value(s),\n None if not available in the DataFrame.\n\n The diverted airport is usually represented as a ICAO or a IATA code.\n\n The ICAO code of an airport is represented by 4 letters (e.g. EHAM for\n Amsterdam Schiphol International Airport) and the IATA code is\n represented by 3 letters and more familiar to the public (e.g. AMS for\n Amsterdam)\n\n \"\"\"\n return self._get_unique(\"diverted\")\n\n @property\n def squawk(self) -> Set[str]:\n \"\"\"Returns all the unique squawk values in the trajectory.\n\n A squawk code is a four-digit number assigned by ATC and set on the\n transponder. Some squawk codes are reserved for specific situations and\n emergencies, e.g. 7700 for general emergency, 7600 for radio failure or\n 7500 for hijacking.\n \"\"\"\n return set(self.data.squawk.unique())\n\n @property\n def icao24(self) -> Union[str, Set[str], None]:\n \"\"\"Returns the unique icao24 value(s) of the DataFrame.\n\n icao24 (ICAO 24-bit address) is a unique identifier associated to a\n transponder. These identifiers correlate to the aircraft registration.\n\n For example icao24 code 'ac82ec' is associated to 'N905NA'.\n \"\"\"\n icao24 = self._get_unique(\"icao24\")\n if icao24 != icao24:\n raise ValueError(\"NaN appearing in icao24 field\")\n return icao24\n\n @property\n def registration(self) -> Optional[str]:\n from ..data import aircraft\n\n if not isinstance(self.icao24, str):\n return None\n res = aircraft[self.icao24]\n res = res.query(\"registration == registration and registration != ''\")\n if res.shape[0] == 1:\n return res.iloc[0].registration\n return None\n\n @property\n def typecode(self) -> Optional[str]:\n from ..data import aircraft\n\n if not isinstance(self.icao24, str):\n return None\n res = aircraft[self.icao24]\n res = res.query(\"typecode == typecode and typecode != ''\")\n if res.shape[0] == 1:\n return res.iloc[0].typecode\n return None\n\n @property\n def aircraft(self) -> Optional[str]:\n from ..data import aircraft\n\n if not isinstance(self.icao24, str):\n return None\n\n res = str(self.icao24)\n ac = aircraft.get_unique(res)\n\n if ac is None:\n return res\n\n registration = ac[\"registration\"]\n typecode = ac[\"typecode\"]\n flag = ac[\"flag\"]\n\n if registration is not None:\n res += f\" · {flag} {registration}\"\n else:\n res = f\"{flag} {res}\"\n\n if typecode is not None:\n res += f\" ({typecode})\"\n\n return res\n\n # -- Time handling, splitting, interpolation and resampling --\n\n def skip(self, value: deltalike = None, **kwargs) -> Optional[\"Flight\"]:\n \"\"\"Removes the first n days, hours, minutes or seconds of the Flight.\n\n The elements passed as kwargs as passed as is to the datetime.timedelta\n constructor.\n\n Example usage:\n\n >>> flight.skip(minutes=10)\n >>> flight.skip(\"1H\")\n >>> flight.skip(10) # seconds by default\n \"\"\"\n delta = to_timedelta(value, **kwargs)\n bound = self.start + delta # noqa: F841 => used in the query\n # full call is necessary to keep @bound as a local variable\n df = self.data.query(\"timestamp >= @bound\")\n if df.shape[0] == 0:\n return None\n return self.__class__(df)\n\n def first(self, value: deltalike = None, **kwargs) -> Optional[\"Flight\"]:\n \"\"\"Returns the first n days, hours, minutes or seconds of the Flight.\n\n The elements passed as kwargs as passed as is to the datetime.timedelta\n constructor.\n\n Example usage:\n\n >>> flight.first(minutes=10)\n >>> flight.first(\"1H\")\n >>> flight.first(10) # seconds by default\n \"\"\"\n delta = to_timedelta(value, **kwargs)\n bound = self.start + delta # noqa: F841 => used in the query\n # full call is necessary to keep @bound as a local variable\n df = self.data.query(\"timestamp < @bound\")\n if df.shape[0] == 0:\n return None\n return self.__class__(df)\n\n def shorten(self, value: deltalike = None, **kwargs) -> Optional[\"Flight\"]:\n \"\"\"Removes the last n days, hours, minutes or seconds of the Flight.\n\n The elements passed as kwargs as passed as is to the datetime.timedelta\n constructor.\n\n Example usage:\n\n >>> flight.shorten(minutes=10)\n >>> flight.shorten(\"1H\")\n >>> flight.shorten(10) # seconds by default\n \"\"\"\n delta = to_timedelta(value, **kwargs)\n bound = self.stop - delta # noqa: F841 => used in the query\n # full call is necessary to keep @bound as a local variable\n df = self.data.query(\"timestamp <= @bound\")\n if df.shape[0] == 0:\n return None\n return self.__class__(df)\n\n def last(self, value: deltalike = None, **kwargs) -> Optional[\"Flight\"]:\n \"\"\"Returns the last n days, hours, minutes or seconds of the Flight.\n\n The elements passed as kwargs as passed as is to the datetime.timedelta\n constructor.\n\n Example usage:\n\n >>> flight.last(minutes=10)\n >>> flight.last(\"1H\")\n >>> flight.last(10) # seconds by default\n \"\"\"\n delta = to_timedelta(value, **kwargs)\n bound = self.stop - delta # noqa: F841 => used in the query\n # full call is necessary to keep @bound as a local variable\n df = self.data.query(\"timestamp > @bound\")\n if df.shape[0] == 0:\n return None\n return self.__class__(df)\n\n def before(self, time: timelike, strict: bool = True) -> Optional[\"Flight\"]:\n \"\"\"Returns the part of the trajectory flown before a given timestamp.\n\n - ``time`` can be passed as a string, an epoch, a Python datetime, or\n a Pandas timestamp.\n \"\"\"\n return self.between(self.start, time, strict)\n\n def after(self, time: timelike, strict: bool = True) -> Optional[\"Flight\"]:\n \"\"\"Returns the part of the trajectory flown after a given timestamp.\n\n - ``time`` can be passed as a string, an epoch, a Python datetime, or\n a Pandas timestamp.\n \"\"\"\n return self.between(time, self.stop, strict)\n\n def between(\n self, start: timelike, stop: time_or_delta, strict: bool = True\n ) -> Optional[\"Flight\"]:\n \"\"\"Returns the part of the trajectory flown between start and stop.\n\n - ``start`` and ``stop`` can be passed as a string, an epoch, a Python\n datetime, or a Pandas timestamp.\n - ``stop`` can also be passed as a timedelta.\n\n \"\"\"\n\n # Corner cases when start or stop are None or NaT\n if start is None or start != start:\n return self.before(stop, strict=strict)\n\n if stop is None or stop != stop:\n return self.after(start, strict=strict)\n\n start = to_datetime(start)\n if isinstance(stop, timedelta):\n stop = start + stop\n else:\n stop = to_datetime(stop)\n\n # full call is necessary to keep @start and @stop as local variables\n # return self.query('@start < timestamp < @stop') => not valid\n if strict:\n df = self.data.query(\"@start < timestamp < @stop\")\n else:\n df = self.data.query(\"@start <= timestamp <= @stop\")\n\n if df.shape[0] == 0:\n return None\n\n return self.__class__(df)\n\n def at(self, time: Optional[timelike] = None) -> Optional[Position]:\n \"\"\"Returns the position in the trajectory at a given timestamp.\n\n - ``time`` can be passed as a string, an epoch, a Python datetime, or\n a Pandas timestamp.\n\n - If no time is passed (default), the last know position is returned.\n - If no position is available at the given timestamp, None is returned.\n If you expect a position at any price, consider `Flight.resample\n <#traffic.core.Flight.resample>`_\n\n \"\"\"\n\n if time is None:\n return Position(self.data.ffill().iloc[-1])\n\n index = to_datetime(time)\n df = self.data.set_index(\"timestamp\")\n if index not in df.index:\n id_ = getattr(self, \"flight_id\", self.callsign)\n logging.warning(f\"No index {index} for flight {id_}\")\n return None\n return Position(df.loc[index])\n\n def at_ratio(self, ratio: float = 0.5) -> Optional[Position]:\n \"\"\"Returns a position on the trajectory.\n\n This method is convenient to place a marker on the trajectory in\n visualisation output.\n\n - ``Flight.at_ratio(0)`` is the first point in the trajectory.\n - ``Flight.at_ratio(1)`` is the last point of the trajectory\n (equivalent to ``Flight.at()``)\n \"\"\"\n if ratio < 0 or ratio > 1:\n raise RuntimeError(\"ratio must be comprised between 0 and 1\")\n\n subset = self.between(\n self.start, self.start + ratio * self.duration, strict=False\n )\n\n assert subset is not None\n return subset.at()\n\n @flight_iterator\n def sliding_windows(\n self,\n duration: deltalike,\n step: deltalike,\n ) -> Iterator[\"Flight\"]:\n\n duration_ = to_timedelta(duration)\n step_ = to_timedelta(step)\n\n first = self.first(duration_)\n if first is None:\n return\n\n yield first\n\n after = self.after(self.start + step_)\n if after is not None:\n yield from after.sliding_windows(duration_, step_)\n\n @overload\n def split(self, value: int, unit: str) -> FlightIterator:\n ...\n\n @overload\n def split( # noqa: F811\n self, value: str, unit: None = None\n ) -> FlightIterator:\n ...\n\n @flight_iterator\n def split( # noqa: F811\n self, value: Union[int, str] = 10, unit: Optional[str] = None\n ) -> Iterator[\"Flight\"]:\n \"\"\"Iterates on legs of a Flight based on the distrution of timestamps.\n\n By default, the method stops a flight and yields a new one after a gap\n of 10 minutes without data.\n\n The length of the gap (here 10 minutes) can be expressed:\n\n - in the NumPy style: ``Flight.split(10, 'm')`` (see\n ``np.timedelta64``);\n - in the pandas style: ``Flight.split('10T')`` (see ``pd.Timedelta``)\n\n \"\"\"\n if isinstance(value, int) and unit is None:\n # default value is 10 m\n unit = \"m\"\n\n for data in _split(self.data, value, unit):\n yield self.__class__(data)\n\n def max_split(\n self,\n value: Union[int, str] = \"10T\",\n unit: Optional[str] = None,\n key: Callable[[Optional[\"Flight\"]], Any] = attrgetter_duration,\n ) -> Optional[\"Flight\"]:\n \"\"\"Returns the biggest (by default, longest) part of trajectory.\n\n Example usage:\n\n >>> from traffic.data.samples import elal747\n >>> elal747.query(\"altitude < 15000\").max_split()\n Flight ELY1747\n aircraft: 738043 · 🇮🇱 4X-ELC (B744)\n origin: LIRF (2019-11-03 12:14:40+00:00)\n destination: LLBG (2019-11-03 14:13:00+00:00)\n\n In this example, the fancy part of the trajectory occurs below\n 15,000 ft. The command extracts the plane pattern.\n\n \"\"\"\n\n # warnings.warn(\"Use split().max() instead.\", DeprecationWarning)\n return max(\n self.split(value, unit), # type: ignore\n key=key,\n default=None,\n )\n\n def apply_segments(\n self, fun: Callable[..., \"LazyTraffic\"], name: str, *args, **kwargs\n ) -> Optional[\"Flight\"]:\n return getattr(self, name)(*args, **kwargs)(fun)\n\n def apply_time(\n self,\n freq: str = \"1T\",\n merge: bool = True,\n **kwargs,\n ) -> \"Flight\":\n \"\"\"Apply features on time windows.\n\n The following is performed:\n\n - a new column `rounded` rounds the timestamp at the given rate;\n - the groupby/apply is operated with parameters passed in apply;\n - if merge is True, the new column in merged into the Flight,\n otherwise a pd.DataFrame is returned.\n\n For example:\n\n >>> f.agg_time(\"10T\", straight=lambda df: Flight(df).distance())\n\n returns a Flight with a new column straight with the great circle\n distance between points sampled every 10 minutes.\n \"\"\"\n\n if len(kwargs) == 0:\n raise RuntimeError(\"No feature provided for aggregation.\")\n temp_flight = self.assign(\n rounded=lambda df: df.timestamp.dt.round(freq)\n )\n\n agg_data = None\n\n for label, fun in kwargs.items():\n agg_data = (\n agg_data.merge( # type: ignore\n temp_flight.groupby(\"rounded\")\n .apply(lambda df: fun(self.__class__(df)))\n .rename(label),\n left_index=True,\n right_index=True,\n )\n if agg_data is not None\n else temp_flight.groupby(\"rounded\")\n .apply(lambda df: fun(self.__class__(df)))\n .rename(label)\n .to_frame()\n )\n\n if not merge: # mostly for debugging purposes\n return agg_data # type: ignore\n\n return temp_flight.merge(agg_data, left_on=\"rounded\", right_index=True)\n\n def agg_time(\n self,\n freq: str = \"1T\",\n merge: bool = True,\n **kwargs,\n ) -> \"Flight\":\n \"\"\"Aggregate features on time windows.\n\n The following is performed:\n\n - a new column `rounded` rounds the timestamp at the given rate;\n - the groupby/agg is operated with parameters passed in kwargs;\n - if merge is True, the new column in merged into the Flight,\n otherwise a pd.DataFrame is returned.\n\n For example:\n\n >>> f.agg_time('3T', groundspeed='mean')\n\n returns a Flight with a new column groundspeed_mean with groundspeed\n averaged per intervals of 3 minutes.\n \"\"\"\n\n def flatten(\n data: pd.DataFrame, how: Callable = \"_\".join\n ) -> pd.DataFrame:\n data.columns = (\n [\n how(filter(None, map(str, levels)))\n for levels in data.columns.values\n ]\n if isinstance(data.columns, pd.MultiIndex)\n else data.columns\n )\n return data\n\n if len(kwargs) == 0:\n raise RuntimeError(\"No feature provided for aggregation.\")\n temp_flight = self.assign(\n rounded=lambda df: df.timestamp.dt.round(freq)\n )\n\n # force the agg_data to be multi-indexed in columns\n kwargs_modified: Dict[\"str\", List[Any]] = dict(\n (\n key,\n list(value)\n if any(isinstance(value, x) for x in [list, tuple])\n else [value],\n )\n for key, value in kwargs.items()\n )\n agg_data = flatten(temp_flight.groupby(\"rounded\").agg(kwargs_modified))\n\n if not merge: # mostly for debugging purposes\n return agg_data\n\n return temp_flight.merge(agg_data, left_on=\"rounded\", right_index=True)\n\n def handle_last_position(self) -> \"Flight\":\n # The following is True for all data coming from the Impala shell.\n # The following is an attempt to fix #7\n # Note the fun/fast way to produce 1 or trigger NaN (division by zero)\n data = self.data.sort_values(\"timestamp\")\n if \"last_position\" in self.data.columns:\n data = (\n data.assign(\n _mark=lambda df: df.last_position\n != df.shift(1).last_position\n ).assign(\n latitude=lambda df: df.latitude * df._mark / df._mark,\n longitude=lambda df: df.longitude * df._mark / df._mark,\n altitude=lambda df: df.altitude * df._mark / df._mark,\n )\n # keeping last_position causes more problems (= Nan) than\n # anything. Safer to just remove it for now. Like it or not!\n .drop(columns=[\"_mark\", \"last_position\"])\n )\n\n return self.__class__(data)\n\n def resample(self, rule: Union[str, int] = \"1s\") -> \"Flight\":\n \"\"\"Resample the trajectory at a given frequency or number of points.\n\n If the rule is a string representing a pandas `time series frequency\n <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases>`_\n is passed, then the data is resampled along the timestamp axis, then\n interpolated.\n\n If the rule is an integer, the trajectory is resampled to the given\n number of evenly distributed points per trajectory.\n \"\"\"\n\n if isinstance(rule, str):\n data = (\n self.handle_last_position()\n .unwrap() # avoid filled gaps in track and heading\n .assign(start=self.start, stop=self.stop)\n .data.set_index(\"timestamp\")\n .resample(rule)\n .first() # better performance than min() for duplicate index\n .interpolate()\n .reset_index()\n .fillna(method=\"pad\")\n )\n elif isinstance(rule, int):\n # ./site-packages/pandas/core/indexes/base.py:2820: FutureWarning:\n # Converting timezone-aware DatetimeArray to timezone-naive ndarray\n # with 'datetime64[ns]' dtype. In the future, this will return an\n # ndarray with 'object' dtype where each element is a\n # 'pandas.Timestamp' with the correct 'tz'.\n # To accept the future behavior, pass 'dtype=object'.\n # To keep the old behavior, pass 'dtype=\"datetime64[ns]\"'.\n data = (\n self.handle_last_position()\n .unwrap() # avoid filled gaps in track and heading\n .assign(tz_naive=lambda d: d.timestamp.astype(\"datetime64[ns]\"))\n .data.set_index(\"tz_naive\")\n .asfreq((self.stop - self.start) / (rule - 1), method=\"nearest\")\n .reset_index()\n .drop(columns=\"tz_naive\")\n )\n else:\n raise TypeError(\"rule must be a str or an int\")\n\n if \"track_unwrapped\" in data.columns:\n data = data.assign(track=lambda df: df.track_unwrapped % 360)\n if \"heading_unwrapped\" in data.columns:\n data = data.assign(heading=lambda df: df.heading_unwrapped % 360)\n\n return self.__class__(data)\n\n def filter(\n self,\n strategy: Optional[\n Callable[[pd.DataFrame], pd.DataFrame]\n ] = lambda x: x.bfill().ffill(),\n **kwargs,\n ) -> \"Flight\":\n\n \"\"\"Filters the trajectory given features with a median filter.\n\n The method first applies a median filter on each feature of the\n DataFrame. A default kernel size is applied for a number of features\n (resp. latitude, longitude, altitude, track, groundspeed, IAS, TAS) but\n other kernel values may be passed as kwargs parameters.\n\n Rather than returning averaged values, the method computes thresholds\n on sliding windows (as an average of squared differences) and replace\n unacceptable values with NaNs.\n\n Then, a strategy may be applied to fill the NaN values, by default a\n forward/backward fill. Other strategies may be passed, for instance *do\n nothing*: ``None``; or *interpolate*: ``lambda x: x.interpolate()``.\n\n .. note::\n This method if often more efficient when applied several times with\n different kernel values.Kernel values may be passed as integers, or\n list/tuples of integers for cascade of filters:\n\n .. code:: python\n\n # this cascade of filters appears to work well on altitude\n flight.filter(altitude=17).filter(altitude=53)\n\n # this is equivalent to the default value\n flight.filter(altitude=(17, 53))\n\n \"\"\"\n\n import scipy.signal\n\n ks_dict: Dict[str, Union[int, Iterable[int]]] = {\n \"altitude\": (17, 53),\n \"selected_mcp\": (17, 53),\n \"selected_fms\": (17, 53),\n \"IAS\": 23,\n \"TAS\": 23,\n \"Mach\": 23,\n \"groundspeed\": 5,\n \"compute_gs\": (17, 53),\n \"compute_track\": 17,\n \"onground\": 3,\n \"latitude\": 1, # the method doesn't apply well to positions\n \"longitude\": 1,\n **kwargs,\n }\n\n if strategy is None:\n\n def identity(x):\n return x # noqa: E704\n\n strategy = identity\n\n def cascaded_filters(\n df, feature: str, kernel_size: int, filt=scipy.signal.medfilt\n ) -> pd.DataFrame:\n \"\"\"Produces a mask for data to be discarded.\n\n The filtering applies a low pass filter (e.g medfilt) to a signal\n and measures the difference between the raw and the filtered signal.\n\n The average of the squared differences is then produced (sq_eps) and\n used as a threashold for filtering.\n\n Errors may raised if the kernel_size is too large\n \"\"\"\n y = df[feature].astype(float)\n y_m = filt(y, kernel_size)\n sq_eps = (y - y_m) ** 2\n return pd.DataFrame(\n {\n \"timestamp\": df[\"timestamp\"],\n \"y\": y,\n \"y_m\": y_m,\n \"sq_eps\": sq_eps,\n \"sigma\": np.sqrt(filt(sq_eps, kernel_size)),\n },\n index=df.index,\n )\n\n new_data = self.data.sort_values(by=\"timestamp\").copy()\n\n if len(kwargs) == 0:\n features = [\n cast(str, feature)\n for feature in self.data.columns\n if self.data[feature].dtype\n in [np.float32, np.float64, np.int32, np.int64]\n ]\n else:\n features = list(kwargs.keys())\n\n kernels_size: List[Union[int, Iterable[int]]] = [0 for _ in features]\n for idx, feature in enumerate(features):\n kernels_size[idx] = ks_dict.get(feature, 17)\n\n for feat, ks_list in zip(features, kernels_size):\n\n if isinstance(ks_list, int):\n ks_list = [ks_list]\n else:\n ks_list = list(ks_list)\n\n for ks in ks_list:\n # Prepare each feature for the filtering\n df = cascaded_filters(new_data[[\"timestamp\", feat]], feat, ks)\n\n # Decision to accept/reject data points in the time series\n new_data.loc[df.sq_eps > df.sigma, feat] = None\n\n data = strategy(new_data)\n\n if \"onground\" in data.columns:\n data = data.assign(onground=data.onground.astype(bool))\n\n return self.__class__(data)\n\n def filter_position(self, cascades: int = 2) -> Optional[\"Flight\"]:\n # TODO improve based on agg_time or EKF\n flight: Optional[\"Flight\"] = self\n for _ in range(cascades):\n if flight is None:\n return None\n flight = flight.cumulative_distance().query(\n \"compute_gs < compute_gs.mean() + 3 * compute_gs.std()\"\n )\n return flight\n\n def comet(self, **kwargs) -> \"Flight\":\n \"\"\"Computes a comet for a trajectory.\n\n The method uses the last position of a trajectory (method `at()\n <#traffic.core.Flight.at>`_) and uses the ``track`` (in degrees),\n ``groundspeed`` (in knots) and ``vertical_rate`` (in ft/min) values to\n interpolate the trajectory in a straight line.\n\n The elements passed as kwargs as passed as is to the datetime.timedelta\n constructor.\n\n Example usage:\n\n .. code:: python\n\n flight.comet(minutes=10)\n flight.before(\"2018-12-24 23:55\").comet(minutes=10) # Merry XMas!\n\n \"\"\"\n\n last_line = self.at()\n if last_line is None:\n raise ValueError(\"Unknown data for this flight\")\n window = self.last(seconds=20)\n delta = timedelta(**kwargs)\n\n if window is None:\n raise RuntimeError(\"Flight expect at least 20 seconds of data\")\n\n new_gs = window.data.groundspeed.mean()\n new_vr = window.data.vertical_rate.mean()\n\n new_lat, new_lon, _ = geo.destination(\n last_line.latitude,\n last_line.longitude,\n last_line.track,\n new_gs * delta.total_seconds() * 1852 / 3600,\n )\n\n new_alt = last_line.altitude + new_vr * delta.total_seconds() / 60\n\n return Flight(\n pd.DataFrame.from_records(\n [\n last_line,\n pd.Series(\n {\n \"timestamp\": last_line.timestamp + delta,\n \"latitude\": new_lat,\n \"longitude\": new_lon,\n \"altitude\": new_alt,\n \"groundspeed\": new_gs,\n \"vertical_rate\": new_vr,\n }\n ),\n ]\n ).ffill()\n )\n\n # -- Air traffic management --\n\n def assign_id(\n self, name: str = \"{self.callsign}_{idx:>03}\", idx: int = 0\n ) -> \"Flight\":\n \"\"\"Assigns a flight_id to a Flight.\n\n This method is more generally used by the corresponding Traffic and\n LazyTraffic methods but works fine on Flight as well.\n \"\"\"\n return self.assign(flight_id=name.format(self=self, idx=idx))\n\n def onground(self) -> Optional[\"Flight\"]:\n if \"altitude\" not in self.data.columns:\n return self\n if \"onground\" in self.data.columns and self.data.onground.dtype == bool:\n return self.query(\"onground or altitude != altitude\")\n else:\n return self.query(\"altitude != altitude\")\n\n def airborne(self) -> Optional[\"Flight\"]:\n \"\"\"Returns the airborne part of the Flight.\n\n The airborne part is determined by an ``onground`` flag or null values\n in the altitude column.\n \"\"\"\n if \"altitude\" not in self.data.columns:\n return None\n if \"onground\" in self.data.columns and self.data.onground.dtype == bool:\n return self.query(\"not onground and altitude == altitude\")\n else:\n return self.query(\"altitude == altitude\")\n\n def unwrap(self, features: Union[None, str, List[str]] = None) -> \"Flight\":\n \"\"\"Unwraps angles in the DataFrame.\n\n All features representing angles may be unwrapped (through Numpy) to\n avoid gaps between 359° and 1°.\n\n The method applies by default to features ``track`` and ``heading``.\n More or different features may be passed in parameter.\n \"\"\"\n if features is None:\n features = default_angle_features\n\n if isinstance(features, str):\n features = [features]\n\n reset = self.reset_index(drop=True)\n\n result_dict = dict()\n for feature in features:\n if feature not in reset.data.columns:\n continue\n series = reset.data[feature]\n idx = ~series.isnull()\n result_dict[f\"{feature}_unwrapped\"] = pd.Series(\n np.degrees(np.unwrap(np.radians(series.loc[idx]))),\n index=series.loc[idx].index,\n )\n\n return reset.assign(**result_dict)\n\n def compute_wind(self) -> \"Flight\":\n \"\"\"Computes the wind triangle for each timestamp.\n\n This method requires ``groundspeed``, ``track``, true airspeed\n (``TAS``), and ``heading`` features. The groundspeed and the track angle\n are usually available in ADS-B messages; the heading and the true\n airspeed may be decoded in EHS messages.\n\n .. note::\n Check the `query_ehs() <#traffic.core.Flight.query_ehs>`_ method to\n find a way to enrich your flight with such features. Note that this\n data is not necessarily available depending on the location.\n \"\"\"\n\n if any(w not in self.data.columns for w in [\"heading\", \"TAS\"]):\n raise RuntimeError(\n \"No wind data in trajectory. Consider Flight.query_ehs()\"\n )\n\n return self.assign(\n wind_u=self.data.groundspeed * np.sin(np.radians(self.data.track))\n - self.data.TAS * np.sin(np.radians(self.data.heading)),\n wind_v=self.data.groundspeed * np.cos(np.radians(self.data.track))\n - self.data.TAS * np.cos(np.radians(self.data.heading)),\n )\n\n def plot_wind(\n self,\n ax: \"GeoAxesSubplot\",\n resolution: Union[int, str, Dict[str, float], None] = \"5T\",\n filtered: bool = False,\n **kwargs,\n ) -> List[\"Artist\"]: # coverage: ignore\n \"\"\"Plots the wind field seen by the aircraft on a Matplotlib axis.\n\n The Flight supports Cartopy axis as well with automatic projection. If\n no projection is provided, a default `PlateCarree\n <https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#platecarree>`_\n is applied.\n\n The `resolution` argument may be:\n\n - None for a raw plot;\n - an integer or a string to pass to a `Flight.resample()\n <#traffic.core.Flight.resample>`__ method as a preprocessing\n before plotting;\n - or a dictionary, e.g dict(latitude=4, longitude=4), if you\n want a grid with a resolution of 4 points per latitude and\n longitude degree.\n\n Example usage:\n\n .. code:: python\n\n from traffic.drawing import Mercator\n fig, ax = plt.subplots(1, subplot_kw=dict(projection=Mercator()))\n (\n flight\n .resample(\"1s\")\n .query('altitude > 10000')\n .compute_wind()\n .plot_wind(ax, alpha=.5)\n )\n\n \"\"\"\n\n from cartopy.crs import PlateCarree\n\n if \"projection\" in ax.__dict__ and \"transform\" not in kwargs:\n kwargs[\"transform\"] = PlateCarree()\n\n if any(w not in self.data.columns for w in [\"wind_u\", \"wind_v\"]):\n raise RuntimeError(\n \"No wind data in trajectory. Consider Flight.compute_wind()\"\n )\n\n copy_self: Optional[Flight] = self\n\n if filtered:\n copy_self = self.filter(roll=17)\n if copy_self is None:\n return []\n copy_self = copy_self.query(\"roll.abs() < .5\")\n if copy_self is None:\n return []\n copy_self = copy_self.filter(wind_u=17, wind_v=17)\n\n if copy_self is None:\n return []\n\n if resolution is not None:\n\n if isinstance(resolution, (int, str)):\n data = copy_self.resample(resolution).data\n\n if isinstance(resolution, dict):\n r_lat = resolution.get(\"latitude\", None)\n r_lon = resolution.get(\"longitude\", None)\n\n if r_lat is not None and r_lon is not None:\n data = (\n copy_self.assign(\n latitude=lambda x: (\n (r_lat * x.latitude).round() / r_lat\n ),\n longitude=lambda x: (\n (r_lon * x.longitude).round() / r_lon\n ),\n )\n .groupby([\"latitude\", \"longitude\"])\n .agg(dict(wind_u=\"mean\", wind_v=\"mean\"))\n .reset_index()\n )\n\n return ax.barbs(\n data.longitude.values,\n data.latitude.values,\n data.wind_u.values,\n data.wind_v.values,\n **kwargs,\n )\n\n # -- Distances --\n\n def bearing(\n self, other: PointMixin, column_name: str = \"bearing\"\n ) -> \"Flight\":\n # temporary, should implement full stuff\n size = self.data.shape[0]\n return self.assign(\n **{\n column_name: geo.bearing(\n self.data.latitude.values,\n self.data.longitude.values,\n other.latitude * np.ones(size),\n other.longitude * np.ones(size),\n )\n % 360\n }\n )\n\n @overload\n def distance( # type: ignore\n self, other: None = None, column_name: str = \"distance\"\n ) -> float:\n ...\n\n @overload\n def distance( # noqa: F811\n self,\n other: Union[\"Airspace\", Polygon, PointMixin],\n column_name: str = \"distance\",\n ) -> \"Flight\":\n ...\n\n @overload\n def distance( # noqa: F811\n self, other: \"Flight\", column_name: str = \"distance\"\n ) -> Optional[pd.DataFrame]:\n ...\n\n def distance( # noqa: F811\n self,\n other: Union[None, \"Flight\", \"Airspace\", Polygon, PointMixin] = None,\n column_name: str = \"distance\",\n ) -> Union[None, float, \"Flight\", pd.DataFrame]:\n\n \"\"\"Computes the distance from a Flight to another entity.\n\n The behaviour is different according to the type of the second\n element:\n\n - if the other element is None (i.e. flight.distance()), the method\n returns a distance in nautical miles between the first and last\n recorded positions in the DataFrame.\n\n - if the other element is a Flight, the method returns a pandas\n DataFrame with corresponding data from both flights, aligned\n with their timestamps, and two new columns with `lateral` and\n `vertical` distances (resp. in nm and ft) separating them.\n\n - otherwise, the same Flight is returned enriched with a new\n column (by default, named \"distance\") with the distance of each\n point of the trajectory to the geometrical element.\n\n .. warning::\n\n - An Airspace is (currently) considered as its flattened\n representation\n - Computing a distance to a polygon is quite slow at the moment.\n Consider a strict resampling (e.g. one point per minute, \"1T\")\n before calling the method.\n\n \"\"\"\n\n if other is None:\n first = self.at_ratio(0)\n last = self.at_ratio(1)\n if first is None or last is None:\n return 0\n return (\n geo.distance(\n first.latitude,\n first.longitude,\n last.latitude,\n last.longitude,\n )\n / 1852 # in nautical miles\n )\n\n if isinstance(other, PointMixin):\n size = self.data.shape[0]\n return self.assign(\n **{\n column_name: geo.distance(\n self.data.latitude.values,\n self.data.longitude.values,\n other.latitude * np.ones(size),\n other.longitude * np.ones(size),\n )\n / 1852 # in nautical miles\n }\n )\n\n from .airspace import Airspace # noqa: F811\n\n if isinstance(other, Airspace):\n other = other.flatten()\n\n if isinstance(other, Polygon):\n bounds = other.bounds\n\n projection = pyproj.Proj(\n proj=\"aea\", # equivalent projection\n lat_1=bounds[1],\n lat_2=bounds[3],\n lat_0=(bounds[1] + bounds[3]) / 2,\n lon_0=(bounds[0] + bounds[2]) / 2,\n )\n\n transformer = pyproj.Transformer.from_proj(\n pyproj.Proj(\"epsg:4326\"), projection, always_xy=True\n )\n projected_shape = transform(transformer.transform, other)\n\n self_xy = self.compute_xy(projection)\n\n return self.assign(\n **{\n column_name: list(\n projected_shape.exterior.distance(p)\n * (-1 if projected_shape.contains(p) else 1)\n for p in MultiPoint(\n list(zip(self_xy.data.x, self_xy.data.y))\n )\n )\n }\n )\n\n start = max(self.start, other.start)\n stop = min(self.stop, other.stop)\n f1, f2 = (self.between(start, stop), other.between(start, stop))\n if f1 is None or f2 is None:\n return None\n\n cols = [\"timestamp\", \"latitude\", \"longitude\", \"altitude\"]\n cols += [\"icao24\", \"callsign\"]\n if \"flight_id\" in f1.data.columns:\n cols.append(\"flight_id\")\n table = f1.data[cols].merge(f2.data[cols], on=\"timestamp\")\n\n return table.assign(\n lateral=geo.distance(\n table.latitude_x.values,\n table.longitude_x.values,\n table.latitude_y.values,\n table.longitude_y.values,\n )\n / 1852, # in nautical miles\n vertical=(table.altitude_x - table.altitude_y).abs(),\n )\n\n def cumulative_distance(\n self,\n compute_gs: bool = True,\n compute_track: bool = True,\n *,\n reverse: bool = False,\n **kwargs,\n ) -> \"Flight\":\n\n \"\"\"Enrich the structure with new ``cumdist`` column computed from\n latitude and longitude columns.\n\n The first ``cumdist`` value is 0, then distances are computed (in\n **nautical miles**) and summed between consecutive positions. The last\n value is the total length of the trajectory.\n\n When the ``compute_gs`` flag is set to True (default), an additional\n ``compute_gs`` is also added. This value can be compared with the\n decoded ``groundspeed`` value in ADSB messages.\n\n When the ``compute_track`` flag is set to True (default), an additional\n ``compute_track`` is also added. This value can be compared with the\n decoded ``track`` value in ADSB messages.\n\n \"\"\"\n\n if \"compute_groundspeed\" in kwargs:\n warnings.warn(\"Use compute_gs argument\", DeprecationWarning)\n compute_gs = kwargs[\"compute_groundspeed\"]\n\n cur_sorted = self.sort_values(\"timestamp\", ascending=not reverse)\n coords = cur_sorted.data[[\"timestamp\", \"latitude\", \"longitude\"]]\n\n delta = pd.concat([coords, coords.add_suffix(\"_1\").diff()], axis=1)\n delta_1 = delta.iloc[1:]\n d = geo.distance(\n delta_1.latitude.values,\n delta_1.longitude.values,\n (delta_1.latitude + delta_1.latitude_1).values,\n (delta_1.longitude + delta_1.longitude_1).values,\n )\n\n res = cur_sorted.assign(\n cumdist=np.pad(d.cumsum() / 1852, (1, 0), \"constant\")\n )\n\n if compute_gs:\n gs = d / delta_1.timestamp_1.dt.total_seconds() * (3600 / 1852)\n res = res.assign(compute_gs=np.abs(np.pad(gs, (1, 0), \"edge\")))\n\n if compute_track:\n track = geo.bearing(\n delta_1.latitude.values,\n delta_1.longitude.values,\n (delta_1.latitude + delta_1.latitude_1).values,\n (delta_1.longitude + delta_1.longitude_1).values,\n )\n track = np.where(track > 0, track, 360 + track)\n res = res.assign(\n compute_track=np.abs(np.pad(track, (1, 0), \"edge\"))\n )\n\n return res.sort_values(\"timestamp\", ascending=True)\n\n # -- Geometry operations --\n\n @property\n def linestring(self) -> Optional[LineString]:\n # longitude is implicit I guess\n if \"latitude\" not in self.data.columns:\n return None\n coords = list(self.coords)\n if len(coords) < 2:\n return None\n return LineString(coords)\n\n @property\n def shape(self) -> Optional[LineString]:\n return self.linestring\n\n @property\n def point(self) -> Optional[Position]:\n return self.at()\n\n def simplify(\n self,\n tolerance: float,\n altitude: Optional[str] = None,\n z_factor: float = 3.048,\n return_mask: bool = False,\n ) -> Union[np.ndarray, \"Flight\"]:\n \"\"\"Simplifies a trajectory with Douglas-Peucker algorithm.\n\n The method uses latitude and longitude, projects the trajectory to a\n conformal projection and applies the algorithm. If x and y features are\n already present in the DataFrame (after a call to `compute_xy()\n <#traffic.core.Flight.compute_xy>`_ for instance) then this projection\n is taken into account.\n\n - By default, a 2D version is called, unless you pass a column name for\n ``altitude``.\n - You may scale the z-axis for more relevance (``z_factor``). The\n default value works well in most situations.\n\n The method returns a Flight unless you specify ``return_mask=True``.\n \"\"\"\n\n if \"x\" in self.data.columns and \"y\" in self.data.columns:\n kwargs = dict(x=\"x\", y=\"y\")\n else:\n kwargs = dict(lat=\"latitude\", lon=\"longitude\")\n\n mask = douglas_peucker(\n df=self.data,\n tolerance=tolerance,\n z=altitude,\n z_factor=z_factor,\n **kwargs,\n )\n\n if return_mask:\n return mask\n else:\n return self.__class__(self.data.loc[mask])\n\n def intersects(self, shape: Union[ShapelyMixin, base.BaseGeometry]) -> bool:\n # implemented and monkey-patched in airspace.py\n # given here for consistency in types\n ...\n\n @flight_iterator\n def clip_iterate(\n self, shape: Union[ShapelyMixin, base.BaseGeometry], strict: bool = True\n ) -> Iterator[\"Flight\"]:\n list_coords = list(self.xy_time)\n if len(list_coords) < 2:\n return None\n\n linestring = LineString(list_coords)\n if not isinstance(shape, base.BaseGeometry):\n shape = shape.shape\n\n intersection = linestring.intersection(shape)\n\n if intersection.is_empty:\n return None\n\n if isinstance(intersection, Point):\n return None\n\n if isinstance(intersection, LineString):\n time_list = list(\n datetime.fromtimestamp(t, timezone.utc)\n for t in np.stack(intersection.coords)[:, 2]\n )\n between = self.between(\n min(time_list), max(time_list), strict=strict\n )\n if between is not None:\n yield between\n return None\n\n def _clip_generator() -> Iterable[Tuple[datetime, datetime]]:\n for segment in intersection:\n times: List[datetime] = list(\n datetime.fromtimestamp(t, timezone.utc)\n for t in np.stack(segment.coords)[:, 2]\n )\n yield min(times), max(times)\n\n for t1, t2 in _clip_generator():\n between = self.between(t1, t2, strict=strict)\n if between is not None:\n yield between\n\n def clip(\n self, shape: Union[ShapelyMixin, base.BaseGeometry], strict: bool = True\n ) -> Optional[\"Flight\"]:\n \"\"\"Clips the trajectory to a given shape.\n\n For a shapely Geometry, the first time of entry and the last time of\n exit are first computed before returning the part of the trajectory\n between the two timestamps.\n\n Most of the time, aircraft do not repeatedly come out and in an\n airspace, but computation errors may sometimes give this impression.\n As a consequence, the clipped trajectory may have points outside the\n shape.\n\n .. warning::\n Altitudes are not taken into account.\n\n \"\"\"\n\n t1 = None\n for segment in self.clip_iterate(shape, strict=strict):\n if t1 is None:\n t1 = segment.start\n t2 = segment.stop\n\n if t1 is None:\n return None\n\n clipped_flight = self.between(t1, t2, strict=strict)\n\n if clipped_flight is None or clipped_flight.shape is None:\n return None\n\n return clipped_flight\n\n # -- OpenSky specific methods --\n\n def query_opensky_sensors(self, where_condition: str = \"\") -> pd.DataFrame:\n from ..data import opensky\n\n return (\n opensky.request(\n \"select s.ITEM, count(*) from state_vectors_data4, \"\n \"state_vectors_data4.serials s \"\n f\"where icao24='{self.icao24}' and \"\n f\"{where_condition} \"\n \"{before_time}<=time and time < {after_time} and \"\n \"{before_hour}<=hour and hour < {after_hour} \"\n \"group by s.ITEM;\",\n self.start,\n self.stop,\n columns=[\"serial\", \"count\"],\n )\n .groupby(\"serial\")\n .sum()\n )\n\n def query_opensky(self, **kwargs) -> Optional[\"Flight\"]:\n \"\"\"Returns data from the same Flight as stored in OpenSky database.\n\n This may be useful if you write your own parser for data from a\n different channel. The method will use the ``callsign`` and ``icao24``\n attributes to build a request for current Flight in the OpenSky Network\n database.\n\n The kwargs argument helps overriding arguments from the query, namely\n start, stop, callsign and icao24.\n\n Returns None if no data is found.\n\n .. note::\n Read more about access to the OpenSky Network database `here\n <opensky_impala.html>`_\n \"\"\"\n\n from ..data import opensky\n\n query_params = {\n \"start\": self.start,\n \"stop\": self.stop,\n \"callsign\": self.callsign,\n \"icao24\": self.icao24,\n \"return_flight\": True,\n **kwargs,\n }\n return opensky.history(**query_params)\n\n def query_ehs(\n self,\n data: Union[None, pd.DataFrame, \"RawData\"] = None,\n failure_mode: str = \"warning\",\n progressbar: Union[bool, Callable[[Iterable], Iterable]] = True,\n ) -> \"Flight\":\n \"\"\"Extends data with extra columns from EHS messages.\n\n By default, raw messages are requested from the OpenSky Network\n database.\n\n .. warning::\n Making a lot of small requests can be very inefficient and may look\n like a denial of service. If you get the raw messages using a\n different channel, you can provide the resulting dataframe as a\n parameter. See the page about `OpenSky Impala access\n <opensky_impala.html>`_\n\n The data parameter expect three columns: ``icao24``, ``rawmsg`` and\n ``mintime``, in conformance with the OpenSky API.\n\n .. note::\n Read more about access to the OpenSky Network database `here\n <opensky_impala.html>`_\n \"\"\"\n\n from ..data import opensky\n from ..data.adsb.raw_data import RawData # noqa: F811\n\n if not isinstance(self.icao24, str):\n raise RuntimeError(\"Several icao24 for this flight\")\n\n if not isinstance(self.callsign, str):\n raise RuntimeError(\"Several callsigns for this flight\")\n\n def fail_warning():\n \"\"\"Called when nothing can be added to data.\"\"\"\n id_ = self.flight_id\n if id_ is None:\n id_ = self.callsign\n logging.warning(f\"No data on Impala for flight {id_}.\")\n return self\n\n def fail_silent():\n return self\n\n failure_dict = dict(warning=fail_warning, silent=fail_silent)\n failure = failure_dict[failure_mode]\n\n if data is None:\n ext = opensky.extended(self.start, self.stop, icao24=self.icao24)\n df = ext.data if ext is not None else None\n else:\n df = data if isinstance(data, pd.DataFrame) else data.data\n df = df.query(\n \"icao24 == @self.icao24 and \"\n \"@self.start < mintime < @self.stop\"\n )\n\n if df is None or df.shape[0] == 0:\n return failure()\n\n timestamped_df = df.sort_values(\"mintime\").assign(\n timestamp=lambda df: df.mintime.dt.round(\"s\")\n )\n\n referenced_df = (\n timestamped_df.merge(self.data, on=\"timestamp\", how=\"outer\")\n .sort_values(\"timestamp\")\n .rename(\n columns=dict(\n altitude=\"alt\",\n altitude_y=\"alt\",\n groundspeed=\"spd\",\n track=\"trk\",\n )\n )[[\"timestamp\", \"latitude\", \"longitude\", \"alt\", \"spd\", \"trk\"]]\n .ffill()\n .drop_duplicates() # bugfix! NEVER ERASE THAT LINE!\n .merge(\n timestamped_df[[\"timestamp\", \"icao24\", \"rawmsg\"]],\n on=\"timestamp\",\n how=\"right\",\n )\n )\n\n identifier = (\n self.flight_id if self.flight_id is not None else self.callsign\n )\n\n t = RawData(referenced_df).decode(\n reference=self.origin if isinstance(self.origin, str) else None,\n progressbar=progressbar,\n progressbar_kw=dict(leave=False, desc=f\"{identifier}:\"),\n )\n\n extended = t[self.icao24] if t is not None else None\n if extended is None:\n return failure()\n\n # fix for https://stackoverflow.com/q/53657210/1595335\n if \"last_position\" in self.data.columns:\n extended = extended.assign(last_position=pd.NaT)\n if \"start\" in self.data.columns:\n extended = extended.assign(start=pd.NaT)\n if \"stop\" in self.data.columns:\n extended = extended.assign(stop=pd.NaT)\n\n aggregate = extended + self\n if \"flight_id\" in self.data.columns:\n aggregate.data.flight_id = self.flight_id\n\n # sometimes weird callsigns are decoded and should be discarded\n # so it seems better to filter on callsign rather than on icao24\n flight = aggregate[self.callsign]\n if flight is None:\n return failure()\n\n if self.number is not None:\n flight = flight.assign(number=self.number)\n if self.origin is not None:\n flight = flight.assign(origin=self.origin)\n if self.destination is not None:\n flight = flight.assign(destination=self.destination)\n\n return flight.sort_values(\"timestamp\")\n\n # -- Visualisation --\n\n def plot(\n self, ax: \"GeoAxesSubplot\", **kwargs\n ) -> List[\"Artist\"]: # coverage: ignore\n \"\"\"Plots the trajectory on a Matplotlib axis.\n\n The Flight supports Cartopy axis as well with automatic projection. If\n no projection is provided, a default `PlateCarree\n <https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#platecarree>`_\n is applied.\n\n Example usage:\n\n .. code:: python\n\n from traffic.drawing import Mercator\n fig, ax = plt.subplots(1, subplot_kw=dict(projection=Mercator())\n flight.plot(ax, alpha=.5)\n\n .. note::\n See also `geoencode() <#traffic.core.Flight.geoencode>`_ for the\n altair equivalent.\n\n \"\"\"\n\n from cartopy.crs import PlateCarree\n\n if \"projection\" in ax.__dict__ and \"transform\" not in kwargs:\n kwargs[\"transform\"] = PlateCarree()\n if self.shape is not None:\n return ax.plot(*self.shape.xy, **kwargs)\n return []\n\n def chart(self, *features) -> \"alt.Chart\": # coverage: ignore\n \"\"\"\n Initializes an altair Chart based on Flight data.\n\n The features passed in parameters are dispatched to allow plotting\n multiple features on the same graph.\n\n Example usage:\n\n .. code:: python\n\n # Most simple usage\n flight.chart().encode(alt.Y(\"altitude\"))\n\n # With some configuration\n flight.chart().encode(\n alt.X(\n \"utcyearmonthdatehoursminutes(timestamp)\",\n axis=alt.Axis(title=None, format=\"%H:%M\"),\n ),\n alt.Y(\"altitude\", title=\"altitude (in ft)\"),\n alt.Color(\"callsign\")\n )\n\n For a more complex graph plotting similar physical quantities on the\n same graph, and other quantities on a different graph, the following\n snippet may be of use.\n\n .. code:: python\n\n # More advanced with several plots on the same graph\n base = (\n flight.chart(\"altitude\", \"groundspeed\", \"IAS\")\n .encode(\n alt.X(\n \"utcyearmonthdatehoursminutesseconds(timestamp)\",\n axis=alt.Axis(title=None, format=\"%H:%M\"),\n )\n )\n .properties(height=200)\n )\n\n alt.vconcat(\n base.transform_filter('datum.variable != \"altitude\"').encode(\n alt.Y(\n \"value:Q\",\n axis=alt.Axis(title=\"speed (in kts)\"),\n scale=alt.Scale(zero=False),\n )\n ),\n base.transform_filter('datum.variable == \"altitude\"').encode(\n alt.Y(\"value:Q\", title=\"altitude (in ft)\")\n ),\n )\n\n .. note::\n See also `plot_time() <#traffic.core.Flight.plot_time>`_ for the\n Matplotlib equivalent.\n\n \"\"\"\n import altair as alt\n\n base = alt.Chart(self.data).encode(\n alt.X(\n \"utcyearmonthdatehoursminutesseconds(timestamp)\",\n title='alt.X(\"utcyearmonthdatehoursminutesseconds(timestamp)\")',\n ),\n )\n if len(features) > 0:\n base = base.transform_fold(\n list(features), as_=[\"variable\", \"value\"]\n ).encode(alt.Y(\"value:Q\"), alt.Color(\"variable:N\"))\n\n return base.mark_line()\n\n def encode(self, **kwargs): # coverage: ignore\n \"\"\"\n DEPRECATED: Use Flight.chart() method instead.\n \"\"\"\n raise DeprecationWarning(\"Use Flight.chart() method instead\")\n\n def plot_time(\n self,\n ax: \"Axes\",\n y: Union[str, List[str]],\n secondary_y: Union[None, str, List[str]] = None,\n **kwargs,\n ) -> None: # coverage: ignore\n \"\"\"Plots the given features according to time.\n\n The method ensures:\n\n - only non-NaN data are displayed (no gap in the plot);\n - the timestamp is naively converted to UTC if not localized.\n\n Example usage:\n\n .. code:: python\n\n ax = plt.axes()\n # most simple version\n flight.plot(ax, 'altitude')\n # or with several comparable features and twin axes\n flight.plot(\n ax, ['altitude', 'groundspeed, 'IAS', 'TAS'],\n secondary_y=['altitude']\n )\n\n .. note::\n See also `chart() <#traffic.core.Flight.chart>`_ for the altair\n equivalent.\n\n \"\"\"\n if isinstance(y, str):\n y = [y]\n if isinstance(secondary_y, str):\n secondary_y = [secondary_y]\n if secondary_y is None:\n secondary_y = []\n\n localized = self.data.timestamp.dt.tz is not None\n for column in y:\n kw = {\n **kwargs,\n **dict(\n y=column,\n secondary_y=column if column in secondary_y else \"\",\n ),\n }\n subtab = self.data.query(f\"{column} == {column}\")\n\n if localized:\n (\n subtab.assign(\n timestamp=lambda df: df.timestamp.dt.tz_convert(\"utc\")\n ).plot(ax=ax, x=\"timestamp\", **kw)\n )\n else:\n (\n subtab.assign(\n timestamp=lambda df: df.timestamp.dt.tz_localize(\n datetime.now().astimezone().tzinfo\n ).dt.tz_convert(\"utc\")\n ).plot(ax=ax, x=\"timestamp\", **kw)\n )\n\n @classmethod\n def from_file(\n cls: Type[T], filename: Union[Path, str], **kwargs\n ) -> Optional[T]:\n\n \"\"\"Read data from various formats.\n\n This class method dispatches the loading of data in various format to\n the proper ``pandas.read_*`` method based on the extension of the\n filename.\n\n - .pkl and .pkl.gz dispatch to ``pandas.read_pickle``;\n - .parquet and .parquet.gz dispatch to ``pandas.read_parquet``;\n - .json and .json.gz dispatch to ``pandas.read_json``;\n - .csv and .csv.gz dispatch to ``pandas.read_csv``;\n - .h5 dispatch to ``pandas.read_hdf``.\n\n Other extensions return ``None``.\n Specific arguments may be passed to the underlying ``pandas.read_*``\n method with the kwargs argument.\n\n Example usage:\n\n >>> t = Flight.from_file(\"example_flight.csv\")\n \"\"\"\n\n tentative = super().from_file(filename, **kwargs)\n if tentative is None:\n return None\n\n # Special treatment for flights to download from flightradar24\n cols_fr24 = {\n \"Altitude\",\n \"Callsign\",\n \"Direction\",\n \"Position\",\n \"Speed\",\n \"Timestamp\",\n \"UTC\",\n }\n if set(tentative.data.columns) != cols_fr24:\n return tentative\n\n latlon = tentative.data.Position.str.split(pat=\",\", expand=True)\n return (\n tentative.assign(\n latitude=latlon[0].astype(float),\n longitude=latlon[1].astype(float),\n timestamp=lambda df: pd.to_datetime(df.UTC),\n )\n .rename(\n columns={\n \"UTC\": \"timestamp\",\n \"Altitude\": \"altitude\",\n \"Callsign\": \"callsign\",\n \"Speed\": \"groundspeed\",\n \"Direction\": \"track\",\n }\n )\n .drop(columns=[\"Timestamp\", \"Position\"])\n )\n",
"import warnings\nfrom operator import attrgetter\nfrom typing import (\n TYPE_CHECKING,\n Iterable,\n Iterator,\n List,\n Optional,\n Sequence,\n Union,\n cast,\n)\n\nimport numpy as np\nimport pandas as pd\nfrom shapely.geometry import LineString, MultiLineString, Point, Polygon\n\nfrom ..core.geodesy import destination, mrr_diagonal\nfrom ..core.iterator import flight_iterator\nfrom ..core.time import deltalike, to_timedelta\n\nif TYPE_CHECKING:\n from ..core import Flight, FlightPlan # noqa: 401\n from ..core.mixins import PointMixin # noqa: 401\n from ..core.structure import Airport, Navaid # noqa: 401\n from ..data import Navaids # noqa: 401\n from ..data.basic.airports import Airports # noqa: 401\n\n\nclass NavigationFeatures:\n\n # shape: Optional[LineString]\n # query: Callable[[\"NavigationFeatures\", str], Optional[\"Flight\"]]\n\n def closest_point(\n self, points: Union[List[\"PointMixin\"], \"PointMixin\"]\n ) -> pd.Series:\n \"\"\"Selects the closest point of the trajectory with respect to\n a point or list of points.\n\n The pd.Series returned by the function is enriched with two fields:\n distance (in meters) and point (containing the name of the closest\n point to the trajectory)\n\n Example usage:\n\n .. code:: python\n\n >>> item = belevingsvlucht.between(\n ... \"2018-05-30 16:00\", \"2018-05-30 17:00\"\n ... ).closest_point( # type: ignore\n ... [\n ... airports[\"EHLE\"], # type: ignore\n ... airports[\"EHAM\"], # type: ignore\n ... navaids[\"NARAK\"], # type: ignore\n ... ]\n ... )\n >>> f\"{item.point}, {item.distance:.2f}m\"\n \"Lelystad Airport, 49.11m\"\n\n \"\"\"\n from ..core.distance import closest_point as cp\n\n # The following cast secures the typing\n self = cast(\"Flight\", self)\n\n if not isinstance(points, list):\n points = [points]\n\n return min(\n (cp(self.data, point) for point in points),\n key=attrgetter(\"distance\"),\n )\n\n # -- Most basic metadata properties --\n\n def takeoff_from(self, airport: Union[str, \"Airport\"]) -> bool:\n \"\"\"Returns True if the flight takes off from the given airport.\"\"\"\n\n from ..core.structure import Airport\n from ..data import airports\n\n return self.takeoff_airport() == (\n airport if isinstance(airport, Airport) else airports[airport]\n )\n\n def takeoff_airport(self, **kwargs) -> \"Airport\":\n \"\"\"Returns the most probable takeoff airport based on the first location\n in the trajectory.\n\n .. code:: python\n\n >>> belevingsvlucht.takeoff_airport()\n EHAM/AMS: Amsterdam Schiphol\n\n When data is missing near the ground, it may be relevant\n to specify a subset of airports as a keyword parameter.\n\n .. code:: python\n\n >>> missing_data = belevingsvlucht.after(\"2018-05-30 15:30\")\n >>> missing_data.takeoff_airport()\n NL-0015/nan: Universitair Medisch Centrum Utrecht Heliport\n\n >>> large_airports = airports.query(\"type == 'large_airport'\")\n >>> missing_data.takeoff_airport(dataset=large_airports)\n EHAM/AMS: Amsterdam Schiphol\n \"\"\"\n\n from ..core.distance import guess_airport\n\n # The following cast secures the typing\n self = cast(\"Flight\", self)\n\n data = self.data.sort_values(\"timestamp\")\n return guess_airport(data.iloc[0], **kwargs)\n\n def landing_at(self, airport: Union[str, \"Airport\"]) -> bool:\n \"\"\"Returns True if the flight lands at the given airport.\"\"\"\n\n from ..core.structure import Airport\n from ..data import airports\n\n return self.landing_airport() == (\n airport if isinstance(airport, Airport) else airports[airport]\n )\n\n def landing_airport(self, **kwargs) -> \"Airport\":\n \"\"\"Returns the most probable landing airport based on the last location\n in the trajectory.\n\n .. code:: python\n\n >>> belevingsvlucht.landing_airport()\n EHAM/AMS: Amsterdam Schiphol\n\n When data is missing near the ground, it may be relevant\n to specify a subset of airports as a keyword parameter.\n\n .. code:: python\n\n >>> missing_data = belevingsvlucht.before(\"2018-05-30 20:00\")\n >>> missing_data.landing_airport()\n NL-0024/nan: Middenmeer Aerodrome\n\n >>> large_airports = airports.query(\"type == 'large_airport'\")\n >>> missing_data.landing_airport(dataset=large_airports)\n EHAM/AMS: Amsterdam Schiphol\n \"\"\"\n\n from ..core.distance import guess_airport\n\n # The following cast secures the typing\n self = cast(\"Flight\", self)\n\n data = self.data.sort_values(\"timestamp\")\n return guess_airport(data.iloc[-1], **kwargs)\n\n # -- Alignments --\n\n @flight_iterator\n def aligned_on_runway(\n self, airport: Union[str, \"Airport\"]\n ) -> Iterator[\"Flight\"]:\n \"\"\"Iterates on all segments of trajectory matching a runway of the\n given airport.\n\n Example usage:\n\n >>> sum(1 for _ in belevingsvlucht.aligned_on_runway(\"EHAM\"))\n 2\n \"\"\"\n\n from ..data import airports\n\n # The following cast secures the typing\n self = cast(\"Flight\", self)\n\n _airport = airports[airport] if isinstance(airport, str) else airport\n if _airport is None or _airport.runways.shape.is_empty:\n return None\n\n if isinstance(_airport.runways.shape, LineString):\n candidate_shapes = [\n LineString(list(self.xy_time)).intersection(\n _airport.runways.shape.buffer(5e-4)\n )\n ]\n else:\n candidate_shapes = [\n LineString(list(self.xy_time)).intersection(\n on_runway.buffer(5e-4)\n )\n for on_runway in _airport.runways.shape\n ]\n\n for intersection in candidate_shapes:\n if intersection.is_empty:\n continue\n if isinstance(intersection, LineString):\n (*_, start), *_, (*_, stop) = intersection.coords\n segment = self.between(start, stop, strict=False)\n if segment is not None:\n yield segment\n if isinstance(intersection, MultiLineString):\n (*_, start), *_, (*_, stop) = intersection[0].coords\n for chunk in intersection:\n (*_, start_bak), *_, (*_, stop) = chunk.coords\n if stop - start > 40: # crossing runways and back\n start = start_bak\n segment = self.between(start, stop, strict=False)\n if segment is not None:\n yield segment\n\n # >>>>> This function is to be deprecated\n\n def on_runway(self, airport: Union[str, \"Airport\"]) -> Optional[\"Flight\"]:\n \"\"\"Returns the longest segment of trajectory which perfectly matches\n a runway at given airport.\n\n .. code:: python\n\n >>> landing = belevingsvlucht.last(minutes=30).on_runway(\"EHAM\")\n >>> landing.mean(\"altitude\")\n -26.0\n\n >>> takeoff = belevingsvlucht.first(minutes=30).on_runway(\"EHAM\")\n >>> takeoff.mean(\"altitude\")\n 437.27272727272725\n\n \"\"\"\n msg = \"Use .aligned_on_runway(airport).max() instead.\"\n warnings.warn(msg, DeprecationWarning)\n\n return max(\n self.aligned_on_runway(airport),\n key=attrgetter(\"duration\"),\n default=None,\n )\n\n # --- end ---\n\n @flight_iterator\n def aligned_on_ils(\n self,\n airport: Union[None, str, \"Airport\"],\n ) -> Iterator[\"Flight\"]:\n \"\"\"Iterates on all segments of trajectory aligned with the ILS of the\n given airport. The runway number is appended as a new ``ILS`` column.\n\n Example usage:\n\n .. code:: python\n\n >>> aligned = belevingsvlucht.aligned_on_ils('EHAM').next()\n >>> f\"ILS {aligned.max('ILS')} until {aligned.stop:%H:%M}\"\n 'ILS 06 until 20:17'\n\n Be aware that all segments are not necessarily yielded in order.\n Consider using ``max(..., key=attrgetter('start'))`` if you want the\n last landing attempt, or ``sorted(..., key=attrgetter('start'))`` for\n an ordered list\n\n .. code:: python\n\n >>> for aligned in belevingsvlucht.aligned_on_ils('EHLE'):\n ... print(aligned.start)\n 2018-05-30 16:50:44+00:00\n 2018-05-30 18:13:02+00:00\n 2018-05-30 16:00:55+00:00\n 2018-05-30 17:21:17+00:00\n 2018-05-30 19:05:22+00:00\n 2018-05-30 19:42:36+00:00\n\n >>> from operator import attrgetter\n >>> last_aligned = max(\n ... belevingsvlucht.aligned_on_ils(\"EHLE\"),\n ... key=attrgetter('start')\n ... )\n \"\"\"\n\n from ..data import airports\n\n # The following cast secures the typing\n self = cast(\"Flight\", self)\n\n if airport is None:\n airport = self.landing_airport()\n\n _airport = airports[airport] if isinstance(airport, str) else airport\n if (\n _airport is None\n or _airport.runways is None\n or _airport.runways.shape.is_empty\n ):\n return None\n\n rad = np.pi / 180\n\n chunks = list()\n for threshold in _airport.runways.list:\n tentative = (\n self.bearing(threshold)\n .distance(threshold)\n .assign(\n b_diff=lambda df: df.distance\n * np.radians(df.bearing - threshold.bearing).abs()\n )\n .query(f\"b_diff < .1 and cos((bearing - track) * {rad}) > 0\")\n )\n if tentative is not None:\n for chunk in tentative.split(\"20s\"):\n if (\n chunk.longer_than(\"1 minute\")\n and chunk.altitude_min < 5000\n ):\n chunks.append(\n chunk.assign(\n ILS=threshold.name, airport=_airport.icao\n )\n )\n\n yield from sorted(chunks, key=attrgetter(\"start\"))\n\n @flight_iterator\n def aligned_on_navpoint(\n self,\n points: Union[\"PointMixin\", Iterable[\"PointMixin\"], \"FlightPlan\"],\n angle_precision: int = 1,\n time_precision: str = \"2T\",\n min_time: str = \"30s\",\n min_distance: int = 80,\n ) -> Iterator[\"Flight\"]:\n \"\"\"Iterates on segments of trajectories aligned with one of the given\n navigational beacons passed in parameter.\n\n The name of the navigational beacon is assigned in a new column\n `navaid`.\n\n \"\"\"\n\n from ..core import FlightPlan\n from ..core.mixins import PointMixin\n\n points_: Sequence[PointMixin]\n\n # The following cast secures the typing\n self = cast(\"Flight\", self)\n\n if isinstance(points, PointMixin):\n points_ = [points]\n elif isinstance(points, FlightPlan):\n points_ = points.all_points\n else:\n points_ = list(points)\n\n for navpoint in points_:\n tentative = (\n self.distance(navpoint)\n .bearing(navpoint)\n .assign(\n shift=lambda df: df.distance\n * (np.radians(df.bearing - df.track).abs()),\n delta=lambda df: (df.bearing - df.track).abs(),\n )\n .query(f\"delta < {angle_precision} and distance < 500\")\n )\n if tentative is not None:\n for chunk in tentative.split(time_precision):\n if (\n chunk.longer_than(min_time)\n and chunk.min(\"distance\") < min_distance\n ):\n yield chunk.assign(navaid=navpoint.name)\n\n def compute_navpoints(\n self, navaids: Optional[\"Navaids\"] = None, buffer: float = 0.1\n ) -> Optional[pd.DataFrame]:\n\n \"\"\"This functions recomputes the most probable alignments on\n navigational points on the trajectory.\n\n By default, all navaids of the default database are considered,\n but limited to a buffered bounding box around the trajectory.\n\n Once computed, the following Altair snippet may be useful to\n display the trajectory as a succession of segments:\n\n .. code:: python\n\n import altair as alt\n\n df = flight.compute_navpoints()\n\n segments = (\n alt.Chart(df.drop(columns=\"duration\")).encode(\n alt.X(\"start\", title=None),\n alt.X2(\"stop\"),\n alt.Y(\"navaid\", sort=\"x\", title=None),\n alt.Color(\"type\", title=\"Navigational point\"),\n alt.Tooltip([\"navaid\", \"distance\", \"shift_mean\"]),\n )\n .mark_bar(size=10)\n .configure_legend(\n orient=\"bottom\",\n labelFontSize=14, titleFontSize=14, labelFont=\"Ubuntu\"\n )\n .configure_axis(labelFontSize=14, labelFont=\"Ubuntu\")\n )\n\n \"\"\"\n\n # The following cast secures the typing\n self = cast(\"Flight\", self)\n\n if navaids is None:\n from ..data import navaids as default_navaids\n\n navaids = default_navaids\n\n navaids_ = navaids.extent(self, buffer=buffer)\n if navaids_ is None:\n return None\n navaids_ = navaids_.drop_duplicates(\"name\")\n all_points: List[\"Navaid\"] = list(navaids_)\n\n def all_aligned_segments(traj: \"Flight\") -> pd.DataFrame:\n return pd.DataFrame.from_records(\n list(\n {\n \"start\": segment.start,\n \"stop\": segment.stop,\n \"duration\": segment.duration,\n \"navaid\": segment.max(\"navaid\"),\n \"distance\": segment.min(\"distance\"),\n \"shift_mean\": segment.shift_mean,\n \"shift_meanp\": segment.shift_mean + 0.02,\n }\n for segment in traj.aligned_on_navpoint(all_points)\n )\n ).sort_values(\"start\")\n\n def groupby_intervals(table: pd.DataFrame) -> Iterator[pd.DataFrame]:\n if table.shape[0] == 0:\n return\n table = table.sort_values(\"start\")\n # take as much as you can\n sweeping_line = table.query(\"stop <= stop.iloc[0]\")\n # try to push the stop line: which intervals overlap the stop line?\n additional = table.query(\n \"start <= @sweeping_line.stop.max() < stop\"\n )\n\n while additional.shape[0] > 0:\n sweeping_line = table.query(\"stop <= @additional.stop.max()\")\n additional = table.query(\n \"start <= @sweeping_line.stop.max() < stop\"\n )\n\n yield sweeping_line\n yield from groupby_intervals(\n table.query(\"start > @sweeping_line.stop.max()\")\n )\n\n def most_probable_navpoints(traj: \"Flight\") -> Iterator[pd.DataFrame]:\n table = all_aligned_segments(traj)\n for block in groupby_intervals(table):\n d_max = block.eval(\"duration.max()\")\n t_threshold = d_max - pd.Timedelta(\"30s\") # noqa: F841\n yield block.sort_values(\"shift_mean\").query(\n \"duration >= @t_threshold\"\n ).head(1)\n\n return pd.concat(list(most_probable_navpoints(self))).merge(\n navaids_.data, left_on=\"navaid\", right_on=\"name\"\n )\n\n @flight_iterator\n def takeoff_from_runway(\n self,\n airport: Union[str, \"Airport\"],\n threshold_alt: int = 2000,\n zone_length: int = 6000,\n little_base: int = 50,\n opening: float = 5,\n ) -> Iterator[\"Flight\"]:\n \"\"\"Identifies the take-off runway for trajectories.\n\n Iterates on all segments of trajectory matching a zone around a runway\n of the given airport. The takeoff runway number is appended as a new\n ``runway`` column.\n\n \"\"\"\n\n from ..data import airports\n\n # Donne les fonctions possibles sur un flight object\n self = cast(\"Flight\", self).phases()\n\n _airport = airports[airport] if isinstance(airport, str) else airport\n if _airport is None or _airport.runways.shape.is_empty:\n return None\n\n nb_run = len(_airport.runways.data)\n alt = _airport.altitude + threshold_alt\n base = zone_length * np.tan(opening * np.pi / 180) + little_base\n\n # Il faut créer les formes autour de chaque runway\n list_p0 = destination(\n list(_airport.runways.data.latitude),\n list(_airport.runways.data.longitude),\n list(_airport.runways.data.bearing),\n [zone_length for i in range(nb_run)],\n )\n list_p1 = destination(\n list(_airport.runways.data.latitude),\n list(_airport.runways.data.longitude),\n [x + 90 for x in list(_airport.runways.data.bearing)],\n [little_base for i in range(nb_run)],\n )\n list_p2 = destination(\n list(_airport.runways.data.latitude),\n list(_airport.runways.data.longitude),\n [x - 90 for x in list(_airport.runways.data.bearing)],\n [little_base for i in range(nb_run)],\n )\n list_p3 = destination(\n list_p0[0],\n list_p0[1],\n [x - 90 for x in list(_airport.runways.data.bearing)],\n [base for i in range(nb_run)],\n )\n list_p4 = destination(\n list_p0[0],\n list_p0[1],\n [x + 90 for x in list(_airport.runways.data.bearing)],\n [base for i in range(nb_run)],\n )\n\n runway_polygons = {}\n\n for i, name in enumerate(_airport.runways.data.name):\n lat = [list_p1[0][i], list_p2[0][i], list_p3[0][i], list_p4[0][i]]\n lon = [list_p1[1][i], list_p2[1][i], list_p3[1][i], list_p4[1][i]]\n\n poly = Polygon(zip(lon, lat))\n runway_polygons[name] = poly\n\n low_traj = self.query(\n f\"(phase == 'CLIMB' or phase == 'LEVEL') and altitude < {alt}\"\n )\n\n if low_traj is None:\n return\n\n for segment in low_traj.split(\"2T\"):\n candidates_set = []\n for name, polygon in runway_polygons.items():\n\n if segment.intersects(polygon):\n candidate = (\n segment.cumulative_distance()\n .clip_iterate(polygon)\n .max(key=\"compute_gs_max\")\n )\n if candidate is None or candidate.shape is None:\n continue\n start_runway = candidate.aligned_on_runway(\"LSZH\").max()\n\n if start_runway is not None:\n candidate = candidate.after(start_runway.start)\n if candidate is None or candidate.shape is None:\n continue\n if candidate.max(\"compute_gs\") < 140:\n continue\n\n candidates_set.append(candidate.assign(runway=name))\n\n result = max(\n candidates_set, key=attrgetter(\"duration\"), default=None\n )\n if result is not None:\n yield result\n\n # -- Special operations --\n\n @flight_iterator\n def emergency(self) -> Iterator[\"Flight\"]:\n \"\"\"Iterates on emergency segments of trajectory.\n\n An emergency is defined with a 7700 squawk code.\n \"\"\"\n sq7700 = self.query(\"squawk == '7700'\") # type: ignore\n if sq7700 is None:\n return\n yield from sq7700.split()\n\n @flight_iterator\n def runway_change(\n self,\n airport: Union[str, \"Airport\", None] = None,\n dataset: Optional[\"Airports\"] = None,\n ) -> Iterator[\"Flight\"]:\n \"\"\"Detects runway changes.\n\n The method yields pieces of trajectories with exactly two runway\n alignments on the same airport not separated by a climbing phase.\n\n In each piece of yielded trajectory, the `ILS` column contains the\n name of the runway targetted by the aircraft at each instant.\n \"\"\"\n\n # The following cast secures the typing\n self = cast(\"Flight\", self)\n\n if airport is None:\n if dataset is None:\n airport = self.landing_airport()\n else:\n airport = self.landing_airport(dataset=dataset)\n\n if airport is None:\n return None\n\n aligned = iter(self.aligned_on_ils(airport))\n first = next(aligned, None)\n if first is None:\n return\n\n for second in aligned:\n candidate = self.between(first.start, second.stop)\n assert candidate is not None\n candidate = candidate.assign(ILS=None)\n if candidate.phases().query('phase == \"CLIMB\"') is None:\n candidate.data.loc[\n candidate.data.timestamp <= first.stop, \"ILS\"\n ] = first.max(\"ILS\")\n candidate.data.loc[\n candidate.data.timestamp >= second.start, \"ILS\"\n ] = second.max(\"ILS\")\n\n yield candidate.assign(\n airport=airport\n if isinstance(airport, str)\n else airport.icao\n )\n\n first = second\n\n @flight_iterator\n def go_around(\n self,\n airport: Union[str, \"Airport\", None] = None,\n dataset: Optional[\"Airports\"] = None,\n ) -> Iterator[\"Flight\"]:\n \"\"\"Detects go-arounds.\n\n The method yields pieces of trajectories with exactly two landing\n attempts (aligned on one runway) on the same airport separated by\n exactly one climbing phase.\n \"\"\"\n\n # The following cast secures the typing\n self = cast(\"Flight\", self)\n\n if airport is None:\n if dataset is None:\n airport = self.landing_airport()\n else:\n airport = self.landing_airport(dataset=dataset)\n\n if airport is None:\n return None\n\n first_attempt = next(self.aligned_on_ils(airport), None)\n\n while first_attempt is not None:\n after_first_attempt = self.after(first_attempt.start)\n assert after_first_attempt is not None\n\n climb = after_first_attempt.phases().query('phase == \"CLIMB\"')\n if climb is None:\n return\n\n after_climb = self.after(next(climb.split(\"10T\")).stop)\n if after_climb is None:\n return\n\n next_attempt = next(after_climb.aligned_on_ils(airport), None)\n\n if next_attempt is not None:\n goaround = self.between(first_attempt.start, next_attempt.stop)\n assert goaround is not None\n\n goaround = goaround.assign(\n ILS=None,\n airport=airport\n if isinstance(airport, str)\n else airport.icao,\n )\n goaround.data.loc[\n goaround.data.timestamp <= first_attempt.stop, \"ILS\"\n ] = first_attempt.max(\"ILS\")\n goaround.data.loc[\n goaround.data.timestamp >= next_attempt.start, \"ILS\"\n ] = next_attempt.max(\"ILS\")\n yield goaround\n\n first_attempt = next_attempt\n\n @flight_iterator\n def landing_attempts(\n self, dataset: Optional[\"Airports\"] = None\n ) -> Iterator[\"Flight\"]:\n \"\"\"Iterates on all landing attempts for current flight.\n\n First, candidates airports are identified in the neighbourhood\n of the segments of trajectory below 10,000 ft. By default, the\n full airport database is considered but it is possible to restrict\n it and pass a smaller database with the dataset parameter.\n\n If no runway information is available for the given airport, no\n trajectory segment will be provided.\n\n .. warning::\n\n This API is not stable yet. The interface may change in a near\n future.\n\n \"\"\"\n candidate = self.query(\"altitude < 8000\") # type: ignore\n if candidate is not None:\n for chunk in candidate.split(\"10T\"):\n point = chunk.query(\"altitude == altitude.min()\")\n if dataset is None:\n cd = point.landing_airport()\n else:\n cd = point.landing_airport(dataset=dataset)\n if cd.runways is not None:\n yield from chunk.assign(airport=cd.icao).aligned_on_ils(cd)\n\n def diversion(self) -> Optional[\"Flight\"]:\n \"\"\"Returns the segment of trajectory after a possible decision\n of diversion.\n\n The method relies on the `destination` parameter to identify the\n intended destination.\n\n \"\"\"\n from ..data import airports\n\n f_above = self.query(\"altitude > 15000\") # type: ignore\n if (\n self.destination != self.destination # type: ignore\n or airports[self.destination] is None # type: ignore\n or f_above is None\n ):\n return None\n\n return (\n f_above.distance(airports[self.destination]) # type: ignore\n .diff(\"distance\")\n .agg_time(\"10T\", distance_diff=\"mean\")\n .query(\"distance_diff > 0\")\n )\n\n def diversion_ts(self) -> pd.Timestamp:\n diversion = self.diversion()\n if diversion is None:\n return pd.Timestamp(\"NaT\")\n return diversion.start\n\n @property\n def holes(self) -> int:\n \"\"\"Returns the number of 'holes' in a trajectory.\"\"\"\n simplified: \"Flight\" = self.simplify(25) # type: ignore\n if simplified.shape is None:\n return -1\n return len(simplified.shape.buffer(1e-3).interiors)\n\n @flight_iterator\n def holding_pattern(\n self,\n min_altitude=7000,\n turning_threshold=0.5,\n low_limit=pd.Timedelta(\"30 seconds\"), # noqa: B008\n high_limit=pd.Timedelta(\"10 minutes\"), # noqa: B008\n turning_limit=pd.Timedelta(\"5 minutes\"), # noqa: B008\n ) -> Iterator[\"Flight\"]:\n \"\"\"Iterates on parallel segments candidates for identifying\n a holding pattern.\n\n .. warning::\n\n This API is not stable yet. The interface may change in a near\n future.\n\n \"\"\"\n # avoid parts that are really way too low\n alt_above = self.query(f\"altitude > {min_altitude}\") # type: ignore\n if alt_above is None:\n return\n\n straight_line = (\n alt_above.unwrap()\n .assign(\n turning_rate=lambda x: x.track_unwrapped.diff()\n / x.timestamp.diff().dt.total_seconds()\n )\n .filter(turning_rate=17)\n .query(f\"turning_rate.abs() < {turning_threshold}\")\n )\n if straight_line is None:\n return\n\n chunk_candidates = list(\n (chunk.start, chunk.duration, chunk.mean(\"track_unwrapped\"), chunk)\n for chunk in straight_line.split(\"10s\")\n if low_limit <= chunk.duration < high_limit\n )\n\n next_ = None\n for (\n (start1, duration1, track1, chunk1),\n (start2, _, track2, chunk2),\n ) in zip(chunk_candidates, chunk_candidates[1:]):\n if (\n start2 - start1 - duration1 < turning_limit\n and abs(abs(track1 - track2) - 180) < 15\n ):\n yield chunk1\n next_ = chunk2\n else:\n if next_ is not None:\n yield next_\n next_ = None\n\n # -- Airport ground operations specific methods --\n\n @flight_iterator\n def on_parking_position(\n self,\n airport: Union[str, \"Airport\"],\n buffer_size: float = 1e-4, # degrees\n ) -> Iterator[\"Flight\"]:\n \"\"\"\n Generates possible parking positions at a given airport.\n\n Example usage:\n\n >>> parking = flight.on_parking_position('LSZH').max()\n # returns the most probable parking position in terms of duration\n\n .. warning::\n\n This method has been well tested for aircraft taking off, but should\n be double checked for landing trajectories.\n\n \"\"\"\n from ..data import airports\n\n # Donne les fonctions possibles sur un flight object\n self = cast(\"Flight\", self)\n\n _airport = airports[airport] if isinstance(airport, str) else airport\n if _airport is None or _airport.runways.shape.is_empty:\n return None\n\n segment = self.filter().inside_bbox(_airport)\n if segment is None:\n return None\n\n segment = segment.split().max()\n\n parking_positions = _airport.parking_position\n for _, p in parking_positions.data.iterrows():\n if segment.intersects(p.geometry.buffer(buffer_size)):\n parking_part = segment.clip(p.geometry.buffer(buffer_size))\n if parking_part is not None:\n yield parking_part.assign(parking_position=p.ref)\n\n def moving(\n self,\n speed_threshold: float = 2,\n time_threshold: str = \"30s\",\n filter_dict=dict(compute_gs=3),\n resample_rule: str = \"5s\",\n ) -> Optional[\"Flight\"]:\n \"\"\"\n Returns the part of the trajectory after the aircraft starts moving.\n\n .. warning::\n\n This method has been extensively tested on aircraft taxiing before\n take-off. It should be adapted/taken with extra care for\n trajectories after landing.\n\n \"\"\"\n\n self = cast(\"Flight\", self)\n\n resampled = self.resample(resample_rule)\n if resampled is None or len(resampled) <= 2:\n return None\n\n moving = (\n resampled.cumulative_distance()\n .filter(**filter_dict)\n .query(f\"compute_gs > {speed_threshold}\")\n )\n if moving is None:\n return None\n\n segment = None\n first_segment = None\n for segment in moving.split(\"1T\"):\n if segment.longer_than(time_threshold) and first_segment is None:\n first_segment = segment\n last_segment = segment\n\n if first_segment is None or last_segment is None:\n return None\n\n return self.between(first_segment.start, last_segment.stop)\n\n def pushback(\n self,\n airport: Union[str, \"Airport\"],\n filter_dict=dict(\n compute_track_unwrapped=21, compute_track=21, compute_gs=21\n ),\n track_threshold: float = 90,\n ) -> Optional[\"Flight\"]:\n \"\"\"\n Returns the pushback part of the trajectory on ground.\n\n The method identifies the start of the movement, the parking_position\n and the moment the aircraft suddenly changes direction the computed\n track angle.\n\n .. warning::\n\n The method has poor performance when trajectory point on ground are\n lacking. This is often the case for data recorded from locations far\n from the airport.\n\n \"\"\"\n\n from ..data import airports\n\n # Donne les fonctions possibles sur un flight object\n self = cast(\"Flight\", self)\n\n _airport = airports[airport] if isinstance(airport, str) else airport\n if _airport is None or _airport.runways.shape.is_empty:\n return None\n\n within_airport = self.inside_bbox(_airport)\n if within_airport is None:\n return None\n\n parking_position = within_airport.on_parking_position(_airport).next()\n if parking_position is None:\n return None\n\n after_parking = within_airport.after(parking_position.start)\n assert after_parking is not None\n\n in_movement = after_parking.moving()\n\n if in_movement is None:\n return None\n\n direction_change = (\n # trim the first few seconds to avoid annoying first spike\n in_movement.first(\"5T\")\n .last(\"4T30s\")\n .cumulative_distance()\n .unwrap([\"compute_track\"])\n .filter(**filter_dict)\n .diff(\"compute_track_unwrapped\")\n .query(f\"compute_track_unwrapped_diff.abs() > {track_threshold}\")\n )\n\n if direction_change is None:\n return None\n\n return in_movement.before(direction_change.start).assign(\n parking_position=parking_position.parking_position_max\n )\n\n def is_from_inertial(self, freq_threshold=0.05) -> bool:\n \"\"\"\n Returns True if ground trajectory data looks noisy.\n\n .. warning::\n\n This method is still experimental and tries to catch trajectories\n based on the inertial system rather than the GPS. It catches zig-zag\n patterns but fails to get trajectories driving between taxiways.\n\n \"\"\"\n self = cast(\"Flight\", self)\n\n if \"compute_track\" not in self.data.columns:\n self = self.cumulative_distance(compute_gs=False)\n\n freq = (\n self.diff(\"compute_track\")\n .compute_track_diff.round()\n .value_counts(normalize=True)\n )\n if 90 not in freq.index or -90 not in freq.index:\n return False\n return freq[90] > freq_threshold and freq[-90] > freq_threshold\n\n @flight_iterator\n def slow_taxi(\n self,\n min_duration: deltalike = \"60s\",\n max_diameter: float = 150, # in meters\n ) -> Iterator[\"Flight\"]:\n \"\"\"\n Holding segments are part of a trajectory where the aircraft stays more\n than min_duration (in s) within a circle of diameter max_diameter (in m)\n\n \"\"\"\n self = cast(\"Flight\", self)\n\n duration_threshold = to_timedelta(min_duration)\n\n current_flight = self.moving()\n if current_flight is None:\n return None\n\n current_flight = current_flight.onground()\n if current_flight is None:\n return None\n\n current_flight = current_flight.resample(\"5s\")\n if current_flight is None:\n return None\n\n traj_df = (\n current_flight.data[[\"timestamp\", \"latitude\", \"longitude\"]]\n .sort_values(\"timestamp\")\n .set_index(\"timestamp\")\n )\n\n segment_geoms = []\n segment_times = []\n\n # Variables to detect changes between a stop\n # segment and a moving segment\n is_stopped = False\n previously_stopped = False\n\n # iterate over each coordinate to create segments\n # Each data point is added to a queue (FIFO)\n for index, row in traj_df.iterrows():\n segment_geoms.append(Point(row.longitude, row.latitude))\n segment_times.append(index)\n\n if not is_stopped: # remove points to the specified min_duration\n while (\n len(segment_geoms) > 2\n and segment_times[-1] - segment_times[0]\n >= duration_threshold\n ):\n segment_geoms.pop(0)\n segment_times.pop(0)\n\n # Check if current segment, trimmed to have a duration shorthen than\n # min_duration threshold, is longer than the maximum distance\n # threshold\n if (\n len(segment_geoms) > 1\n and mrr_diagonal(segment_geoms) < max_diameter\n ):\n is_stopped = True\n else:\n is_stopped = False\n\n # detection of the end of a stop segment and append to\n # stop segment list\n if len(segment_geoms) > 1:\n segment_end = segment_times[-2]\n segment_begin = segment_times[0]\n if not is_stopped and previously_stopped:\n if (\n segment_end - segment_begin >= duration_threshold\n ): # detected end of a stop\n candidate = self.between(segment_begin, segment_end)\n if candidate is not None:\n yield candidate\n segment_geoms = []\n segment_times = []\n\n previously_stopped = is_stopped\n\n if (\n is_stopped\n and segment_times[-1] - segment_times[0] >= duration_threshold\n ):\n candidate = self.between(segment_times[0], segment_times[-1])\n if candidate is not None:\n yield candidate\n"
] |
[
[
"pandas.DataFrame.from_records",
"pandas.concat"
],
[
"pandas.to_datetime",
"numpy.pad",
"pandas.Timedelta",
"numpy.ones",
"numpy.where",
"numpy.radians",
"numpy.stack",
"numpy.timedelta64",
"pandas.Series",
"numpy.nanmax"
],
[
"pandas.Timestamp",
"numpy.tan",
"pandas.Timedelta",
"numpy.radians"
]
] |
Gantulga9480/py2048
|
[
"4a1f9efab9fab4ab6c77232e2d74eaa326446e57"
] |
[
"py2048/game_core.py"
] |
[
"import numpy as np\nimport random\nimport copy\n\nUP = 0\nDOWN = 1\nLEFT = 2\nRIGHT = 3\nUNDO = 4 # Experimantal\nACTION_SPACE = 5 # 5 for +UNDO\nINPLACE = 5 # For animation\n\n\nclass Node:\n\n def __init__(self, value) -> None:\n self.value = value\n\n def __eq__(self, __o: object) -> bool:\n if isinstance(__o, Node):\n return __o.value == self.value\n elif isinstance(__o, int):\n return __o == self.value\n\n def __ne__(self, __o: object) -> bool:\n if isinstance(__o, Node):\n return __o.value != self.value\n elif isinstance(__o, int):\n return __o != self.value\n\n def __repr__(self) -> str:\n return str(self.value)\n\n\nclass Board:\n\n ODDS = 10 # odds to generate 4 instead of 2\n START_BOX = 2 # Boxes to generate at start\n BOARD_SHAPE = (4, 4)\n\n def __init__(self, board=None) -> None:\n \"\"\"\n If board is present, game board from pre-defined values.\n Otherwise will generate new board.\n Input shape must be (4, 4).\n \"\"\"\n self.reset(board)\n\n def __repr__(self) -> str:\n return (f'{self.board[0][0]} {self.board[0][1]} {self.board[0][2]} '\n f'{self.board[0][3]}\\n'\n f'{self.board[1][0]} {self.board[1][1]} {self.board[1][2]} '\n f'{self.board[1][3]}\\n'\n f'{self.board[2][0]} {self.board[2][1]} {self.board[2][2]} '\n f'{self.board[2][3]}\\n'\n f'{self.board[3][0]} {self.board[3][1]} {self.board[3][2]} '\n f'{self.board[3][3]}\\n')\n\n def __eq__(self, __o: object) -> bool:\n for i in range(4):\n for j in range(4):\n try:\n if self.board[i][j].value != __o[i][j].value:\n return False\n except TypeError:\n return False\n return True\n\n def __ne__(self, __o: object) -> bool:\n for i in range(4):\n for j in range(4):\n if self.board[i][j].value != __o[i][j].value:\n return True\n return False\n\n def __getitem__(self, indices):\n \"\"\"\n Access game board Node values by indexing Board class instanse.\n \"\"\"\n return self.board[indices[0]][indices[1]].value\n\n def __setitem__(self, indices, new_value):\n if isinstance(new_value, Node):\n self.board[indices[0]][indices[1]] = new_value\n else:\n self.board[indices[0]][indices[1]].value = new_value\n\n def reset(self, board=None):\n self.board = [[Node(0), Node(0), Node(0), Node(0)],\n [Node(0), Node(0), Node(0), Node(0)],\n [Node(0), Node(0), Node(0), Node(0)],\n [Node(0), Node(0), Node(0), Node(0)]]\n self.last_board = None\n self.score = 0\n self.last_score = 0\n self.possible_actions = []\n self.changes = []\n self.empty_boxes = []\n if board is not None:\n self.set(board)\n else:\n for _ in range(self.START_BOX):\n self.empty_boxes = self.get_empty()\n self.generate()\n\n def set(self, b) -> None:\n self.board = [[Node(b[0, 0]), Node(b[0, 1]),\n Node(b[0, 2]), Node(b[0, 3])],\n [Node(b[1, 0]), Node(b[1, 1]),\n Node(b[1, 2]), Node(b[1, 3])],\n [Node(b[2, 0]), Node(b[2, 1]),\n Node(b[2, 2]), Node(b[2, 3])],\n [Node(b[3, 0]), Node(b[3, 1]),\n Node(b[3, 2]), Node(b[3, 3])]]\n\n def set_all(self, board):\n self.set(board.get())\n self.score = board.score\n self.last_score = board.last_score\n self.possible_actions = board.possible_actions.copy()\n self.changes = board.changes.copy()\n self.empty_boxes = board.empty_boxes.copy()\n self.last_board = copy.deepcopy(board.last_board)\n\n def get(self) -> np.ndarray:\n board = np.zeros(self.BOARD_SHAPE, dtype=np.int32)\n for i in range(self.BOARD_SHAPE[0]):\n for j in range(self.BOARD_SHAPE[1]):\n board[i, j] = self.board[i][j].value\n return board.copy()\n\n def generate(self):\n if self.empty_boxes.__len__() > 0:\n pos = random.choice(self.empty_boxes)\n odd = random.randint(1, (100 // self.ODDS))\n if odd == (100 // self.ODDS):\n self.board[pos[0]][pos[1]].value = 4\n else:\n self.board[pos[0]][pos[1]].value = 2\n\n def get_empty(self):\n empty_box = []\n for i in range(4):\n for j in range(4):\n if self.board[i][j].value == 0:\n empty_box.append([i, j])\n if empty_box.__len__() > 0:\n return empty_box.copy()\n return None\n\n def is_full(self):\n self.empty_boxes = self.get_empty()\n if self.empty_boxes.__len__() > 0:\n return False\n else:\n return True\n\n def available(self):\n if self.board[3][3].value == 0:\n return True\n for i in range(3):\n for j in range(4):\n if self.board[i][j].value == self.board[i+1][j].value or \\\n self.board[i][j].value == 0:\n return True\n for i in range(4):\n for j in range(3):\n if self.board[i][j].value == self.board[i][j+1].value or \\\n self.board[i][j].value == 0:\n return True\n return False\n\n\nclass Engine:\n\n def __init__(self) -> None:\n self.board = None\n self.changed = False\n\n def move(self, board: Board, dir) -> bool:\n self.board = board\n if dir != UNDO:\n # required for not exceeding maximum recursion depth\n self.board.last_board = None\n self.board.last_board = copy.deepcopy(board)\n self.board.changes.clear()\n self.board.last_score = self.board.score\n if dir == UP:\n self.board.score += self.up()\n elif dir == DOWN:\n self.board.score += self.down()\n elif dir == LEFT:\n self.board.score += self.left()\n elif dir == RIGHT:\n self.board.score += self.right()\n elif dir == UNDO:\n return self.undo()\n if self.changed:\n if not self.board.is_full():\n self.board.generate()\n self.get_possible_actions()\n return True\n self.board.score = 0\n return False\n\n def undo(self):\n if self.board.last_board is not None:\n self.board.set_all(self.board.last_board)\n self.board.last_board = None # Delete last board after UNDO\n self.get_possible_actions()\n return True\n return False\n\n def up(self):\n __score = 0\n self.changed = False\n self.board.changes.clear()\n for i in range(4):\n row_modif = False\n for j in range(1, 4, 1):\n if self.board[j, i] != 0:\n modif = False\n start_index = [j, i]\n stop_index = [j, i]\n while True:\n if j >= 1:\n if j == 1 and row_modif and not modif:\n break\n elif j == 2 and row_modif and not modif and \\\n self.board[j-1, i] == self.board[j, i]:\n break\n elif self.board[j-1, i] == \\\n self.board[j, i] and not modif:\n self.board[j-1, i] = \\\n self.board[j, i]*2\n __score += self.board[j, i]*2\n self.board[j, i] = 0\n modif = True\n row_modif = True\n stop_index = [j-1, i]\n elif self.board[j-1, i] == 0:\n self.board[j-1, i] = \\\n self.board[j, i]\n self.board[j, i] = 0\n stop_index = [j-1, i]\n j -= 1\n else:\n break\n if start_index[0] != stop_index[0] or \\\n start_index[1] != stop_index[1]:\n self.changed = True\n self.board.changes.append([start_index,\n stop_index, UP])\n else:\n self.board.changes.append([start_index,\n stop_index, INPLACE])\n return __score\n\n def down(self):\n __score = 0\n self.changed = False\n self.board.changes.clear()\n for i in range(4):\n row_modif = False\n for j in range(3, -1, -1):\n if self.board[j, i] != 0:\n modif = False\n start_index = [j, i]\n stop_index = [j, i]\n while True:\n try:\n if j == 2 and row_modif and not modif:\n break\n elif j == 1 and row_modif and not modif and \\\n self.board[j+1, i] == self.board[j, i]:\n break\n elif self.board[j+1, i] == \\\n self.board[j, i] and not modif:\n self.board[j+1, i] = \\\n self.board[j, i]*2\n __score += self.board[j, i]*2\n self.board[j, i] = 0\n modif = True\n row_modif = True\n stop_index = [j+1, i]\n elif self.board[j+1, i] == 0:\n self.board[j+1, i] = \\\n self.board[j, i]\n self.board[j, i] = 0\n stop_index = [j+1, i]\n j += 1\n except IndexError:\n break\n if start_index[0] != stop_index[0] or \\\n start_index[1] != stop_index[1]:\n self.changed = True\n self.board.changes.append([start_index,\n stop_index, DOWN])\n else:\n self.board.changes.append([start_index,\n stop_index, INPLACE])\n return __score\n\n def left(self):\n __score = 0\n self.changed = False\n self.board.changes.clear()\n for j in range(4):\n row_modif = False\n for i in range(1, 4, 1):\n if self.board[j, i] != 0:\n modif = False\n start_index = [j, i]\n stop_index = [j, i]\n while True:\n if i >= 1:\n if i == 1 and row_modif and not modif:\n break\n elif i == 2 and row_modif and not modif and \\\n self.board[j, i-1] == self.board[j, i]:\n break\n elif self.board[j, i-1] == \\\n self.board[j, i] and not modif:\n self.board[j, i-1] = \\\n self.board[j, i]*2\n __score += self.board[j, i]*2\n self.board[j, i] = 0\n modif = True\n row_modif = True\n stop_index = [j, i-1]\n elif self.board[j, i-1] == 0:\n self.board[j, i-1] = \\\n self.board[j, i]\n self.board[j, i] = 0\n stop_index = [j, i-1]\n i -= 1\n else:\n break\n if start_index[0] != stop_index[0] or \\\n start_index[1] != stop_index[1]:\n self.changed = True\n self.board.changes.append([start_index,\n stop_index, LEFT])\n else:\n self.board.changes.append([start_index,\n stop_index, INPLACE])\n return __score\n\n def right(self):\n __score = 0\n self.changed = False\n self.board.changes.clear()\n for j in range(4):\n row_modif = False\n for i in range(3, -1, -1):\n if self.board[j, i] != 0:\n modif = False\n start_index = [j, i]\n stop_index = [j, i]\n while True:\n try:\n if i == 2 and row_modif and not modif:\n break\n elif i == 1 and row_modif and not modif and \\\n self.board[j, i+1] == self.board[j, i]:\n break\n elif self.board[j, i+1] == \\\n self.board[j, i] and not modif:\n self.board[j, i+1] = \\\n self.board[j, i] * 2\n __score += self.board[j, i]*2\n self.board[j, i] = 0\n modif = True\n row_modif = True\n stop_index = [j, i+1]\n elif self.board[j, i+1] == 0:\n self.board[j, i+1] = \\\n self.board[j, i]\n self.board[j, i] = 0\n stop_index = [j, i+1]\n i += 1\n except IndexError:\n break\n if start_index[0] != stop_index[0] or \\\n start_index[1] != stop_index[1]:\n self.changed = True\n self.board.changes.append([start_index,\n stop_index, RIGHT])\n else:\n self.board.changes.append([start_index,\n stop_index, INPLACE])\n return __score\n\n def get_possible_actions(self, board=None):\n moves = []\n if board is not None:\n self.board = board\n changes_tmp = self.board.changes.copy() # preserve changes\n start = self.board.get() # Get copy of main board values\n changed_state_tmp = self.changed # preserve changed state\n for action in range(ACTION_SPACE):\n if action == UP:\n self.up()\n elif action == DOWN:\n self.down()\n elif action == LEFT:\n self.left()\n elif action == RIGHT:\n self.right()\n elif action == UNDO:\n self.changed = False\n if self.board.last_board is not None:\n self.changed = True\n if self.changed:\n moves.append(action)\n self.board.set(start) # Revert back to main board values\n self.board.changes = changes_tmp.copy() # set back to main changes\n self.changed = changed_state_tmp\n if len(moves) > 0:\n self.board.possible_actions = moves.copy()\n return moves\n self.board.possible_actions = []\n return []\n"
] |
[
[
"numpy.zeros"
]
] |
gilbertmike/tugofwar-horserace
|
[
"504f9129dee1fec88daf3bcbf3714fec3db215cf"
] |
[
"tugofwar_horserace/horserace.py"
] |
[
"import numpy as np\n\nclass HorseRace:\n def __init__(self, quality_1: float, quality_2: float, thres: int):\n \"\"\"Creates a new simulation instance with two options with qualities\n `quality_1` and `quality_2`. Decision is made when threshold `thres`\n is reached.\n\n Every simulation time step, the sigmoid\n P = 1/(1 + exp(-quality_i))\n is used as probability that a stream S_i receives a reward.\n \"\"\"\n self.quality_1 = quality_1\n self.reward_probs_1 = 1 / (1 + np.exp(-quality_1))\n self.quality_2 = quality_2\n self.reward_probs_2 = 1 / (1 + np.exp(-quality_2))\n self.thres = thres\n\n def simulate(self, num_sim: int) -> list:\n \"\"\"Runs `num_sim` simulations and returns history and time of decision.\n\n Args:\n `num_sim`: number of simulations to be run.\n\n Returns:\n a list size `num_size` which contains tuples (timestep, decision) \n where timestep is the time when decision is made and decision is\n the index of chosen option (1 or 2).\n \"\"\"\n # Accumulator of rewards of option 1 and 2\n S_1 = np.zeros((num_sim,))\n S_2 = np.zeros((num_sim,))\n decision_time = np.zeros(num_sim)\n decision = np.zeros(num_sim)\n time = 1\n while True:\n # Generate rewards for all num_sim simulations for S_1 and S_2\n reward = np.random.rand(num_sim) < self.reward_probs_1\n reward = reward * (decision == 0) # mask for undecided simulations\n S_1 += reward\n reward = np.random.rand(num_sim) < self.reward_probs_2\n reward = reward * (decision == 0) # mask for undecided simulations\n S_2 += reward\n # Update decision_time and decision for simulations that just decided 2\n thres_2 = S_2 > self.thres\n decision_time = np.where(\n np.logical_and(thres_2, decision_time == 0),\n time,\n decision_time\n )\n decision = np.where(\n np.logical_and(thres_2, decision == 0),\n 2,\n decision\n )\n # Update decision_time and decision for simulations that just decided 1\n thres_1 = S_1 > self.thres\n decision_time = np.where(\n np.logical_and(thres_1, decision_time == 0),\n time,\n decision_time\n )\n decision = np.where(\n np.logical_and(thres_1, decision == 0),\n 1,\n decision\n )\n time += 1\n if np.all(decision > 0):\n break\n return list(zip(decision_time, decision))\n"
] |
[
[
"numpy.random.rand",
"numpy.zeros",
"numpy.exp",
"numpy.logical_and",
"numpy.all"
]
] |
2360673637/AIGames
|
[
"7d149cc2cff8fa626ee1c9e1ad7c39e1a724a5bb"
] |
[
"AIPong/Algorithm_1/main.py"
] |
[
"'''\n主函数\n作者: Charles\n公众号: Charles的皮卡丘\n'''\nimport config\nimport tensorflow as tf\nfrom nets.qNet import DQN\n\n\ndef main():\n\tsession = tf.InteractiveSession()\n\tDQN(config.options).train(session)\n\n\nif __name__ == '__main__':\n\tmain()"
] |
[
[
"tensorflow.InteractiveSession"
]
] |
manivaradarajan/tensorflow
|
[
"8ec19e0f48b0bfb74f67bd37c4c1ae2bce1d10f3"
] |
[
"tensorflow/python/keras/metrics.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# pylint: disable=unused-import\n\"\"\"Built-in metrics.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport sys\nimport types\nimport numpy as np\nimport six\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras.engine.base_layer import Layer\nfrom tensorflow.python.keras.losses import binary_crossentropy\nfrom tensorflow.python.keras.losses import categorical_crossentropy\nfrom tensorflow.python.keras.losses import categorical_hinge\nfrom tensorflow.python.keras.losses import cosine_proximity\nfrom tensorflow.python.keras.losses import hinge\nfrom tensorflow.python.keras.losses import kullback_leibler_divergence\nfrom tensorflow.python.keras.losses import logcosh\nfrom tensorflow.python.keras.losses import mean_absolute_error\nfrom tensorflow.python.keras.losses import mean_absolute_percentage_error\nfrom tensorflow.python.keras.losses import mean_squared_error\nfrom tensorflow.python.keras.losses import mean_squared_logarithmic_error\nfrom tensorflow.python.keras.losses import poisson\nfrom tensorflow.python.keras.losses import sparse_categorical_crossentropy\nfrom tensorflow.python.keras.losses import squared_hinge\nfrom tensorflow.python.keras.utils import metrics_utils\nfrom tensorflow.python.keras.utils.generic_utils import deserialize_keras_object\nfrom tensorflow.python.keras.utils.generic_utils import serialize_keras_object\nfrom tensorflow.python.keras.utils.generic_utils import to_list\nfrom tensorflow.python.keras.utils.losses_utils import squeeze_or_expand_dimensions\nfrom tensorflow.python.keras.utils.tf_utils import is_tensor_or_variable\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import confusion_matrix\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.ops import variables as tf_variables\nfrom tensorflow.python.ops import weights_broadcast_ops\nfrom tensorflow.python.util.tf_export import keras_export\nfrom tensorflow.tools.docs import doc_controls\n\n\n@keras_export('keras.metrics.Metric')\n@six.add_metaclass(abc.ABCMeta)\nclass Metric(Layer):\n \"\"\"Encapsulates metric logic and state.\n\n Usage:\n\n ```python\n m = SomeMetric(...)\n for input in ...:\n m.update_state(input)\n print('Final result: ', m.result().numpy())\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = tf.keras.Sequential()\n model.add(tf.keras.layers.Dense(64, activation='relu'))\n model.add(tf.keras.layers.Dense(64, activation='relu'))\n model.add(tf.keras.layers.Dense(10, activation='softmax'))\n\n model.compile(optimizer=tf.train.RMSPropOptimizer(0.01),\n loss=tf.keras.losses.categorical_crossentropy,\n metrics=[tf.keras.metrics.CategoricalAccuracy()])\n\n data = np.random.random((1000, 32))\n labels = np.random.random((1000, 10))\n\n dataset = tf.data.Dataset.from_tensor_slices((data, labels))\n dataset = dataset.batch(32)\n dataset = dataset.repeat()\n\n model.fit(dataset, epochs=10, steps_per_epoch=30)\n ```\n\n To be implemented by subclasses:\n * `__init__()`: All state variables should be created in this method by\n calling `self.add_weight()` like: `self.var = self.add_weight(...)`\n * `update_state()`: Has all updates to the state variables like:\n self.var.assign_add(...).\n * `result()`: Computes and returns a value for the metric\n from the state variables.\n\n Example subclass implementation:\n\n ```\n class BinaryTruePositives(Metric):\n def __init__(self, name='binary_true_positives', dtype=None):\n super(BinaryTruePositives, self).__init__(name=name, dtype=dtype)\n self.true_positives = self.add_weight(\n 'true_positives', initializer=init_ops.zeros_initializer)\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n y_true = math_ops.cast(y_true, dtypes.bool)\n y_pred = math_ops.cast(y_pred, dtypes.bool)\n y_pred, y_true, sample_weight = squeeze_or_expand_dimensions(\n y_pred, y_true, sample_weight)\n\n values = math_ops.logical_and(\n math_ops.equal(y_true, True), math_ops.equal(y_pred, True))\n values = math_ops.cast(values, self._dtype)\n if sample_weight is not None:\n sample_weight = math_ops.cast(sample_weight, self._dtype)\n values = math_ops.multiply(values, sample_weight)\n self.true_positives.assign_add(math_ops.reduce_sum(values))\n\n def result(self):\n return array_ops.identity(self.true_positives)\n ```\n \"\"\"\n\n def __init__(self, name=None, dtype=None, **kwargs):\n super(Metric, self).__init__(name=name, dtype=dtype, **kwargs)\n self.stateful = True # All metric layers are stateful.\n self.built = True\n self._dtype = K.floatx() if dtype is None else dtypes.as_dtype(dtype).name\n\n def __new__(cls, *args, **kwargs):\n obj = super(Metric, cls).__new__(cls)\n\n if sys.version_info < (3,):\n # Wrap methods in `weakmethod` function to remove binding and create a\n # weak reference. This is to remove reference cycle that is created here.\n # This is not an issue in python versions > 3.\n if context.executing_eagerly():\n obj.update_state = metrics_utils.weakmethod(obj.update_state)\n obj.update_state = metrics_utils.weakmethod(\n types.MethodType(\n metrics_utils.update_state_wrapper(obj.update_state), obj))\n result = metrics_utils.weakmethod(obj.result)\n obj.result = metrics_utils.weakmethod(\n types.MethodType(metrics_utils.result_wrapper(result), obj))\n else:\n obj.update_state = types.MethodType(\n metrics_utils.update_state_wrapper(obj.update_state), obj)\n obj.result = types.MethodType(\n metrics_utils.result_wrapper(obj.result), obj)\n\n return obj\n\n def __call__(self, *args, **kwargs):\n \"\"\"Accumulates statistics and then computes metric result value.\n\n Args:\n *args:\n **kwargs: A mini-batch of inputs to the Metric,\n passed on to `update_state()`.\n\n Returns:\n The metric value tensor.\n \"\"\"\n update_op = self.update_state(*args, **kwargs)\n with ops.control_dependencies([update_op]):\n result_t = self.result()\n\n # We are adding the metric object as metadata on the result tensor.\n # This is required when we want to use a metric with `add_metric` API on\n # a Model/Layer in graph mode. This metric instance will later be used\n # to reset variable state after each epoch of training.\n # Example:\n # model = Model()\n # model.add_metric(Mean()(values), name='mean')\n if not context.executing_eagerly():\n result_t._metric_obj = self # pylint: disable=protected-access\n return result_t\n\n @property\n def dtype(self):\n return self._dtype\n\n def get_config(self):\n \"\"\"Returns the serializable config of the metric.\"\"\"\n return {'name': self.name, 'dtype': self.dtype}\n\n def reset_states(self):\n \"\"\"Resets all of the metric state variables.\n\n This function is called between epochs/steps,\n when a metric is evaluated during training.\n \"\"\"\n for v in self.variables:\n K.set_value(v, 0)\n\n @abc.abstractmethod\n def update_state(self, *args, **kwargs):\n \"\"\"Accumulates statistics for the metric.\n\n Note: This function is executed as a graph function in graph mode.\n This means:\n a) Operations on the same resource are executed in textual order.\n This should make it easier to do things like add the updated\n value of a variable to another, for example.\n b) You don't need to worry about collecting the update ops to execute.\n All update ops added to the graph by this function will be executed.\n As a result, code should generally work the same way with graph or\n eager execution.\n\n Args:\n *args:\n **kwargs: A mini-batch of inputs to the Metric.\n \"\"\"\n NotImplementedError('Must be implemented in subclasses.')\n\n @abc.abstractmethod\n def result(self):\n \"\"\"Computes and returns the metric value tensor.\n\n Result computation is an idempotent operation that simply calculates the\n metric value using the state variables.\n \"\"\"\n NotImplementedError('Must be implemented in subclasses.')\n\n ### For use by subclasses ###\n @doc_controls.for_subclass_implementers\n def add_weight(self,\n name,\n shape=(),\n aggregation=tf_variables.VariableAggregation.SUM,\n synchronization=tf_variables.VariableSynchronization.ON_READ,\n initializer=None,\n dtype=None):\n \"\"\"Adds state variable. Only for use by subclasses.\"\"\"\n return super(Metric, self).add_weight(\n name=name,\n shape=shape,\n dtype=self._dtype if dtype is None else dtype,\n trainable=False,\n initializer=initializer,\n collections=[],\n synchronization=synchronization,\n aggregation=aggregation)\n\n ### End: For use by subclasses ###\n\n\nclass Reduce(Metric):\n \"\"\"Encapsulates metrics that perform a reduce operation on the values.\"\"\"\n\n def __init__(self, reduction, name, dtype=None):\n \"\"\"Creates a `Reduce` instance.\n\n Args:\n reduction: a `tf.keras.metrics.Reduction` enum value.\n name: string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(Reduce, self).__init__(name=name, dtype=dtype)\n self.reduction = reduction\n self.total = self.add_weight(\n 'total', initializer=init_ops.zeros_initializer)\n if reduction in [metrics_utils.Reduction.SUM_OVER_BATCH_SIZE,\n metrics_utils.Reduction.WEIGHTED_MEAN]:\n self.count = self.add_weight(\n 'count', initializer=init_ops.zeros_initializer)\n\n def update_state(self, values, sample_weight=None):\n \"\"\"Accumulates statistics for computing the reduction metric.\n\n For example, if `values` is [1, 3, 5, 7] and reduction=SUM_OVER_BATCH_SIZE,\n then the value of `result()` is 4. If the `sample_weight` is specified as\n [1, 1, 0, 0] then value of `result()` would be 2.\n\n Args:\n values: Per-example value.\n sample_weight: Optional weighting of each example. Defaults to 1.\n\n Returns:\n Update op.\n \"\"\"\n values = math_ops.cast(values, self._dtype)\n if sample_weight is not None:\n sample_weight = math_ops.cast(sample_weight, self._dtype)\n # Update dimensions of weights to match with values if possible.\n values, _, sample_weight = squeeze_or_expand_dimensions(\n values, None, sample_weight)\n try:\n # Broadcast weights if possible.\n sample_weight = weights_broadcast_ops.broadcast_weights(\n sample_weight, values)\n except ValueError:\n # Reduce values to same ndim as weight array\n ndim = K.ndim(values)\n weight_ndim = K.ndim(sample_weight)\n if self.reduction == metrics_utils.Reduction.SUM:\n values = math_ops.reduce_sum(\n values, axis=list(range(weight_ndim, ndim)))\n else:\n values = math_ops.reduce_mean(\n values, axis=list(range(weight_ndim, ndim)))\n values = math_ops.multiply(values, sample_weight)\n\n value_sum = math_ops.reduce_sum(values)\n with ops.control_dependencies([value_sum]):\n update_total_op = self.total.assign_add(value_sum)\n\n # Exit early if the reduction doesn't have a denominator.\n if self.reduction == metrics_utils.Reduction.SUM:\n return update_total_op\n\n # Update `count` for reductions that require a denominator.\n if self.reduction == metrics_utils.Reduction.SUM_OVER_BATCH_SIZE:\n num_values = math_ops.cast(array_ops.size(values), self._dtype)\n elif self.reduction == metrics_utils.Reduction.WEIGHTED_MEAN:\n if sample_weight is None:\n num_values = math_ops.cast(array_ops.size(values), self._dtype)\n else:\n num_values = math_ops.reduce_sum(sample_weight)\n else:\n raise NotImplementedError(\n 'reduction [%s] not implemented' % self.reduction)\n\n with ops.control_dependencies([update_total_op]):\n return self.count.assign_add(num_values)\n\n def result(self):\n if self.reduction == metrics_utils.Reduction.SUM:\n return array_ops.identity(self.total)\n elif self.reduction in [\n metrics_utils.Reduction.WEIGHTED_MEAN,\n metrics_utils.Reduction.SUM_OVER_BATCH_SIZE\n ]:\n return math_ops.div_no_nan(self.total, self.count)\n else:\n raise NotImplementedError(\n 'reduction [%s] not implemented' % self.reduction)\n\n\n@keras_export('keras.metrics.Sum')\nclass Sum(Reduce):\n \"\"\"Computes the (weighted) sum of the given values.\n\n For example, if values is [1, 3, 5, 7] then the sum is 16.\n If the weights were specified as [1, 1, 0, 0] then the sum would be 4.\n\n This metric creates one variable, `total`, that is used to compute the sum of\n `values`. This is ultimately returned as `sum`.\n\n If `sample_weight` is `None`, weights default to 1. Use `sample_weight` of 0\n to mask values.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.Sum()\n m.update_state([1, 3, 5, 7])\n print('Final result: ', m.result().numpy()) # Final result: 16.0\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.add_metric(tf.keras.metrics.Sum(name='sum_1')(outputs))\n model.compile('sgd', loss='mse')\n ```\n \"\"\"\n\n def __init__(self, name='sum', dtype=None):\n \"\"\"Creates a `Sum` instance.\n\n Args:\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(Sum, self).__init__(reduction=metrics_utils.Reduction.SUM,\n name=name, dtype=dtype)\n\n\n@keras_export('keras.metrics.Mean')\nclass Mean(Reduce):\n \"\"\"Computes the (weighted) mean of the given values.\n\n For example, if values is [1, 3, 5, 7] then the mean is 4.\n If the weights were specified as [1, 1, 0, 0] then the mean would be 2.\n\n This metric creates two variables, `total` and `count` that are used to\n compute the average of `values`. This average is ultimately returned as `mean`\n which is an idempotent operation that simply divides `total` by `count`.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.Mean()\n m.update_state([1, 3, 5, 7])\n print('Final result: ', m.result().numpy()) # Final result: 4.0\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.add_metric(tf.keras.metrics.Mean(name='mean_1')(outputs))\n model.compile('sgd', loss='mse')\n ```\n \"\"\"\n\n def __init__(self, name='mean', dtype=None):\n \"\"\"Creates a `Mean` instance.\n\n Args:\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(Mean, self).__init__(\n reduction=metrics_utils.Reduction.WEIGHTED_MEAN, name=name, dtype=dtype)\n\n\n@keras_export('keras.metrics.MeanRelativeError')\nclass MeanRelativeError(Mean):\n \"\"\"Computes the mean relative error by normalizing with the given values.\n\n This metric creates two local variables, `total` and `count` that are used to\n compute the mean relative absolute error. This average is weighted by\n `sample_weight`, and it is ultimately returned as `mean_relative_error`:\n an idempotent operation that simply divides `total` by `count`.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.MeanRelativeError(normalizer=[1, 3, 2, 3])\n m.update_state([1, 3, 2, 3], [2, 4, 6, 8])\n\n # metric = mean(|y_pred - y_true| / normalizer)\n # = mean([1, 1, 4, 5] / [1, 3, 2, 3]) = mean([1, 1/3, 2, 5/3])\n # = 5/4 = 1.25\n print('Final result: ', m.result().numpy()) # Final result: 1.25\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile(\n 'sgd',\n loss='mse',\n metrics=[tf.keras.metrics.MeanRelativeError(normalizer=[1, 3])])\n ```\n \"\"\"\n\n def __init__(self, normalizer, name=None, dtype=None):\n \"\"\"Creates a `MeanRelativeError` instance.\n\n Args:\n normalizer: The normalizer values with same shape as predictions.\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(MeanRelativeError, self).__init__(name=name, dtype=dtype)\n normalizer = math_ops.cast(normalizer, self._dtype)\n self.normalizer = normalizer\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n \"\"\"Accumulates metric statistics.\n\n Args:\n y_true: The ground truth values.\n y_pred: The predicted values.\n sample_weight: Optional weighting of each example. Defaults to 1. Can be a\n `Tensor` whose rank is either 0, or the same rank as `y_true`, and must\n be broadcastable to `y_true`.\n\n Returns:\n Update op.\n \"\"\"\n y_true = math_ops.cast(y_true, self._dtype)\n y_pred = math_ops.cast(y_pred, self._dtype)\n y_pred, y_true, sample_weight = squeeze_or_expand_dimensions(\n y_pred, y_true, sample_weight)\n\n y_pred, self.normalizer = confusion_matrix.remove_squeezable_dimensions(\n y_pred, self.normalizer)\n y_pred.shape.assert_is_compatible_with(y_pred.shape)\n relative_errors = math_ops.div_no_nan(\n math_ops.abs(y_true - y_pred), self.normalizer)\n\n return super(MeanRelativeError, self).update_state(\n relative_errors, sample_weight=sample_weight)\n\n def get_config(self):\n n = self.normalizer\n config = {'normalizer': K.eval(n) if is_tensor_or_variable(n) else n}\n base_config = super(MeanRelativeError, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass MeanMetricWrapper(Mean):\n \"\"\"Wraps a stateless metric function with the Mean metric.\"\"\"\n\n def __init__(self, fn, name=None, dtype=None, **kwargs):\n \"\"\"Creates a `MeanMetricWrapper` instance.\n\n Args:\n fn: The metric function to wrap, with signature\n `fn(y_true, y_pred, **kwargs)`.\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n **kwargs: The keyword arguments that are passed on to `fn`.\n \"\"\"\n super(MeanMetricWrapper, self).__init__(name=name, dtype=dtype)\n self._fn = fn\n self._fn_kwargs = kwargs\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n \"\"\"Accumulates metric statistics.\n\n `y_true` and `y_pred` should have the same shape.\n\n Args:\n y_true: The ground truth values.\n y_pred: The predicted values.\n sample_weight: Optional weighting of each example. Defaults to 1. Can be\n a `Tensor` whose rank is either 0, or the same rank as `y_true`,\n and must be broadcastable to `y_true`.\n\n Returns:\n Update op.\n \"\"\"\n y_true = math_ops.cast(y_true, self._dtype)\n y_pred = math_ops.cast(y_pred, self._dtype)\n y_pred, y_true, sample_weight = squeeze_or_expand_dimensions(\n y_pred, y_true, sample_weight)\n\n matches = self._fn(y_true, y_pred, **self._fn_kwargs)\n return super(MeanMetricWrapper, self).update_state(\n matches, sample_weight=sample_weight)\n\n def get_config(self):\n config = {}\n for k, v in six.iteritems(self._fn_kwargs):\n config[k] = K.eval(v) if is_tensor_or_variable(v) else v\n base_config = super(MeanMetricWrapper, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.metrics.Accuracy')\nclass Accuracy(MeanMetricWrapper):\n \"\"\"Calculates how often predictions matches labels.\n\n For example, if `y_true` is [1, 2, 3, 4] and `y_pred` is [0, 2, 3, 4]\n then the accuracy is 3/4 or .75. If the weights were specified as\n [1, 1, 0, 0] then the accuracy would be 1/2 or .5.\n\n This metric creates two local variables, `total` and `count` that are used to\n compute the frequency with which `y_pred` matches `y_true`. This frequency is\n ultimately returned as `binary accuracy`: an idempotent operation that simply\n divides `total` by `count`.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.Accuracy()\n m.update_state([1, 2, 3, 4], [0, 2, 3, 4])\n print('Final result: ', m.result().numpy()) # Final result: 0.75\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', loss='mse', metrics=[tf.keras.metrics.Accuracy()])\n ```\n \"\"\"\n\n def __init__(self, name='accuracy', dtype=None):\n super(Accuracy, self).__init__(accuracy, name, dtype=dtype)\n\n\n@keras_export('keras.metrics.BinaryAccuracy')\nclass BinaryAccuracy(MeanMetricWrapper):\n \"\"\"Calculates how often predictions matches labels.\n\n For example, if `y_true` is [1, 1, 0, 0] and `y_pred` is [0.98, 1, 0, 0.6]\n then the binary accuracy is 3/4 or .75. If the weights were specified as\n [1, 0, 0, 1] then the binary accuracy would be 1/2 or .5.\n\n This metric creates two local variables, `total` and `count` that are used to\n compute the frequency with which `y_pred` matches `y_true`. This frequency is\n ultimately returned as `binary accuracy`: an idempotent operation that simply\n divides `total` by `count`.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.BinaryAccuracy()\n m.update_state([1, 1, 0, 0], [0.98, 1, 0, 0.6])\n print('Final result: ', m.result().numpy()) # Final result: 0.75\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', loss='mse', metrics=[tf.keras.metrics.BinaryAccuracy()])\n ```\n \"\"\"\n\n def __init__(self, name='binary_accuracy', dtype=None, threshold=0.5):\n \"\"\"Creates a `BinaryAccuracy` instance.\n\n Args:\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n threshold: (Optional) Float representing the threshold for deciding\n whether prediction values are 1 or 0.\n \"\"\"\n super(BinaryAccuracy, self).__init__(\n binary_accuracy, name, dtype=dtype, threshold=threshold)\n\n\n@keras_export('keras.metrics.CategoricalAccuracy')\nclass CategoricalAccuracy(MeanMetricWrapper):\n \"\"\"Calculates how often predictions matches labels.\n\n For example, if `y_true` is [[0, 0, 1], [0, 1, 0]] and `y_pred` is\n [[0.1, 0.9, 0.8], [0.05, 0.95, 0]] then the categorical accuracy is 1/2 or .5.\n If the weights were specified as [0.7, 0.3] then the categorical accuracy\n would be .3.\n\n This metric creates two local variables, `total` and `count` that are used to\n compute the frequency with which `y_pred` matches `y_true`. This frequency is\n ultimately returned as `categorical accuracy`: an idempotent operation that\n simply divides `total` by `count`.\n\n `y_pred` and `y_true` should be passed in as vectors of probabilities, rather\n than as labels. If necessary, use `tf.one_hot` to expand `y_true` as a vector.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.CategoricalAccuracy()\n m.update_state([[0, 0, 1], [0, 1, 0]], [[0.1, 0.9, 0.8], [0.05, 0.95, 0]])\n print('Final result: ', m.result().numpy()) # Final result: 0.5\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile(\n 'sgd',\n loss='mse',\n metrics=[tf.keras.metrics.CategoricalAccuracy()])\n ```\n \"\"\"\n\n def __init__(self, name='categorical_accuracy', dtype=None):\n \"\"\"Creates a `CategoricalAccuracy` instance.\n\n Args:\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(CategoricalAccuracy, self).__init__(\n categorical_accuracy, name, dtype=dtype)\n\n\n@keras_export('keras.metrics.SparseCategoricalAccuracy')\nclass SparseCategoricalAccuracy(MeanMetricWrapper):\n \"\"\"Calculates how often predictions matches integer labels.\n\n For example, if `y_true` is [[2], [1]] and `y_pred` is\n [[0.1, 0.9, 0.8], [0.05, 0.95, 0]] then the categorical accuracy is 1/2 or .5.\n If the weights were specified as [0.7, 0.3] then the categorical accuracy\n would be .3.\n\n This metric creates two local variables, `total` and `count` that are used to\n compute the frequency with which `y_pred` matches `y_true`. This frequency is\n ultimately returned as `sparse categorical accuracy`: an idempotent operation\n that simply divides `total` by `count`.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.SparseCategoricalAccuracy()\n m.update_state([[2], [1]], [[0.1, 0.9, 0.8], [0.05, 0.95, 0]])\n print('Final result: ', m.result().numpy()) # Final result: 0.5\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile(\n 'sgd',\n loss='mse',\n metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])\n ```\n \"\"\"\n\n def __init__(self, name='sparse_categorical_accuracy', dtype=None):\n super(SparseCategoricalAccuracy, self).__init__(\n sparse_categorical_accuracy, name, dtype=dtype)\n\n\n@keras_export('keras.metrics.TopKCategoricalAccuracy')\nclass TopKCategoricalAccuracy(MeanMetricWrapper):\n \"\"\"Computes how often targets are in the top `K` predictions.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.TopKCategoricalAccuracy()\n m.update_state([[0, 0, 1], [0, 1, 0]], [[0.1, 0.9, 0.8], [0.05, 0.95, 0]])\n print('Final result: ', m.result().numpy()) # Final result: 1.0\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', metrics=[tf.keras.metrics.TopKCategoricalAccuracy()])\n ```\n \"\"\"\n\n def __init__(self, k=5, name='top_k_categorical_accuracy', dtype=None):\n \"\"\"Creates a `TopKCategoricalAccuracy` instance.\n\n Args:\n k: (Optional) Number of top elements to look at for computing accuracy.\n Defaults to 5.\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(TopKCategoricalAccuracy, self).__init__(\n top_k_categorical_accuracy, name, dtype=dtype, k=k)\n\n\n@keras_export('keras.metrics.SparseTopKCategoricalAccuracy')\nclass SparseTopKCategoricalAccuracy(MeanMetricWrapper):\n \"\"\"Computes how often integer targets are in the top `K` predictions.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.SparseTopKCategoricalAccuracy()\n m.update_state([2, 1], [[0.1, 0.9, 0.8], [0.05, 0.95, 0]])\n print('Final result: ', m.result().numpy()) # Final result: 1.0\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile(\n 'sgd',\n metrics=[tf.keras.metrics.SparseTopKCategoricalAccuracy()])\n ```\n \"\"\"\n\n def __init__(self, k=5, name='sparse_top_k_categorical_accuracy', dtype=None):\n \"\"\"Creates a `SparseTopKCategoricalAccuracy` instance.\n\n Args:\n k: (Optional) Number of top elements to look at for computing accuracy.\n Defaults to 5.\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(SparseTopKCategoricalAccuracy, self).__init__(\n sparse_top_k_categorical_accuracy, name, dtype=dtype, k=k)\n\n\nclass _ConfusionMatrixConditionCount(Metric):\n \"\"\"Calculates the number of the given confusion matrix condition.\"\"\"\n\n def __init__(self,\n confusion_matrix_cond,\n thresholds=None,\n name=None,\n dtype=None):\n \"\"\"Creates a `_ConfusionMatrixConditionCount` instance.\n\n Args:\n confusion_matrix_cond: One of `metrics_utils.ConfusionMatrix` conditions.\n thresholds: (Optional) Defaults to 0.5. A float value or a python\n list/tuple of float threshold values in [0, 1]. A threshold is compared\n with prediction values to determine the truth value of predictions\n (i.e., above the threshold is `true`, below is `false`). One metric\n value is generated for each threshold value.\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(_ConfusionMatrixConditionCount, self).__init__(name=name, dtype=dtype)\n self._confusion_matrix_cond = confusion_matrix_cond\n self.init_thresholds = thresholds\n self.thresholds = metrics_utils.parse_init_thresholds(\n thresholds, default_threshold=0.5)\n self.accumulator = self.add_weight(\n 'accumulator',\n shape=(len(self.thresholds),),\n initializer=init_ops.zeros_initializer)\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n \"\"\"Accumulates the given confusion matrix condition statistics.\n\n Args:\n y_true: The ground truth values.\n y_pred: The predicted values.\n sample_weight: Optional weighting of each example. Defaults to 1. Can be a\n `Tensor` whose rank is either 0, or the same rank as `y_true`, and must\n be broadcastable to `y_true`.\n\n Returns:\n Update op.\n \"\"\"\n return metrics_utils.update_confusion_matrix_variables(\n {self._confusion_matrix_cond: self.accumulator},\n y_true,\n y_pred,\n thresholds=self.thresholds,\n sample_weight=sample_weight)\n\n def result(self):\n if len(self.thresholds) == 1:\n result = self.accumulator[0]\n else:\n result = self.accumulator\n return ops.convert_to_tensor(result)\n\n def reset_states(self):\n num_thresholds = len(to_list(self.thresholds))\n for v in self.variables:\n K.set_value(v, np.zeros((num_thresholds,)))\n\n def get_config(self):\n config = {'thresholds': self.init_thresholds}\n base_config = super(_ConfusionMatrixConditionCount, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.metrics.FalsePositives')\nclass FalsePositives(_ConfusionMatrixConditionCount):\n \"\"\"Calculates the number of false positives.\n\n For example, if `y_true` is [0, 1, 0, 0] and `y_pred` is [0, 0, 1, 1]\n then the false positives value is 2. If the weights were specified as\n [0, 0, 1, 0] then the false positives value would be 1.\n\n If `sample_weight` is given, calculates the sum of the weights of\n false positives. This metric creates one local variable, `accumulator`\n that is used to keep track of the number of false positives.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.FalsePositives()\n m.update_state([0, 1, 0, 0], [0, 0, 1, 1])\n print('Final result: ', m.result().numpy()) # Final result: 2\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', loss='mse', metrics=[tf.keras.metrics.FalsePositives()])\n ```\n \"\"\"\n\n def __init__(self, thresholds=None, name=None, dtype=None):\n \"\"\"Creates a `FalsePositives` instance.\n\n Args:\n thresholds: (Optional) Defaults to 0.5. A float value or a python\n list/tuple of float threshold values in [0, 1]. A threshold is compared\n with prediction values to determine the truth value of predictions\n (i.e., above the threshold is `true`, below is `false`). One metric\n value is generated for each threshold value.\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(FalsePositives, self).__init__(\n confusion_matrix_cond=metrics_utils.ConfusionMatrix.FALSE_POSITIVES,\n thresholds=thresholds,\n name=name,\n dtype=dtype)\n\n\n@keras_export('keras.metrics.FalseNegatives')\nclass FalseNegatives(_ConfusionMatrixConditionCount):\n \"\"\"Calculates the number of false negatives.\n\n For example, if `y_true` is [0, 1, 1, 1] and `y_pred` is [0, 1, 0, 0]\n then the false negatives value is 2. If the weights were specified as\n [0, 0, 1, 0] then the false negatives value would be 1.\n\n If `sample_weight` is given, calculates the sum of the weights of\n false negatives. This metric creates one local variable, `accumulator`\n that is used to keep track of the number of false negatives.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.FalseNegatives()\n m.update_state([0, 1, 1, 1], [0, 1, 0, 0])\n print('Final result: ', m.result().numpy()) # Final result: 2\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', loss='mse', metrics=[tf.keras.metrics.FalseNegatives()])\n ```\n \"\"\"\n\n def __init__(self, thresholds=None, name=None, dtype=None):\n \"\"\"Creates a `FalseNegatives` instance.\n\n Args:\n thresholds: (Optional) Defaults to 0.5. A float value or a python\n list/tuple of float threshold values in [0, 1]. A threshold is compared\n with prediction values to determine the truth value of predictions\n (i.e., above the threshold is `true`, below is `false`). One metric\n value is generated for each threshold value.\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(FalseNegatives, self).__init__(\n confusion_matrix_cond=metrics_utils.ConfusionMatrix.FALSE_NEGATIVES,\n thresholds=thresholds,\n name=name,\n dtype=dtype)\n\n\n@keras_export('keras.metrics.TrueNegatives')\nclass TrueNegatives(_ConfusionMatrixConditionCount):\n \"\"\"Calculates the number of true negatives.\n\n For example, if `y_true` is [0, 1, 0, 0] and `y_pred` is [1, 1, 0, 0]\n then the true negatives value is 2. If the weights were specified as\n [0, 0, 1, 0] then the true negatives value would be 1.\n\n If `sample_weight` is given, calculates the sum of the weights of\n true negatives. This metric creates one local variable, `accumulator`\n that is used to keep track of the number of true negatives.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.TrueNegatives()\n m.update_state([0, 1, 0, 0], [1, 1, 0, 0])\n print('Final result: ', m.result().numpy()) # Final result: 2\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', loss='mse', metrics=[tf.keras.metrics.TrueNegatives()])\n ```\n \"\"\"\n\n def __init__(self, thresholds=None, name=None, dtype=None):\n \"\"\"Creates a `TrueNegatives` instance.\n\n Args:\n thresholds: (Optional) Defaults to 0.5. A float value or a python\n list/tuple of float threshold values in [0, 1]. A threshold is compared\n with prediction values to determine the truth value of predictions\n (i.e., above the threshold is `true`, below is `false`). One metric\n value is generated for each threshold value.\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(TrueNegatives, self).__init__(\n confusion_matrix_cond=metrics_utils.ConfusionMatrix.TRUE_NEGATIVES,\n thresholds=thresholds,\n name=name,\n dtype=dtype)\n\n\n@keras_export('keras.metrics.TruePositives')\nclass TruePositives(_ConfusionMatrixConditionCount):\n \"\"\"Calculates the number of true positives.\n\n For example, if `y_true` is [0, 1, 1, 1] and `y_pred` is [1, 0, 1, 1]\n then the true positives value is 2. If the weights were specified as\n [0, 0, 1, 0] then the true positives value would be 1.\n\n If `sample_weight` is given, calculates the sum of the weights of\n true positives. This metric creates one local variable, `true_positives`\n that is used to keep track of the number of true positives.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.TruePositives()\n m.update_state([0, 1, 1, 1], [1, 0, 1, 1])\n print('Final result: ', m.result().numpy()) # Final result: 2\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', loss='mse', metrics=[tf.keras.metrics.TruePositives()])\n ```\n \"\"\"\n\n def __init__(self, thresholds=None, name=None, dtype=None):\n \"\"\"Creates a `TruePositives` instance.\n\n Args:\n thresholds: (Optional) Defaults to 0.5. A float value or a python\n list/tuple of float threshold values in [0, 1]. A threshold is compared\n with prediction values to determine the truth value of predictions\n (i.e., above the threshold is `true`, below is `false`). One metric\n value is generated for each threshold value.\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(TruePositives, self).__init__(\n confusion_matrix_cond=metrics_utils.ConfusionMatrix.TRUE_POSITIVES,\n thresholds=thresholds,\n name=name,\n dtype=dtype)\n\n\n@keras_export('keras.metrics.Precision')\nclass Precision(Metric):\n \"\"\"Computes the precision of the predictions with respect to the labels.\n\n For example, if `y_true` is [0, 1, 1, 1] and `y_pred` is [1, 0, 1, 1]\n then the precision value is 2/(2+1) ie. 0.66. If the weights were specified as\n [0, 0, 1, 0] then the precision value would be 1.\n\n The metric creates two local variables, `true_positives` and `false_positives`\n that are used to compute the precision. This value is ultimately returned as\n `precision`, an idempotent operation that simply divides `true_positives`\n by the sum of `true_positives` and `false_positives`.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n If `top_k` is set, we'll calculate precision as how often on average a class\n among the top-k classes with the highest predicted values of a batch entry is\n correct and can be found in the label for that entry.\n\n If `class_id` is specified, we calculate precision by considering only the\n entries in the batch for which `class_id` is above the threshold and/or in the\n top-k highest predictions, and computing the fraction of them for which\n `class_id` is indeed a correct label.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.Precision()\n m.update_state([0, 1, 1, 1], [1, 0, 1, 1])\n print('Final result: ', m.result().numpy()) # Final result: 0.66\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', loss='mse', metrics=[tf.keras.metrics.Precision()])\n ```\n \"\"\"\n\n def __init__(self,\n thresholds=None,\n top_k=None,\n class_id=None,\n name=None,\n dtype=None):\n \"\"\"Creates a `Precision` instance.\n\n Args:\n thresholds: (Optional) A float value or a python list/tuple of float\n threshold values in [0, 1]. A threshold is compared with prediction\n values to determine the truth value of predictions (i.e., above the\n threshold is `true`, below is `false`). One metric value is generated\n for each threshold value. If neither thresholds nor top_k are set, the\n default is to calculate precision with `thresholds=0.5`.\n top_k: (Optional) Unset by default. An int value specifying the top-k\n predictions to consider when calculating precision.\n class_id: (Optional) Integer class ID for which we want binary metrics.\n This must be in the half-open interval `[0, num_classes)`, where\n `num_classes` is the last dimension of predictions.\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(Precision, self).__init__(name=name, dtype=dtype)\n self.init_thresholds = thresholds\n self.top_k = top_k\n self.class_id = class_id\n\n default_threshold = 0.5 if top_k is None else metrics_utils.NEG_INF\n self.thresholds = metrics_utils.parse_init_thresholds(\n thresholds, default_threshold=default_threshold)\n self.true_positives = self.add_weight(\n 'true_positives',\n shape=(len(self.thresholds),),\n initializer=init_ops.zeros_initializer)\n self.false_positives = self.add_weight(\n 'false_positives',\n shape=(len(self.thresholds),),\n initializer=init_ops.zeros_initializer)\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n \"\"\"Accumulates true positive and false positive statistics.\n\n Args:\n y_true: The ground truth values, with the same dimensions as `y_pred`.\n Will be cast to `bool`.\n y_pred: The predicted values. Each element must be in the range `[0, 1]`.\n sample_weight: Optional weighting of each example. Defaults to 1. Can be a\n `Tensor` whose rank is either 0, or the same rank as `y_true`, and must\n be broadcastable to `y_true`.\n\n Returns:\n Update op.\n \"\"\"\n return metrics_utils.update_confusion_matrix_variables(\n {\n metrics_utils.ConfusionMatrix.TRUE_POSITIVES: self.true_positives,\n metrics_utils.ConfusionMatrix.FALSE_POSITIVES: self.false_positives\n },\n y_true,\n y_pred,\n thresholds=self.thresholds,\n top_k=self.top_k,\n class_id=self.class_id,\n sample_weight=sample_weight)\n\n def result(self):\n result = math_ops.div_no_nan(self.true_positives,\n self.true_positives + self.false_positives)\n return result[0] if len(self.thresholds) == 1 else result\n\n def reset_states(self):\n num_thresholds = len(to_list(self.thresholds))\n for v in self.variables:\n K.set_value(v, np.zeros((num_thresholds,)))\n\n def get_config(self):\n config = {\n 'thresholds': self.init_thresholds,\n 'top_k': self.top_k,\n 'class_id': self.class_id\n }\n base_config = super(Precision, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.metrics.Recall')\nclass Recall(Metric):\n \"\"\"Computes the recall of the predictions with respect to the labels.\n\n For example, if `y_true` is [0, 1, 1, 1] and `y_pred` is [1, 0, 1, 1]\n then the recall value is 2/(2+1) ie. 0.66. If the weights were specified as\n [0, 0, 1, 0] then the recall value would be 1.\n\n This metric creates two local variables, `true_positives` and\n `false_negatives`, that are used to compute the recall. This value is\n ultimately returned as `recall`, an idempotent operation that simply divides\n `true_positives` by the sum of `true_positives` and `false_negatives`.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n If `top_k` is set, recall will be computed as how often on average a class\n among the labels of a batch entry is in the top-k predictions.\n\n If `class_id` is specified, we calculate recall by considering only the\n entries in the batch for which `class_id` is in the label, and computing the\n fraction of them for which `class_id` is above the threshold and/or in the\n top-k predictions.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.Recall()\n m.update_state([0, 1, 1, 1], [1, 0, 1, 1])\n print('Final result: ', m.result().numpy()) # Final result: 0.66\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', loss='mse', metrics=[tf.keras.metrics.Recall()])\n ```\n \"\"\"\n\n def __init__(self,\n thresholds=None,\n top_k=None,\n class_id=None,\n name=None,\n dtype=None):\n \"\"\"Creates a `Recall` instance.\n\n Args:\n thresholds: (Optional) A float value or a python list/tuple of float\n threshold values in [0, 1]. A threshold is compared with prediction\n values to determine the truth value of predictions (i.e., above the\n threshold is `true`, below is `false`). One metric value is generated\n for each threshold value. If neither thresholds nor top_k are set, the\n default is to calculate recall with `thresholds=0.5`.\n top_k: (Optional) Unset by default. An int value specifying the top-k\n predictions to consider when calculating recall.\n class_id: (Optional) Integer class ID for which we want binary metrics.\n This must be in the half-open interval `[0, num_classes)`, where\n `num_classes` is the last dimension of predictions.\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(Recall, self).__init__(name=name, dtype=dtype)\n self.init_thresholds = thresholds\n self.top_k = top_k\n self.class_id = class_id\n\n default_threshold = 0.5 if top_k is None else metrics_utils.NEG_INF\n self.thresholds = metrics_utils.parse_init_thresholds(\n thresholds, default_threshold=default_threshold)\n self.true_positives = self.add_weight(\n 'true_positives',\n shape=(len(self.thresholds),),\n initializer=init_ops.zeros_initializer)\n self.false_negatives = self.add_weight(\n 'false_negatives',\n shape=(len(self.thresholds),),\n initializer=init_ops.zeros_initializer)\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n \"\"\"Accumulates true positive and false negative statistics.\n\n Args:\n y_true: The ground truth values, with the same dimensions as `y_pred`.\n Will be cast to `bool`.\n y_pred: The predicted values. Each element must be in the range `[0, 1]`.\n sample_weight: Optional weighting of each example. Defaults to 1. Can be a\n `Tensor` whose rank is either 0, or the same rank as `y_true`, and must\n be broadcastable to `y_true`.\n\n Returns:\n Update op.\n \"\"\"\n return metrics_utils.update_confusion_matrix_variables(\n {\n metrics_utils.ConfusionMatrix.TRUE_POSITIVES: self.true_positives,\n metrics_utils.ConfusionMatrix.FALSE_NEGATIVES: self.false_negatives\n },\n y_true,\n y_pred,\n thresholds=self.thresholds,\n top_k=self.top_k,\n class_id=self.class_id,\n sample_weight=sample_weight)\n\n def result(self):\n result = math_ops.div_no_nan(self.true_positives,\n self.true_positives + self.false_negatives)\n return result[0] if len(self.thresholds) == 1 else result\n\n def reset_states(self):\n num_thresholds = len(to_list(self.thresholds))\n for v in self.variables:\n K.set_value(v, np.zeros((num_thresholds,)))\n\n def get_config(self):\n config = {\n 'thresholds': self.init_thresholds,\n 'top_k': self.top_k,\n 'class_id': self.class_id\n }\n base_config = super(Recall, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass SensitivitySpecificityBase(Metric):\n \"\"\"Abstract base class for computing sensitivity and specificity.\n\n For additional information about specificity and sensitivity, see the\n following: https://en.wikipedia.org/wiki/Sensitivity_and_specificity\n \"\"\"\n\n def __init__(self, value, num_thresholds=200, name=None, dtype=None):\n super(SensitivitySpecificityBase, self).__init__(name=name, dtype=dtype)\n if num_thresholds <= 0:\n raise ValueError('`num_thresholds` must be > 0.')\n self.value = value\n self.true_positives = self.add_weight(\n 'true_positives',\n shape=(num_thresholds,),\n initializer=init_ops.zeros_initializer)\n self.true_negatives = self.add_weight(\n 'true_negatives',\n shape=(num_thresholds,),\n initializer=init_ops.zeros_initializer)\n self.false_positives = self.add_weight(\n 'false_positives',\n shape=(num_thresholds,),\n initializer=init_ops.zeros_initializer)\n self.false_negatives = self.add_weight(\n 'false_negatives',\n shape=(num_thresholds,),\n initializer=init_ops.zeros_initializer)\n\n # Compute `num_thresholds` thresholds in [0, 1]\n if num_thresholds == 1:\n self.thresholds = [0.5]\n else:\n thresholds = [(i + 1) * 1.0 / (num_thresholds - 1)\n for i in range(num_thresholds - 2)]\n self.thresholds = [0.0] + thresholds + [1.0]\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n \"\"\"Accumulates confusion matrix statistics.\n\n Args:\n y_true: The ground truth values.\n y_pred: The predicted values.\n sample_weight: Optional weighting of each example. Defaults to 1. Can be a\n `Tensor` whose rank is either 0, or the same rank as `y_true`, and must\n be broadcastable to `y_true`.\n\n Returns:\n Update op.\n \"\"\"\n return metrics_utils.update_confusion_matrix_variables(\n {\n metrics_utils.ConfusionMatrix.TRUE_POSITIVES: self.true_positives,\n metrics_utils.ConfusionMatrix.TRUE_NEGATIVES: self.true_negatives,\n metrics_utils.ConfusionMatrix.FALSE_POSITIVES: self.false_positives,\n metrics_utils.ConfusionMatrix.FALSE_NEGATIVES: self.false_negatives,\n },\n y_true,\n y_pred,\n thresholds=self.thresholds,\n sample_weight=sample_weight)\n\n def reset_states(self):\n num_thresholds = len(self.thresholds)\n for v in self.variables:\n K.set_value(v, np.zeros((num_thresholds,)))\n\n\n@keras_export('keras.metrics.SensitivityAtSpecificity')\nclass SensitivityAtSpecificity(SensitivitySpecificityBase):\n \"\"\"Computes the sensitivity at a given specificity.\n\n `Sensitivity` measures the proportion of actual positives that are correctly\n identified as such (tp / (tp + fn)).\n `Specificity` measures the proportion of actual negatives that are correctly\n identified as such (tn / (tn + fp)).\n\n This metric creates four local variables, `true_positives`, `true_negatives`,\n `false_positives` and `false_negatives` that are used to compute the\n sensitivity at the given specificity. The threshold for the given specificity\n value is computed and used to evaluate the corresponding sensitivity.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n For additional information about specificity and sensitivity, see the\n following: https://en.wikipedia.org/wiki/Sensitivity_and_specificity\n\n Usage:\n\n ```python\n m = tf.keras.metrics.SensitivityAtSpecificity(0.4, num_thresholds=1)\n m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9])\n print('Final result: ', m.result().numpy()) # Final result: 0.5\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile(\n 'sgd',\n loss='mse',\n metrics=[tf.keras.metrics.SensitivityAtSpecificity()])\n ```\n \"\"\"\n\n def __init__(self, specificity, num_thresholds=200, name=None, dtype=None):\n \"\"\"Creates a `SensitivityAtSpecificity` instance.\n\n Args:\n specificity: A scalar value in range `[0, 1]`.\n num_thresholds: (Optional) Defaults to 200. The number of thresholds to\n use for matching the given specificity.\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n if specificity < 0 or specificity > 1:\n raise ValueError('`specificity` must be in the range [0, 1].')\n self.specificity = specificity\n self.num_thresholds = num_thresholds\n super(SensitivityAtSpecificity, self).__init__(\n specificity, num_thresholds=num_thresholds, name=name, dtype=dtype)\n\n def result(self):\n # Calculate specificities at all the thresholds.\n specificities = math_ops.div_no_nan(\n self.true_negatives, self.true_negatives + self.false_positives)\n\n # Find the index of the threshold where the specificity is closest to the\n # given specificity.\n min_index = math_ops.argmin(\n math_ops.abs(specificities - self.value), axis=0)\n min_index = math_ops.cast(min_index, dtypes.int32)\n\n # Compute sensitivity at that index.\n return math_ops.div_no_nan(\n self.true_positives[min_index],\n self.true_positives[min_index] + self.false_negatives[min_index])\n\n def get_config(self):\n config = {\n 'num_thresholds': self.num_thresholds,\n 'specificity': self.specificity\n }\n base_config = super(SensitivityAtSpecificity, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.metrics.SpecificityAtSensitivity')\nclass SpecificityAtSensitivity(SensitivitySpecificityBase):\n \"\"\"Computes the specificity at a given sensitivity.\n\n `Sensitivity` measures the proportion of actual positives that are correctly\n identified as such (tp / (tp + fn)).\n `Specificity` measures the proportion of actual negatives that are correctly\n identified as such (tn / (tn + fp)).\n\n This metric creates four local variables, `true_positives`, `true_negatives`,\n `false_positives` and `false_negatives` that are used to compute the\n specificity at the given sensitivity. The threshold for the given sensitivity\n value is computed and used to evaluate the corresponding specificity.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n For additional information about specificity and sensitivity, see the\n following: https://en.wikipedia.org/wiki/Sensitivity_and_specificity\n\n Usage:\n\n ```python\n m = tf.keras.metrics.SpecificityAtSensitivity(0.8, num_thresholds=1)\n m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9])\n print('Final result: ', m.result().numpy()) # Final result: 1.0\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile(\n 'sgd',\n loss='mse',\n metrics=[tf.keras.metrics.SpecificityAtSensitivity()])\n ```\n \"\"\"\n\n def __init__(self, sensitivity, num_thresholds=200, name=None, dtype=None):\n \"\"\"Creates a `SpecificityAtSensitivity` instance.\n\n Args:\n sensitivity: A scalar value in range `[0, 1]`.\n num_thresholds: (Optional) Defaults to 200. The number of thresholds to\n use for matching the given specificity.\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n if sensitivity < 0 or sensitivity > 1:\n raise ValueError('`sensitivity` must be in the range [0, 1].')\n self.sensitivity = sensitivity\n self.num_thresholds = num_thresholds\n super(SpecificityAtSensitivity, self).__init__(\n sensitivity, num_thresholds=num_thresholds, name=name, dtype=dtype)\n\n def result(self):\n # Calculate sensitivities at all the thresholds.\n sensitivities = math_ops.div_no_nan(\n self.true_positives, self.true_positives + self.false_negatives)\n\n # Find the index of the threshold where the sensitivity is closest to the\n # given specificity.\n min_index = math_ops.argmin(\n math_ops.abs(sensitivities - self.value), axis=0)\n min_index = math_ops.cast(min_index, dtypes.int32)\n\n # Compute specificity at that index.\n return math_ops.div_no_nan(\n self.true_negatives[min_index],\n self.true_negatives[min_index] + self.false_positives[min_index])\n\n def get_config(self):\n config = {\n 'num_thresholds': self.num_thresholds,\n 'sensitivity': self.sensitivity\n }\n base_config = super(SpecificityAtSensitivity, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.metrics.AUC')\nclass AUC(Metric):\n \"\"\"Computes the approximate AUC (Area under the curve) via a Riemann sum.\n\n This metric creates four local variables, `true_positives`, `true_negatives`,\n `false_positives` and `false_negatives` that are used to compute the AUC.\n To discretize the AUC curve, a linearly spaced set of thresholds is used to\n compute pairs of recall and precision values. The area under the ROC-curve is\n therefore computed using the height of the recall values by the false positive\n rate, while the area under the PR-curve is the computed using the height of\n the precision values by the recall.\n\n This value is ultimately returned as `auc`, an idempotent operation that\n computes the area under a discretized curve of precision versus recall values\n (computed using the aforementioned variables). The `num_thresholds` variable\n controls the degree of discretization with larger numbers of thresholds more\n closely approximating the true AUC. The quality of the approximation may vary\n dramatically depending on `num_thresholds`.\n\n For best results, `predictions` should be distributed approximately uniformly\n in the range [0, 1] and not peaked around 0 or 1. The quality of the AUC\n approximation may be poor if this is not the case. Setting `summation_method`\n to 'minoring' or 'majoring' can help quantify the error in the approximation\n by providing lower or upper bound estimate of the AUC.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.AUC(num_thresholds=3)\n m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9])\n\n # threshold values are [0 - 1e-7, 0.5, 1 + 1e-7]\n # tp = [2, 1, 0], fp = [2, 0, 0], fn = [0, 1, 2], tn = [0, 2, 2]\n # recall = [1, 0.5, 0], fp_rate = [1, 0, 0]\n # auc = ((((1+0.5)/2)*(1-0))+ (((0.5+0)/2)*(0-0))) = 0.75\n\n print('Final result: ', m.result().numpy()) # Final result: 0.75\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', loss='mse', metrics=[tf.keras.metrics.AUC()])\n ```\n \"\"\"\n\n def __init__(self,\n num_thresholds=200,\n curve='ROC',\n summation_method='interpolation',\n name=None,\n dtype=None):\n \"\"\"Creates an `AUC` instance.\n\n Args:\n num_thresholds: (Optional) Defaults to 200. The number of thresholds to\n use when discretizing the roc curve. Values must be > 1.\n curve: (Optional) Specifies the name of the curve to be computed, 'ROC'\n [default] or 'PR' for the Precision-Recall-curve.\n summation_method: (Optional) Specifies the Riemann summation method used\n (https://en.wikipedia.org/wiki/Riemann_sum): 'interpolation' [default],\n applies mid-point summation scheme for `ROC`. For PR-AUC, interpolates\n (true/false) positives but not the ratio that is precision (see Davis\n & Goadrich 2006 for details); 'minoring' that applies left summation\n for increasing intervals and right summation for decreasing intervals;\n 'majoring' that does the opposite.\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n # Validate configurations.\n if num_thresholds <= 1:\n raise ValueError('`num_thresholds` must be > 1.')\n if isinstance(curve, metrics_utils.AUCCurve) and curve not in list(\n metrics_utils.AUCCurve):\n raise ValueError('Invalid curve: \"{}\". Valid options are: \"{}\"'.format(\n curve, list(metrics_utils.AUCCurve)))\n if isinstance(\n summation_method,\n metrics_utils.AUCSummationMethod) and summation_method not in list(\n metrics_utils.AUCSummationMethod):\n raise ValueError(\n 'Invalid summation method: \"{}\". Valid options are: \"{}\"'.format(\n summation_method, list(metrics_utils.AUCSummationMethod)))\n\n # Update properties.\n self.num_thresholds = num_thresholds\n if isinstance(curve, metrics_utils.AUCCurve):\n self.curve = curve\n else:\n self.curve = metrics_utils.AUCCurve.from_str(curve)\n if isinstance(summation_method, metrics_utils.AUCSummationMethod):\n self.summation_method = summation_method\n else:\n self.summation_method = metrics_utils.AUCSummationMethod.from_str(\n summation_method)\n super(AUC, self).__init__(name=name, dtype=dtype)\n\n # Create metric variables\n self.true_positives = self.add_weight(\n 'true_positives',\n shape=(num_thresholds,),\n initializer=init_ops.zeros_initializer)\n self.true_negatives = self.add_weight(\n 'true_negatives',\n shape=(num_thresholds,),\n initializer=init_ops.zeros_initializer)\n self.false_positives = self.add_weight(\n 'false_positives',\n shape=(num_thresholds,),\n initializer=init_ops.zeros_initializer)\n self.false_negatives = self.add_weight(\n 'false_negatives',\n shape=(num_thresholds,),\n initializer=init_ops.zeros_initializer)\n\n # Compute `num_thresholds` thresholds in [0, 1]\n thresholds = [\n (i + 1) * 1.0 / (num_thresholds - 1) for i in range(num_thresholds - 2)\n ]\n self.thresholds = [0.0 - K.epsilon()] + thresholds + [1.0 + K.epsilon()]\n # epsilon - to account for floating point imprecisions.\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n \"\"\"Accumulates confusion matrix statistics.\n\n Args:\n y_true: The ground truth values.\n y_pred: The predicted values.\n sample_weight: Optional weighting of each example. Defaults to 1. Can be a\n `Tensor` whose rank is either 0, or the same rank as `y_true`, and must\n be broadcastable to `y_true`.\n\n Returns:\n Update op.\n \"\"\"\n return metrics_utils.update_confusion_matrix_variables({\n metrics_utils.ConfusionMatrix.TRUE_POSITIVES: self.true_positives,\n metrics_utils.ConfusionMatrix.TRUE_NEGATIVES: self.true_negatives,\n metrics_utils.ConfusionMatrix.FALSE_POSITIVES: self.false_positives,\n metrics_utils.ConfusionMatrix.FALSE_NEGATIVES: self.false_negatives,\n }, y_true, y_pred, self.thresholds, sample_weight=sample_weight)\n\n def interpolate_pr_auc(self):\n \"\"\"Interpolation formula inspired by section 4 of Davis & Goadrich 2006.\n\n https://www.biostat.wisc.edu/~page/rocpr.pdf\n\n Note here we derive & use a closed formula not present in the paper\n as follows:\n\n Precision = TP / (TP + FP) = TP / P\n\n Modeling all of TP (true positive), FP (false positive) and their sum\n P = TP + FP (predicted positive) as varying linearly within each interval\n [A, B] between successive thresholds, we get\n\n Precision slope = dTP / dP\n = (TP_B - TP_A) / (P_B - P_A)\n = (TP - TP_A) / (P - P_A)\n Precision = (TP_A + slope * (P - P_A)) / P\n\n The area within the interval is (slope / total_pos_weight) times\n\n int_A^B{Precision.dP} = int_A^B{(TP_A + slope * (P - P_A)) * dP / P}\n int_A^B{Precision.dP} = int_A^B{slope * dP + intercept * dP / P}\n\n where intercept = TP_A - slope * P_A = TP_B - slope * P_B, resulting in\n\n int_A^B{Precision.dP} = TP_B - TP_A + intercept * log(P_B / P_A)\n\n Bringing back the factor (slope / total_pos_weight) we'd put aside, we get\n\n slope * [dTP + intercept * log(P_B / P_A)] / total_pos_weight\n\n where dTP == TP_B - TP_A.\n\n Note that when P_A == 0 the above calculation simplifies into\n\n int_A^B{Precision.dTP} = int_A^B{slope * dTP} = slope * (TP_B - TP_A)\n\n which is really equivalent to imputing constant precision throughout the\n first bucket having >0 true positives.\n\n Returns:\n pr_auc: an approximation of the area under the P-R curve.\n \"\"\"\n dtp = self.true_positives[:self.num_thresholds -\n 1] - self.true_positives[1:]\n p = self.true_positives + self.false_positives\n dp = p[:self.num_thresholds - 1] - p[1:]\n\n prec_slope = math_ops.div_no_nan(\n dtp, math_ops.maximum(dp, 0), name='prec_slope')\n intercept = self.true_positives[1:] - math_ops.multiply(prec_slope, p[1:])\n\n safe_p_ratio = array_ops.where(\n math_ops.logical_and(p[:self.num_thresholds - 1] > 0, p[1:] > 0),\n math_ops.div_no_nan(\n p[:self.num_thresholds - 1],\n math_ops.maximum(p[1:], 0),\n name='recall_relative_ratio'),\n array_ops.ones_like(p[1:]))\n\n return math_ops.reduce_sum(\n math_ops.div_no_nan(\n prec_slope * (dtp + intercept * math_ops.log(safe_p_ratio)),\n math_ops.maximum(self.true_positives[1:] + self.false_negatives[1:],\n 0),\n name='pr_auc_increment'),\n name='interpolate_pr_auc')\n\n def result(self):\n if (self.curve == metrics_utils.AUCCurve.PR and\n self.summation_method == metrics_utils.AUCSummationMethod.INTERPOLATION\n ):\n # This use case is different and is handled separately.\n return self.interpolate_pr_auc()\n\n # Set `x` and `y` values for the curves based on `curve` config.\n recall = math_ops.div_no_nan(self.true_positives,\n self.true_positives + self.false_negatives)\n if self.curve == metrics_utils.AUCCurve.ROC:\n fp_rate = math_ops.div_no_nan(self.false_positives,\n self.false_positives + self.true_negatives)\n x = fp_rate\n y = recall\n else: # curve == 'PR'.\n precision = math_ops.div_no_nan(\n self.true_positives, self.true_positives + self.false_positives)\n x = recall\n y = precision\n\n # Find the rectangle heights based on `summation_method`.\n if self.summation_method == metrics_utils.AUCSummationMethod.INTERPOLATION:\n # Note: the case ('PR', 'interpolation') has been handled above.\n heights = (y[:self.num_thresholds - 1] + y[1:]) / 2.\n elif self.summation_method == metrics_utils.AUCSummationMethod.MINORING:\n heights = math_ops.minimum(y[:self.num_thresholds - 1], y[1:])\n else: # self.summation_method = metrics_utils.AUCSummationMethod.MAJORING:\n heights = math_ops.maximum(y[:self.num_thresholds - 1], y[1:])\n\n # Sum up the areas of all the rectangles.\n return math_ops.reduce_sum(\n math_ops.multiply(x[:self.num_thresholds - 1] - x[1:], heights),\n name=self.name)\n\n def reset_states(self):\n num_thresholds = len(self.thresholds)\n for v in self.variables:\n K.set_value(v, np.zeros((num_thresholds,)))\n\n def get_config(self):\n config = {\n 'num_thresholds': self.num_thresholds,\n 'curve': self.curve.value,\n 'summation_method': self.summation_method.value,\n }\n base_config = super(AUC, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.metrics.CosineProximity')\nclass CosineProximity(MeanMetricWrapper):\n \"\"\"Computes the cosine distance between the labels and predictions.\n\n For example, if `y_true` is [0, 1, 1], and `y_pred` is [1, 0, 1], the cosine\n proximity is -0.5.\n\n This metric keeps the average cosine distance between `predictions` and\n `labels` over a stream of data.\n\n Usage:\n ```python\n m = tf.metrics.CosineProximity()\n m.update_state([0, 1, 1], [1, 0, 1])\n print('Final result: ', m.result().numpy()) # Final result: -0.5\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile(\n 'sgd',\n loss='mse',\n metrics=[tf.metrics.CosineProximity()])\n ```\n \"\"\"\n\n def __init__(self, name='cosine_proximity', dtype=None, axis=-1):\n \"\"\"Creates a `CosineProximity` instance.\n\n Args:\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n axis: (Optional) Defaults to -1. The dimension along which the cosine\n proximity is computed.\n \"\"\"\n super(CosineProximity, self).__init__(cosine, name, dtype=dtype, axis=axis)\n\n\n@keras_export('keras.metrics.MeanAbsoluteError')\nclass MeanAbsoluteError(MeanMetricWrapper):\n \"\"\"Computes the mean absolute error between the labels and predictions.\n\n For example, if `y_true` is [0., 0., 1., 1.], and `y_pred` is [1., 1., 1., 0.]\n the mean absolute error is 3/4 (0.75).\n\n Usage:\n ```python\n m = tf.metrics.MeanAbsoluteError()\n m.update_state([0., 0., 1., 1.], [1., 1., 1., 0.])\n print('Final result: ', m.result().numpy()) # Final result: 0.75\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', metrics=[tf.keras.metrics.MeanAbsoluteError()])\n ```\n \"\"\"\n\n def __init__(self, name='mean_absolute_error', dtype=None):\n super(MeanAbsoluteError, self).__init__(\n mean_absolute_error, name, dtype=dtype)\n\n\n@keras_export('keras.metrics.MeanAbsolutePercentageError')\nclass MeanAbsolutePercentageError(MeanMetricWrapper):\n \"\"\"Computes the mean absolute percentage error between `y_true` and `y_pred`.\n\n For example, if `y_true` is [0., 0., 1., 1.], and `y_pred` is [1., 1., 1., 0.]\n the mean absolute percentage error is 5e+08.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.MeanAbsolutePercentageError()\n m.update_state([0., 0., 1., 1.], [1., 1., 1., 0.])\n print('Final result: ', m.result().numpy()) # Final result: 5e+08\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', metrics=[tf.keras.metrics.MeanAbsolutePercentageError()])\n ```\n \"\"\"\n\n def __init__(self, name='mean_absolute_percentage_error', dtype=None):\n super(MeanAbsolutePercentageError, self).__init__(\n mean_absolute_percentage_error, name, dtype=dtype)\n\n\n@keras_export('keras.metrics.MeanSquaredError')\nclass MeanSquaredError(MeanMetricWrapper):\n \"\"\"Computes the mean squared error between `y_true` and `y_pred`.\n\n For example, if `y_true` is [0., 0., 1., 1.], and `y_pred` is [1., 1., 1., 0.]\n the mean squared error is 3/4 (0.75).\n\n Usage:\n\n ```python\n m = tf.keras.metrics.MeanSquaredError()\n m.update_state([0., 0., 1., 1.], [1., 1., 1., 0.])\n print('Final result: ', m.result().numpy()) # Final result: 0.75\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', metrics=[tf.keras.metrics.MeanSquaredError()])\n ```\n \"\"\"\n\n def __init__(self, name='mean_squared_error', dtype=None):\n super(MeanSquaredError, self).__init__(\n mean_squared_error, name, dtype=dtype)\n\n\n@keras_export('keras.metrics.MeanSquaredLogarithmicError')\nclass MeanSquaredLogarithmicError(MeanMetricWrapper):\n \"\"\"Computes the mean squared logarithmic error between `y_true` and `y_pred`.\n\n For example, if `y_true` is [0., 0., 1., 1.], and `y_pred` is [1., 1., 1., 0.]\n the mean squared logarithmic error is 0.36034.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.MeanSquaredLogarithmicError()\n m.update_state([0., 0., 1., 1.], [1., 1., 1., 0.])\n print('Final result: ', m.result().numpy()) # Final result: 0.36034\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', metrics=[tf.keras.metrics.MeanSquaredLogarithmicError()])\n ```\n \"\"\"\n\n def __init__(self, name='mean_squared_logarithmic_error', dtype=None):\n super(MeanSquaredLogarithmicError, self).__init__(\n mean_squared_logarithmic_error, name, dtype=dtype)\n\n\n@keras_export('keras.metrics.Hinge')\nclass Hinge(MeanMetricWrapper):\n \"\"\"Computes the hinge metric between `y_true` and `y_pred`.\n\n For example, if `y_true` is [0., 1., 1.], and `y_pred` is [1., 0., 1.]\n the hinge metric value is 0.66.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.Hinge()\n m.update_state([0., 1., 1.], [1., 0., 1.])\n print('Final result: ', m.result().numpy()) # Final result: 0.66\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', metrics=[tf.keras.metrics.Hinge()])\n ```\n \"\"\"\n\n def __init__(self, name='hinge', dtype=None):\n super(Hinge, self).__init__(hinge, name, dtype=dtype)\n\n\n@keras_export('keras.metrics.SquaredHinge')\nclass SquaredHinge(MeanMetricWrapper):\n \"\"\"Computes the squared hinge metric between `y_true` and `y_pred`.\n\n For example, if `y_true` is [0., 1., 1.], and `y_pred` is [1., 0., 1.]\n the squared hinge metric value is 0.66.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.SquaredHinge()\n m.update_state([0., 1., 1.], [1., 0., 1.])\n print('Final result: ', m.result().numpy()) # Final result: 0.66\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', metrics=[tf.keras.metrics.SquaredHinge()])\n ```\n \"\"\"\n\n def __init__(self, name='squared_hinge', dtype=None):\n super(SquaredHinge, self).__init__(squared_hinge, name, dtype=dtype)\n\n\n@keras_export('keras.metrics.CategoricalHinge')\nclass CategoricalHinge(MeanMetricWrapper):\n \"\"\"Computes the categorical hinge metric between `y_true` and `y_pred`.\n\n For example, if `y_true` is [0., 1., 1.], and `y_pred` is [1., 0., 1.]\n the categorical hinge metric value is 1.0.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.CategoricalHinge()\n m.update_state([0., 1., 1.], [1., 0., 1.])\n print('Final result: ', m.result().numpy()) # Final result: 1.0\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', metrics=[tf.keras.metrics.CategoricalHinge()])\n ```\n \"\"\"\n\n def __init__(self, name='categorical_hinge', dtype=None):\n super(CategoricalHinge, self).__init__(categorical_hinge, name, dtype=dtype)\n\n\n@keras_export('keras.metrics.RootMeanSquaredError')\nclass RootMeanSquaredError(Mean):\n \"\"\"Computes root mean squared error metric between `y_true` and `y_pred`.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.RootMeanSquaredError()\n m.update_state([2., 4., 6.], [1., 3., 2.])\n print('Final result: ', m.result().numpy()) # Final result: 2.449\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', metrics=[tf.keras.metrics.RootMeanSquaredError()])\n ```\n \"\"\"\n\n def __init__(self, name='root_mean_squared_error', dtype=None):\n super(RootMeanSquaredError, self).__init__(name, dtype=dtype)\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n \"\"\"Accumulates root mean squared error statistics.\n\n Args:\n y_true: The ground truth values.\n y_pred: The predicted values.\n sample_weight: Optional weighting of each example. Defaults to 1. Can be a\n `Tensor` whose rank is either 0, or the same rank as `y_true`, and must\n be broadcastable to `y_true`.\n\n Returns:\n Update op.\n \"\"\"\n y_true = math_ops.cast(y_true, self._dtype)\n y_pred = math_ops.cast(y_pred, self._dtype)\n y_pred, y_true, sample_weight = squeeze_or_expand_dimensions(\n y_pred, y_true, sample_weight)\n error_sq = math_ops.squared_difference(y_pred, y_true)\n return super(RootMeanSquaredError, self).update_state(\n error_sq, sample_weight=sample_weight)\n\n def result(self):\n return math_ops.sqrt(math_ops.div_no_nan(self.total, self.count))\n\n\n@keras_export('keras.metrics.LogCoshError')\nclass LogCoshError(MeanMetricWrapper):\n \"\"\"Computes the logarithm of the hyperbolic cosine of the prediction error.\n\n `logcosh = log((exp(x) + exp(-x))/2)`, where x is the error (y_pred - y_true)\n\n Usage:\n\n ```python\n m = tf.keras.metrics.LogCoshError()\n m.update_state([0., 1., 1.], [1., 0., 1.])\n print('Final result: ', m.result().numpy()) # Final result: 0.289\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', metrics=[tf.keras.metrics.LogCoshError()])\n ```\n \"\"\"\n\n def __init__(self, name='logcosh', dtype=None):\n super(LogCoshError, self).__init__(logcosh, name, dtype=dtype)\n\n\n@keras_export('keras.metrics.Poisson')\nclass Poisson(MeanMetricWrapper):\n \"\"\"Computes the Poisson metric between `y_true` and `y_pred`.\n\n `metric = y_pred - y_true * log(y_pred)`\n\n Usage:\n\n ```python\n m = tf.keras.metrics.Poisson()\n m.update_state([1, 9, 2], [4, 8, 12])\n print('Final result: ', m.result().numpy()) # Final result: -4.63\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', metrics=[tf.keras.metrics.Poisson()])\n ```\n \"\"\"\n\n def __init__(self, name='poisson', dtype=None):\n super(Poisson, self).__init__(poisson, name, dtype=dtype)\n\n\n@keras_export('keras.metrics.KLDivergence')\nclass KLDivergence(MeanMetricWrapper):\n \"\"\"Computes Kullback Leibler divergence metric between `y_true` and `y_pred`.\n\n `metric = y_true * log(y_true / y_pred)`\n\n Usage:\n\n ```python\n m = tf.keras.metrics.KLDivergence()\n m.update_state([.4, .9, .2], [.5, .8, .12])\n print('Final result: ', m.result().numpy()) # Final result: -0.043\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile('sgd', metrics=[tf.keras.metrics.KLDivergence()])\n ```\n \"\"\"\n\n def __init__(self, name='kullback_leibler_divergence', dtype=None):\n super(KLDivergence, self).__init__(\n kullback_leibler_divergence, name, dtype=dtype)\n\n\n@keras_export('keras.metrics.MeanIoU')\nclass MeanIoU(Metric):\n \"\"\"Computes the mean Intersection-Over-Union metric.\n\n Mean Intersection-Over-Union is a common evaluation metric for semantic image\n segmentation, which first computes the IOU for each semantic class and then\n computes the average over classes. IOU is defined as follows:\n IOU = true_positive / (true_positive + false_positive + false_negative).\n The predictions are accumulated in a confusion matrix, weighted by\n `sample_weight` and the metric is then calculated from it.\n\n If `sample_weight` is `None`, weights default to 1.\n Use `sample_weight` of 0 to mask values.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.MeanIoU(num_classes=2)\n m.update_state([0, 0, 1, 1], [0, 1, 0, 1])\n\n # cm = [[1, 1],\n [1, 1]]\n # sum_row = [2, 2], sum_col = [2, 2], true_positives = [1, 1]\n # iou = true_positives / (sum_row + sum_col - true_positives))\n # result = (1 / (2 + 2 - 1) + 1 / (2 + 2 - 1)) / 2 = 0.33\n print('Final result: ', m.result().numpy()) # Final result: 0.33\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile(\n 'sgd',\n loss='mse',\n metrics=[tf.keras.metrics.MeanIoU(num_classes=2)])\n ```\n \"\"\"\n\n def __init__(self, num_classes, name=None, dtype=None):\n \"\"\"Creates a `MeanIoU` instance.\n\n Args:\n num_classes: The possible number of labels the prediction task can have.\n This value must be provided, since a confusion matrix of dimension =\n [num_classes, num_classes] will be allocated.\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(MeanIoU, self).__init__(name=name, dtype=dtype)\n self.num_classes = num_classes\n\n # Variable to accumulate the predictions in the confusion matrix. Setting\n # the type to be `float64` as required by confusion_matrix_ops.\n self.total_cm = self.add_weight(\n 'total_confusion_matrix',\n shape=(num_classes, num_classes),\n initializer=init_ops.zeros_initializer,\n dtype=dtypes.float64)\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n \"\"\"Accumulates the confusion matrix statistics.\n\n Args:\n y_true: The ground truth values.\n y_pred: The predicted values.\n sample_weight: Optional weighting of each example. Defaults to 1. Can be a\n `Tensor` whose rank is either 0, or the same rank as `y_true`, and must\n be broadcastable to `y_true`.\n\n Returns:\n Update op.\n \"\"\"\n # Flatten the input if its rank > 1.\n if y_pred.shape.ndims > 1:\n y_pred = array_ops.reshape(y_pred, [-1])\n\n if y_true.shape.ndims > 1:\n y_true = array_ops.reshape(y_true, [-1])\n\n if sample_weight is not None and sample_weight.shape.ndims > 1:\n sample_weight = array_ops.reshape(sample_weight, [-1])\n\n # Accumulate the prediction to current confusion matrix.\n current_cm = confusion_matrix.confusion_matrix(\n y_true,\n y_pred,\n self.num_classes,\n weights=sample_weight,\n dtype=dtypes.float64)\n return self.total_cm.assign_add(current_cm)\n\n def result(self):\n \"\"\"Compute the mean intersection-over-union via the confusion matrix.\"\"\"\n sum_over_row = math_ops.cast(\n math_ops.reduce_sum(self.total_cm, axis=0), dtype=self._dtype)\n sum_over_col = math_ops.cast(\n math_ops.reduce_sum(self.total_cm, axis=1), dtype=self._dtype)\n true_positives = math_ops.cast(\n array_ops.diag_part(self.total_cm), dtype=self._dtype)\n\n # sum_over_row + sum_over_col =\n # 2 * true_positives + false_positives + false_negatives.\n denominator = sum_over_row + sum_over_col - true_positives\n\n # The mean is only computed over classes that appear in the\n # label or prediction tensor. If the denominator is 0, we need to\n # ignore the class.\n num_valid_entries = math_ops.reduce_sum(\n math_ops.cast(math_ops.not_equal(denominator, 0), dtype=self._dtype))\n\n iou = math_ops.div_no_nan(true_positives, denominator)\n\n return math_ops.div_no_nan(\n math_ops.reduce_sum(iou, name='mean_iou'), num_valid_entries)\n\n def reset_states(self):\n K.set_value(self.total_cm, np.zeros((self.num_classes, self.num_classes)))\n\n def get_config(self):\n config = {'num_classes': self.num_classes}\n base_config = super(MeanIoU, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.metrics.MeanTensor')\nclass MeanTensor(Metric):\n \"\"\"Computes the element-wise (weighted) mean of the given tensors.\n\n `MeanTensor` returns a tensor with the same shape of the input tensors. The\n mean value is updated by keeping local variables `total` and `count`. The\n `total` tracks the sum of the weighted values, and `count` stores the sum of\n the weighted counts.\n\n Usage:\n\n ```python\n m = tf.metrics.MeanTensor()\n m.update_state([0, 1, 2, 3])\n m.update_state([4, 5, 6, 7])\n print('Result: ', m.result().numpy()) # Result: [2, 3, 4, 5]\n m.update_state([12, 10, 8, 6], sample_weights= [0, 0.2, 0.5, 1])\n print('Result: ', m.result().numpy()) # Result: [2, 3.636, 4.8, 5.333]\n ```\n \"\"\"\n\n def __init__(self, name='mean_tensor', dtype=None):\n \"\"\"Creates a `MeanTensor` instance.\n\n Args:\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n \"\"\"\n super(MeanTensor, self).__init__(name=name, dtype=dtype)\n self._shape = None\n self._total = None\n self._count = None\n self._built = False\n\n def _build(self, shape):\n self._shape = tensor_shape.TensorShape(shape)\n # Create new state variables\n self._total = self.add_weight(\n 'total', shape=shape, initializer=init_ops.zeros_initializer)\n self._count = self.add_weight(\n 'count', shape=shape, initializer=init_ops.zeros_initializer)\n with ops.init_scope():\n if not context.executing_eagerly():\n K._initialize_variables(K._get_session()) # pylint: disable=protected-access\n self._built = True\n\n @property\n def total(self):\n return self._total if self._built else None\n\n @property\n def count(self):\n return self._count if self._built else None\n\n def update_state(self, values, sample_weight=None):\n \"\"\"Accumulates statistics for computing the element-wise mean.\n\n Args:\n values: Per-example value.\n sample_weight: Optional weighting of each example. Defaults to 1.\n\n Returns:\n Update op.\n \"\"\"\n values = math_ops.cast(values, self._dtype)\n if not self._built:\n self._build(values.shape)\n elif values.shape != self._shape:\n raise ValueError('MeanTensor input values must always have the same '\n 'shape. Expected shape (set during the first call): {}. '\n 'Got: {}'.format(self._shape, values.get_shape()))\n\n num_values = array_ops.ones_like(values)\n if sample_weight is not None:\n sample_weight = math_ops.cast(sample_weight, self._dtype)\n\n # Update dimensions of weights to match with values if possible.\n values, _, sample_weight = squeeze_or_expand_dimensions(\n values, None, sample_weight)\n try:\n # Broadcast weights if possible.\n sample_weight = weights_broadcast_ops.broadcast_weights(\n sample_weight, values)\n except ValueError:\n # Reduce values to same ndim as weight array\n ndim = K.ndim(values)\n weight_ndim = K.ndim(sample_weight)\n values = math_ops.reduce_mean(\n values, axis=list(range(weight_ndim, ndim)))\n\n num_values = math_ops.multiply(num_values, sample_weight)\n values = math_ops.multiply(values, sample_weight)\n\n update_total_op = self._total.assign_add(values)\n with ops.control_dependencies([update_total_op]):\n return self._count.assign_add(num_values)\n\n def result(self):\n if not self._built:\n raise ValueError(\n 'MeanTensor does not have any result yet. Please call the MeanTensor '\n 'instance or use `.update_state(value)` before retrieving the result.'\n )\n return math_ops.div_no_nan(self.total, self.count)\n\n def reset_states(self):\n if self._built:\n for v in self.variables:\n K.set_value(v, np.zeros(self._shape.as_list()))\n\n\n@keras_export('keras.metrics.BinaryCrossentropy')\nclass BinaryCrossentropy(MeanMetricWrapper):\n \"\"\"Computes the crossentropy metric between the labels and predictions.\n\n This is the crossentropy metric class to be used when there are only two\n label classes (0 and 1).\n\n Usage:\n\n ```python\n m = tf.keras.metrics.BinaryCrossentropy()\n m.update_state([1., 0., 1., 0.], [1., 1., 1., 0.])\n\n # EPSILON = 1e-7, y = y_true, y` = y_pred, Y_MAX = 0.9999999\n # y` = clip_ops.clip_by_value(output, EPSILON, 1. - EPSILON)\n # y` = [Y_MAX, Y_MAX, Y_MAX, EPSILON]\n\n # Metric = -(y log(y` + EPSILON) + (1 - y) log(1 - y` + EPSILON))\n # = [-log(Y_MAX + EPSILON), -log(1 - Y_MAX + EPSILON),\n # -log(Y_MAX + EPSILON), -log(1)]\n # = [(0 + 15.33) / 2, (0 + 0) / 2]\n # Reduced metric = 7.665 / 2\n\n print('Final result: ', m.result().numpy()) # Final result: 3.833\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile(\n 'sgd',\n loss='mse',\n metrics=[tf.keras.metrics.BinaryCrossentropy()])\n ```\n \"\"\"\n\n def __init__(self,\n name='binary_crossentropy',\n dtype=None,\n from_logits=False,\n label_smoothing=0):\n \"\"\"Creates a `BinaryCrossentropy` instance.\n\n Args:\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n from_logits: (Optional )Whether output is expected to be a logits tensor.\n By default, we consider that output encodes a probability distribution.\n label_smoothing: (Optional) Float in [0, 1]. When > 0, label values are\n smoothed, meaning the confidence on label values are relaxed.\n e.g. `label_smoothing=0.2` means that we will use a value of `0.1` for\n label `0` and `0.9` for label `1`\"\n \"\"\"\n label_smoothing = ops.convert_to_tensor(label_smoothing, dtype=K.floatx())\n\n super(BinaryCrossentropy, self).__init__(\n binary_crossentropy,\n name,\n dtype=dtype,\n from_logits=from_logits,\n label_smoothing=label_smoothing)\n\n\n@keras_export('keras.metrics.CategoricalCrossentropy')\nclass CategoricalCrossentropy(MeanMetricWrapper):\n \"\"\"Computes the crossentropy metric between the labels and predictions.\n\n This is the crossentropy metric class to be used when there are multiple\n label classes (2 or more). Here we assume that labels are given as a `one_hot`\n representation. eg., When labels values are [2, 0, 1],\n `y_true` = [[0, 0, 1], [1, 0, 0], [0, 1, 0]].\n\n Usage:\n\n ```python\n m = tf.keras.metrics.CategoricalCrossentropy()\n m.update_state([[0, 1, 0], [0, 0, 1]],\n [[0.05, 0.95, 0], [0.1, 0.8, 0.1]])\n\n # EPSILON = 1e-7, y = y_true, y` = y_pred\n # y` = clip_ops.clip_by_value(output, EPSILON, 1. - EPSILON)\n # y` = [[0.05, 0.95, EPSILON], [0.1, 0.8, 0.1]]\n\n # xent = -sum(y * log(y'), axis = -1)\n # = -((log 0.95), (log 0.1))\n # = [0.051, 2.302]\n # Reduced xent = (0.051 + 2.302) / 2\n\n print('Final result: ', m.result().numpy()) # Final result: 1.176\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile(\n 'sgd',\n loss='mse',\n metrics=[tf.keras.metrics.CategoricalCrossentropy()])\n ```\n\n Args:\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n from_logits: (Optional ) Whether `y_pred` is expected to be a logits tensor.\n By default, we assume that `y_pred` encodes a probability distribution.\n label_smoothing: Float in [0, 1]. When > 0, label values are smoothed,\n meaning the confidence on label values are relaxed. e.g.\n `label_smoothing=0.2` means that we will use a value of `0.1` for label\n `0` and `0.9` for label `1`\"\n \"\"\"\n\n def __init__(self,\n name='categorical_crossentropy',\n dtype=None,\n from_logits=False,\n label_smoothing=0):\n label_smoothing = ops.convert_to_tensor(label_smoothing, dtype=K.floatx())\n\n super(CategoricalCrossentropy, self).__init__(\n categorical_crossentropy,\n name,\n dtype=dtype,\n from_logits=from_logits,\n label_smoothing=label_smoothing)\n\n\n@keras_export('keras.metrics.SparseCategoricalCrossentropy')\nclass SparseCategoricalCrossentropy(MeanMetricWrapper):\n \"\"\"Computes the crossentropy metric between the labels and predictions.\n\n Use this crossentropy metric when there are two or more label classes.\n We expect labels to be provided as integers. If you want to provide labels\n using `one-hot` representation, please use `CategoricalCrossentropy` metric.\n There should be `# classes` floating point values per feature for `y_pred`\n and a single floating point value per feature for `y_true`.\n\n In the snippet below, there is a single floating point value per example for\n `y_true` and `# classes` floating pointing values per example for `y_pred`.\n The shape of `y_true` is `[batch_size]` and the shape of `y_pred` is\n `[batch_size, num_classes]`.\n\n Usage:\n\n ```python\n m = tf.keras.metrics.SparseCategoricalCrossentropy()\n m.update_state(\n [1, 2],\n [[0.05, 0.95, 0], [0.1, 0.8, 0.1]])\n\n # y_true = one_hot(y_true) = [[0, 1, 0], [0, 0, 1]]\n # logits = log(y_pred)\n # softmax = exp(logits) / sum(exp(logits), axis=-1)\n # softmax = [[0.05, 0.95, EPSILON], [0.1, 0.8, 0.1]]\n\n # xent = -sum(y * log(softmax), 1)\n # log(softmax) = [[-2.9957, -0.0513, -16.1181], [-2.3026, -0.2231, -2.3026]]\n # y_true * log(softmax) = [[0, -0.0513, 0], [0, 0, -2.3026]]\n\n # xent = [0.0513, 2.3026]\n # Reduced xent = (0.0513 + 2.3026) / 2\n\n print('Final result: ', m.result().numpy()) # Final result: 1.176\n ```\n\n Usage with tf.keras API:\n\n ```python\n model = keras.models.Model(inputs, outputs)\n model.compile(\n 'sgd',\n loss='mse',\n metrics=[tf.keras.metrics.SparseCategoricalCrossentropy()])\n ```\n\n Args:\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n from_logits: (Optional ) Whether `y_pred` is expected to be a logits tensor.\n By default, we assume that `y_pred` encodes a probability distribution.\n axis: (Optional) Defaults to -1. The dimension along which the metric is\n computed.\n \"\"\"\n\n def __init__(self,\n name='sparse_categorical_crossentropy',\n dtype=None,\n from_logits=False,\n axis=-1):\n\n super(SparseCategoricalCrossentropy, self).__init__(\n sparse_categorical_crossentropy,\n name,\n dtype=dtype,\n from_logits=from_logits,\n axis=axis)\n\n\ndef accuracy(y_true, y_pred):\n y_pred.get_shape().assert_is_compatible_with(y_true.get_shape())\n if y_true.dtype != y_pred.dtype:\n y_pred = math_ops.cast(y_pred, y_true.dtype)\n return math_ops.cast(math_ops.equal(y_true, y_pred), K.floatx())\n\n\n@keras_export('keras.metrics.binary_accuracy')\ndef binary_accuracy(y_true, y_pred, threshold=0.5):\n threshold = math_ops.cast(threshold, y_pred.dtype)\n y_pred = math_ops.cast(y_pred > threshold, y_pred.dtype)\n return K.mean(math_ops.equal(y_true, y_pred), axis=-1)\n\n\n@keras_export('keras.metrics.categorical_accuracy')\ndef categorical_accuracy(y_true, y_pred):\n return math_ops.cast(\n math_ops.equal(\n math_ops.argmax(y_true, axis=-1), math_ops.argmax(y_pred, axis=-1)),\n K.floatx())\n\n\n@keras_export('keras.metrics.sparse_categorical_accuracy')\ndef sparse_categorical_accuracy(y_true, y_pred):\n y_pred_rank = ops.convert_to_tensor(y_pred).get_shape().ndims\n y_true_rank = ops.convert_to_tensor(y_true).get_shape().ndims\n # If the shape of y_true is (num_samples, 1), squeeze to (num_samples,)\n if (y_true_rank is not None) and (y_pred_rank is not None) and (len(\n K.int_shape(y_true)) == len(K.int_shape(y_pred))):\n y_true = array_ops.squeeze(y_true, [-1])\n y_pred = math_ops.argmax(y_pred, axis=-1)\n\n # If the predicted output and actual output types don't match, force cast them\n # to match.\n if K.dtype(y_pred) != K.dtype(y_true):\n y_pred = math_ops.cast(y_pred, K.dtype(y_true))\n\n return math_ops.cast(math_ops.equal(y_true, y_pred), K.floatx())\n\n\n@keras_export('keras.metrics.top_k_categorical_accuracy')\ndef top_k_categorical_accuracy(y_true, y_pred, k=5):\n return K.mean(\n nn.in_top_k(y_pred, math_ops.argmax(y_true, axis=-1), k), axis=-1)\n\n\n@keras_export('keras.metrics.sparse_top_k_categorical_accuracy')\ndef sparse_top_k_categorical_accuracy(y_true, y_pred, k=5):\n y_pred_rank = ops.convert_to_tensor(y_pred).get_shape().ndims\n y_true_rank = ops.convert_to_tensor(y_true).get_shape().ndims\n # If the shape of y_true is (num_samples, 1), squeeze to (num_samples,)\n if (y_true_rank is not None) and (y_pred_rank is not None) and (len(\n K.int_shape(y_true)) == len(K.int_shape(y_pred))):\n y_true = array_ops.squeeze(y_true, [-1])\n\n return K.mean(nn.in_top_k(y_pred, math_ops.cast(y_true, 'int32'), k), axis=-1)\n\n# Aliases\n\nmse = MSE = mean_squared_error\nmae = MAE = mean_absolute_error\nmape = MAPE = mean_absolute_percentage_error\nmsle = MSLE = mean_squared_logarithmic_error\ncosine = cosine_proximity\n\n\ndef clone_metric(metric):\n \"\"\"Returns a clone of the metric if stateful, otherwise returns it as is.\"\"\"\n if isinstance(metric, Metric):\n return metric.__class__.from_config(metric.get_config())\n return metric\n\n\ndef clone_metrics(metrics):\n \"\"\"Clones the given metric list/dict.\"\"\"\n if metrics is None:\n return None\n if isinstance(metrics, dict):\n return {key: clone_metric(value) for key, value in metrics.items()}\n return [clone_metric(metric) for metric in metrics]\n\n\n@keras_export('keras.metrics.serialize')\ndef serialize(metric):\n return serialize_keras_object(metric)\n\n\n@keras_export('keras.metrics.deserialize')\ndef deserialize(config, custom_objects=None):\n return deserialize_keras_object(\n config,\n module_objects=globals(),\n custom_objects=custom_objects,\n printable_module_name='metric function')\n\n\n@keras_export('keras.metrics.get')\ndef get(identifier):\n if isinstance(identifier, dict):\n return deserialize(identifier)\n elif isinstance(identifier, six.string_types):\n return deserialize(str(identifier))\n elif callable(identifier):\n return identifier\n else:\n raise ValueError('Could not interpret '\n 'metric function identifier: %s' % identifier)\n"
] |
[
[
"tensorflow.python.ops.array_ops.identity",
"tensorflow.python.ops.math_ops.equal",
"tensorflow.python.keras.utils.generic_utils.serialize_keras_object",
"tensorflow.python.keras.utils.tf_utils.is_tensor_or_variable",
"tensorflow.python.ops.math_ops.minimum",
"tensorflow.python.framework.ops.init_scope",
"tensorflow.python.ops.math_ops.reduce_sum",
"tensorflow.python.ops.math_ops.div_no_nan",
"tensorflow.python.ops.array_ops.ones_like",
"tensorflow.python.ops.confusion_matrix.remove_squeezable_dimensions",
"tensorflow.python.keras.backend.int_shape",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.framework.ops.control_dependencies",
"tensorflow.python.keras.backend.ndim",
"tensorflow.python.ops.math_ops.cast",
"tensorflow.python.util.tf_export.keras_export",
"tensorflow.python.keras.backend.epsilon",
"tensorflow.python.keras.utils.losses_utils.squeeze_or_expand_dimensions",
"tensorflow.python.keras.utils.metrics_utils.update_state_wrapper",
"tensorflow.python.ops.math_ops.log",
"tensorflow.python.keras.utils.metrics_utils.AUCCurve.from_str",
"tensorflow.python.ops.confusion_matrix.confusion_matrix",
"tensorflow.python.keras.utils.metrics_utils.result_wrapper",
"tensorflow.python.keras.backend.eval",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.ops.math_ops.maximum",
"tensorflow.python.keras.utils.metrics_utils.weakmethod",
"tensorflow.python.keras.utils.metrics_utils.parse_init_thresholds",
"numpy.zeros",
"tensorflow.python.keras.utils.metrics_utils.update_confusion_matrix_variables",
"tensorflow.python.ops.math_ops.squared_difference",
"tensorflow.python.framework.dtypes.as_dtype",
"tensorflow.python.ops.array_ops.squeeze",
"tensorflow.python.keras.utils.generic_utils.to_list",
"tensorflow.python.ops.weights_broadcast_ops.broadcast_weights",
"tensorflow.python.keras.backend.set_value",
"tensorflow.python.ops.math_ops.argmax",
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.python.ops.math_ops.not_equal",
"tensorflow.python.ops.math_ops.abs",
"tensorflow.python.ops.math_ops.logical_and",
"tensorflow.python.keras.utils.metrics_utils.AUCSummationMethod.from_str",
"tensorflow.python.keras.backend.floatx",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.array_ops.size",
"tensorflow.python.keras.backend._get_session",
"tensorflow.python.ops.math_ops.multiply",
"tensorflow.python.ops.array_ops.diag_part",
"tensorflow.python.keras.backend.dtype"
]
] |
anushkaray/mmsegmentation
|
[
"07cb3b809d59bd72cc11afd6a9ce96215e9aaf96"
] |
[
"mmseg/apis/train.py"
] |
[
"# Copyright (c) OpenMMLab. All rights reserved.\nimport random\nimport warnings\n\nimport mmcv\nimport numpy as np\nimport torch\nimport torch.distributed as dist\nfrom mmcv.parallel import MMDataParallel, MMDistributedDataParallel\nfrom mmcv.runner import HOOKS, build_optimizer, build_runner, get_dist_info\nfrom mmcv.utils import build_from_cfg\n\nfrom mmseg import digit_version\nfrom mmseg.core import DistEvalHook, EvalHook\nfrom mmseg.datasets import build_dataloader, build_dataset\nfrom mmseg.utils import find_latest_checkpoint, get_root_logger\n\n\ndef init_random_seed(seed=None, device='cuda'):\n \"\"\"Initialize random seed.\n\n If the seed is not set, the seed will be automatically randomized,\n and then broadcast to all processes to prevent some potential bugs.\n Args:\n seed (int, Optional): The seed. Default to None.\n device (str): The device where the seed will be put on.\n Default to 'cuda'.\n Returns:\n int: Seed to be used.\n \"\"\"\n if seed is not None:\n return seed\n\n # Make sure all ranks share the same random seed to prevent\n # some potential bugs. Please refer to\n # https://github.com/open-mmlab/mmdetection/issues/6339\n rank, world_size = get_dist_info()\n seed = np.random.randint(2**31)\n if world_size == 1:\n return seed\n\n if rank == 0:\n random_num = torch.tensor(seed, dtype=torch.int32, device=device)\n else:\n random_num = torch.tensor(0, dtype=torch.int32, device=device)\n dist.broadcast(random_num, src=0)\n return random_num.item()\n\n\ndef set_random_seed(seed, deterministic=False):\n \"\"\"Set random seed.\n\n Args:\n seed (int): Seed to be used.\n deterministic (bool): Whether to set the deterministic option for\n CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`\n to True and `torch.backends.cudnn.benchmark` to False.\n Default: False.\n \"\"\"\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n if deterministic:\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n\n\ndef train_segmentor(model,\n dataset,\n cfg,\n distributed=False,\n validate=False,\n timestamp=None,\n meta=None):\n \"\"\"Launch segmentor training.\"\"\"\n logger = get_root_logger(cfg.log_level)\n\n # prepare data loaders\n dataset = dataset if isinstance(dataset, (list, tuple)) else [dataset]\n print(\"Dataset in API train.py \", dataset)\n data_loaders = [\n build_dataloader(\n ds,\n cfg.data.samples_per_gpu,\n cfg.data.workers_per_gpu,\n # cfg.gpus will be ignored if distributed\n len(cfg.gpu_ids),\n dist=distributed,\n seed=cfg.seed,\n drop_last=True) for ds in dataset\n ]\n\n # put model on gpus\n if distributed:\n find_unused_parameters = cfg.get('find_unused_parameters', False)\n # Sets the `find_unused_parameters` parameter in\n # torch.nn.parallel.DistributedDataParallel\n model = MMDistributedDataParallel(\n model.cuda(),\n device_ids=[torch.cuda.current_device()],\n broadcast_buffers=False,\n find_unused_parameters=find_unused_parameters)\n else:\n if not torch.cuda.is_available():\n assert digit_version(mmcv.__version__) >= digit_version('1.4.4'), \\\n 'Please use MMCV >= 1.4.4 for CPU training!'\n model = MMDataParallel(model, device_ids=cfg.gpu_ids)\n # build runner\n optimizer = build_optimizer(model, cfg.optimizer)\n\n if cfg.get('runner') is None:\n cfg.runner = {'type': 'IterBasedRunner', 'max_iters': cfg.total_iters}\n warnings.warn(\n 'config is now expected to have a `runner` section, '\n 'please set `runner` in your config.', UserWarning)\n\n runner = build_runner(\n cfg.runner,\n default_args=dict(\n model=model,\n batch_processor=None,\n optimizer=optimizer,\n work_dir=cfg.work_dir,\n logger=logger,\n meta=meta))\n\n # register hooks\n runner.register_training_hooks(cfg.lr_config, cfg.optimizer_config,\n cfg.checkpoint_config, cfg.log_config,\n cfg.get('momentum_config', None))\n\n # an ugly walkaround to make the .log and .log.json filenames the same\n runner.timestamp = timestamp\n\n # register eval hooks\n if validate:\n val_dataset = build_dataset(cfg.data.val, dict(test_mode=True))\n val_dataloader = build_dataloader(\n val_dataset,\n samples_per_gpu=1,\n workers_per_gpu=cfg.data.workers_per_gpu,\n dist=distributed,\n shuffle=False)\n eval_cfg = cfg.get('evaluation', {})\n eval_cfg['by_epoch'] = cfg.runner['type'] != 'IterBasedRunner'\n eval_hook = DistEvalHook if distributed else EvalHook\n # In this PR (https://github.com/open-mmlab/mmcv/pull/1193), the\n # priority of IterTimerHook has been modified from 'NORMAL' to 'LOW'.\n runner.register_hook(\n eval_hook(val_dataloader, **eval_cfg), priority='LOW')\n\n # user-defined hooks\n if cfg.get('custom_hooks', None):\n custom_hooks = cfg.custom_hooks\n assert isinstance(custom_hooks, list), \\\n f'custom_hooks expect list type, but got {type(custom_hooks)}'\n for hook_cfg in cfg.custom_hooks:\n assert isinstance(hook_cfg, dict), \\\n 'Each item in custom_hooks expects dict type, but got ' \\\n f'{type(hook_cfg)}'\n hook_cfg = hook_cfg.copy()\n priority = hook_cfg.pop('priority', 'NORMAL')\n hook = build_from_cfg(hook_cfg, HOOKS)\n runner.register_hook(hook, priority=priority)\n\n if cfg.resume_from is None and cfg.get('auto_resume'):\n resume_from = find_latest_checkpoint(cfg.work_dir)\n if resume_from is not None:\n cfg.resume_from = resume_from\n if cfg.resume_from:\n runner.resume(cfg.resume_from)\n elif cfg.load_from:\n runner.load_checkpoint(cfg.load_from)\n runner.run(data_loaders, cfg.workflow)\n"
] |
[
[
"torch.cuda.manual_seed_all",
"numpy.random.seed",
"torch.cuda.current_device",
"torch.manual_seed",
"torch.cuda.is_available",
"numpy.random.randint",
"torch.tensor",
"torch.distributed.broadcast"
]
] |
zabop/lightkurve
|
[
"d9c4c40f846aae7cb138e8943950058de3ffd8e7"
] |
[
"lightkurve/interact_bls.py"
] |
[
"\"\"\"This module provides helper functions for the `LightCurve.interact_bls()` feature.\"\"\"\nimport logging\nimport warnings\nimport numpy as np\nfrom astropy.convolution import convolve, Box1DKernel\n\nlog = logging.getLogger(__name__)\n\n# Import the optional AstroPy dependency, or print a friendly error otherwise.\n# BoxLeastSquares was added to `astropy.stats` in AstroPy v3.1 and then\n# moved to `astropy.timeseries` in v3.2, which makes the import below\n# somewhat complicated.\ntry:\n from astropy.timeseries import BoxLeastSquares\nexcept ImportError:\n try:\n from astropy.stats import BoxLeastSquares\n except ImportError:\n pass # we will print an error message in `show_interact_widget` instead\n\n# Import the optional Bokeh dependency, or print a friendly error otherwise.\ntry:\n import bokeh # Import bokeh first so we get an ImportError we can catch\n from bokeh.io import show, output_notebook\n from bokeh.plotting import figure, ColumnDataSource\n from bokeh.models import Selection, Slider, Span, Range1d\n from bokeh.models import Text\n from bokeh.layouts import layout, Spacer\n from bokeh.models.tools import HoverTool\n from bokeh.models.widgets import Button, Paragraph\n from bokeh.events import PanEnd, Reset\nexcept ImportError:\n pass # we will print an error message in `show_interact_widget` instead\n\nfrom .interact import prepare_lightcurve_datasource\nfrom .lightcurve import LightCurve\n\n\n__all__ = ['show_interact_widget']\n\n\ndef prepare_bls_datasource(result, loc):\n \"\"\"Prepare a bls result for bokeh plotting\n\n Parameters\n ----------\n result : BLS.model result\n The BLS model result to use\n loc : int\n Index of the \"best\" period. (Usually the max power)\n\n Returns\n -------\n bls_source : Bokeh.plotting.ColumnDataSource\n Bokeh style source for plotting\n \"\"\"\n preselected = Selection()\n preselected.indices = [loc]\n bls_source = ColumnDataSource(data=dict(\n period=result['period'],\n power=result['power'],\n depth=result['depth'],\n duration=result['duration'],\n transit_time=result['transit_time']),\n selected=preselected)\n return bls_source\n\n\ndef prepare_folded_datasource(folded_lc):\n \"\"\"Prepare a FoldedLightCurve object for bokeh plotting.\n\n Parameters\n ----------\n folded_lc : lightkurve.FoldedLightCurve\n The folded lightcurve\n\n Returns\n -------\n folded_source : Bokeh.plotting.ColumnDataSource\n Bokeh style source for plotting\n \"\"\"\n folded_src = ColumnDataSource(data=dict(\n phase=np.sort(folded_lc.time),\n flux=folded_lc.flux[np.argsort(folded_lc.time)]))\n return folded_src\n\n\n# Helper functions for help text...\n\ndef prepare_lc_help_source(lc):\n data = dict(time=[(np.max(lc.time) - np.min(lc.time)) * 0.98 + np.min(lc.time)],\n flux=[(np.max(lc.flux) - np.min(lc.flux)) * 0.9 + np.min(lc.flux)],\n boxicon=['https://bokeh.pydata.org/en/latest/_images/BoxZoom.png'],\n panicon=['https://bokeh.pydata.org/en/latest/_images/Pan.png'],\n reseticon=['https://bokeh.pydata.org/en/latest/_images/Reset.png'],\n tapicon=['https://bokeh.pydata.org/en/latest/_images/Tap.png'],\n hovericon=['https://bokeh.pydata.org/en/latest/_images/Hover.png'],\n helpme=['?'],\n help=[\"\"\"\n <div style=\"width: 550px;\">\n <div>\n <span style=\"font-size: 12px; font-weight: bold;\">Light Curve</span>\n </div>\n <div>\n <span style=\"font-size: 11px;\"\">This panel shows the full light curve, with the BLS model overlayed in red. The period of the model is the period\n currently selected in the BLS panel [top, left], indicated by the vertical red line. The duration of the transit model is given by the duration slider below..</span>\n <br></br>\n </div>\n <div>\n <span style=\"font-size: 12px; font-weight: bold;\">Bokeh Tools</span>\n </div>\n <div>\n <span style=\"font-size: 11px;\"\">Each of the three panels have Bokeh tools to navigate them.\n You can turn off/on each tool by clicking the icon in the tray below each panel.\n You can zoom in using the Box Zoom Tool, move about the panel using the Pan Tool,\n or reset the panel back to the original view using the Reset Tool. </span>\n <br></br>\n <center>\n <table>\n <tr>\n <td><img src=\"@boxicon\" height=\"20\" width=\"20\"></td><td><span style=\"font-size: 11px;\"\">Box Zoom Tool</span></td>\n </tr>\n <tr>\n <td><img src=\"@panicon\" height=\"20\" width=\"20\"></td><td><span style=\"font-size: 11px;\"\">Pan Tool</span></td>\n </tr>\n <tr>\n <td><img src=\"@reseticon\" height=\"20\" width=\"20\"></td><td><span style=\"font-size: 11px;\"\">Reset Tool</span></td>\n </tr>\n <tr>\n <td><img src=\"@tapicon\" height=\"20\" width=\"20\"></td><td><span style=\"font-size: 11px;\"\">Tap Tool (select periods in BLS Panel only)</span></td>\n </tr>\n <tr>\n <td><img src=\"@hovericon\" height=\"20\" width=\"20\"></td><td><span style=\"font-size: 11px;\"\">Help Messages (click to disable/enable help)</span></td>\n </tr>\n </table>\n </center>\n </div>\n </div>\n \"\"\"])\n return ColumnDataSource(data=data)\n\n\ndef prepare_bls_help_source(bls_source, slider_value):\n data = dict(period=[bls_source.data['period'][int(slider_value*0.95)]],\n power=[(np.max(bls_source.data['power']) - np.min(bls_source.data['power'])) * 0.98 + np.min(bls_source.data['power'])],\n helpme=['?'],\n help=[\"\"\"\n <div style=\"width: 375px;\">\n <div style=\"height: 190px;\">\n </div>\n <div>\n <span style=\"font-size: 12px; font-weight: bold;\">Box Least Squares Periodogram</span>\n </div>\n <div>\n <span style=\"font-size: 11px;\"\">This panel shows the BLS periodogram for\n the light curve shown in the lower panel.\n The current selected period is highlighted by the red line.\n The selected period is the peak period within the range.\n The Folded Light Curve panel [right] will update when a new period\n is selected in the BLS Panel. You can select a new period either by\n using the Box Zoom tool to select a smaller range, or by clicking on the peak you want to select. </span>\n <br></br>\n <span style=\"font-size: 11px;\"\">The panel is set at the resolution\n given by the Resolution Slider [bottom]. This value is the number\n of points in the BLS Periodogram panel.\n Increasing the resolution will make the BLS Periodogram more accurate,\n but slower to render. To increase the resolution for a given peak,\n simply zoom in with the Box Zoom Tool.</span>\n\n </div>\n </div>\n \"\"\"])\n return ColumnDataSource(data=data)\n\n\ndef prepare_f_help_source(f):\n data = dict(phase=[(np.max(f.time) - np.min(f.time)) * 0.98 + np.min(f.time)],\n flux=[(np.max(f.flux) - np.min(f.flux)) * 0.98 + np.min(f.flux)],\n helpme=['?'],\n help=[\"\"\"\n <div style=\"width: 375px;\">\n <div style=\"height: 190px;\">\n </div>\n <div>\n <span style=\"font-size: 12px; font-weight: bold;\">Folded Light Curve</span>\n </div>\n <div>\n <span style=\"font-size: 11px;\"\">This panel shows the folded light curve,\n using the period currently selected in the BLS panel [left], indicated by the red line.\n The transit model is show in red, and duration of the transit model\n is given by the duration slider below. Update the slider to change the duration.\n The period and transit midpoint values of the model are given above this panel.</span>\n <br></br>\n <span style=\"font-size: 11px;\"\">If the folded transit looks like a near miss of\n the true period, try zooming in on the peak in the BLS Periodogram panel [right]\n with the Box Zoom tool. This will increase the resolution of the peak, and provide\n a better period solution. You can also vary the transit duration, for a better fit.\n If the transit model is too shallow, it may be that you have selected a harmonic.\n Look in the BLS Periodogram for a peak at (e.g. 0.25x, 0.5x, 2x, 4x the current period etc).</span>\n </div>\n </div>\n \"\"\"])\n return ColumnDataSource(data=data)\n\n\ndef make_lightcurve_figure_elements(lc, model_lc, lc_source, model_lc_source, help_source):\n \"\"\"Make a figure with a simple light curve scatter and model light curve line.\n\n Parameters\n ----------\n lc : lightkurve.LightCurve\n Light curve to plot\n model_lc : lightkurve.LightCurve\n Model light curve to plot\n lc_source : bokeh.plotting.ColumnDataSource\n Bokeh style source object for plotting light curve\n model_lc_source : bokeh.plotting.ColumnDataSource\n Bokeh style source object for plotting model light curve\n help_source : bokeh.plotting.ColumnDataSource\n Bokeh style source object for rendering help button\n\n Returns\n -------\n fig : bokeh.plotting.figure\n Bokeh figure object\n \"\"\"\n # Make figure\n fig = figure(title='Light Curve', plot_height=300, plot_width=900,\n tools=\"pan,box_zoom,reset\",\n toolbar_location=\"below\",\n border_fill_color=\"#FFFFFF\", active_drag=\"box_zoom\")\n fig.title.offset = -10\n fig.yaxis.axis_label = 'Flux (e/s)'\n if lc.time_format == 'bkjd':\n fig.xaxis.axis_label = 'Time - 2454833 (days)'\n elif lc.time_format == 'btjd':\n fig.xaxis.axis_label = 'Time - 2457000 (days)'\n else:\n fig.xaxis.axis_label = 'Time (days)'\n ylims = [np.nanmin(lc.flux), np.nanmax(lc.flux)]\n fig.y_range = Range1d(start=ylims[0], end=ylims[1])\n\n # Add light curve\n fig.circle('time', 'flux', line_width=1, color='#191919',\n source=lc_source, nonselection_line_color='#191919', size=0.5,\n nonselection_line_alpha=1.0)\n # Add model\n fig.step('time', 'flux', line_width=1, color='firebrick',\n source=model_lc_source, nonselection_line_color='firebrick',\n nonselection_line_alpha=1.0)\n\n # Help button\n question_mark = Text(x=\"time\", y=\"flux\", text=\"helpme\", text_color=\"grey\",\n text_align='center', text_baseline=\"middle\",\n text_font_size='12px', text_font_style='bold',\n text_alpha=0.6)\n fig.add_glyph(help_source, question_mark)\n help = fig.circle('time', 'flux', alpha=0.0, size=15, source=help_source,\n line_width=2, line_color='grey', line_alpha=0.6)\n tooltips = help_source.data['help'][0]\n fig.add_tools(HoverTool(tooltips=tooltips, renderers=[help],\n mode='mouse', point_policy=\"snap_to_data\"))\n return fig\n\n\ndef make_folded_figure_elements(f, f_model_lc, f_source, f_model_lc_source, help_source):\n \"\"\"Make a scatter plot of a FoldedLightCurve.\n\n Parameters\n ----------\n f : lightkurve.LightCurve\n Folded light curve to plot\n f_model_lc : lightkurve.LightCurve\n Model folded light curve to plot\n f_source : bokeh.plotting.ColumnDataSource\n Bokeh style source object for plotting folded light curve\n f_model_lc_source : bokeh.plotting.ColumnDataSource\n Bokeh style source object for plotting model folded light curve\n help_source : bokeh.plotting.ColumnDataSource\n Bokeh style source object for rendering help button\n\n Returns\n -------\n fig : bokeh.plotting.figure\n Bokeh figure object\n \"\"\"\n\n # Build Figure\n fig = figure(title='Folded Light Curve', plot_height=340, plot_width=450,\n tools=\"pan,box_zoom,reset\",\n toolbar_location=\"below\",\n border_fill_color=\"#FFFFFF\", active_drag=\"box_zoom\")\n fig.title.offset = -10\n fig.yaxis.axis_label = 'Flux'\n fig.xaxis.axis_label = 'Phase'\n\n # Scatter point for data\n fig.circle('phase', 'flux', line_width=1, color='#191919',\n source=f_source, nonselection_line_color='#191919',\n nonselection_line_alpha=1.0, size=0.1)\n\n # Line plot for model\n fig.step('phase', 'flux', line_width=3, color='firebrick',\n source=f_model_lc_source, nonselection_line_color='firebrick',\n nonselection_line_alpha=1.0)\n\n # Help button\n question_mark = Text(x=\"phase\", y=\"flux\", text=\"helpme\", text_color=\"grey\",\n text_align='center', text_baseline=\"middle\",\n text_font_size='12px', text_font_style='bold',\n text_alpha=0.6)\n fig.add_glyph(help_source, question_mark)\n help = fig.circle('phase', 'flux', alpha=0.0, size=15, source=help_source,\n line_width=2, line_color='grey', line_alpha=0.6)\n\n tooltips = help_source.data['help'][0]\n fig.add_tools(HoverTool(tooltips=tooltips, renderers=[help],\n mode='mouse', point_policy=\"snap_to_data\"))\n return fig\n\n\ndef make_bls_figure_elements(result, bls_source, help_source):\n \"\"\"Make a line plot of a BLS result.\n\n Parameters\n ----------\n result : BLS.model result\n BLS model result to plot\n bls_source : bokeh.plotting.ColumnDataSource\n Bokeh style source object for plotting BLS source\n help_source : bokeh.plotting.ColumnDataSource\n Bokeh style source object for rendering help button\n\n Returns\n -------\n fig : bokeh.plotting.figure\n Bokeh figure object\n vertical_line : bokeh.models.Span\n Vertical line to highlight current selected period\n \"\"\"\n\n # Build Figure\n fig = figure(title='BLS Periodogram', plot_height=340, plot_width=450,\n tools=\"pan,box_zoom,tap,reset\",\n toolbar_location=\"below\",\n border_fill_color=\"#FFFFFF\", x_axis_type='log', active_drag=\"box_zoom\")\n fig.title.offset = -10\n fig.yaxis.axis_label = 'Power'\n fig.xaxis.axis_label = 'Period [days]'\n fig.y_range = Range1d(start=result.power.min() * 0.95, end=result.power.max() * 1.05)\n fig.x_range = Range1d(start=result.period.min(), end=result.period.max())\n\n # Add circles for the selection of new period. These are always hidden\n circ = fig.circle('period', 'power', source=bls_source, fill_alpha=0., size=6,\n line_color=None, selection_color=\"white\",\n nonselection_fill_alpha=0.0,\n nonselection_fill_color='white',\n nonselection_line_color=None,\n nonselection_line_alpha=0.0,\n fill_color=None, hover_fill_color=\"white\",\n hover_alpha=0., hover_line_color=\"white\")\n\n # Add line for the BLS power\n fig.line('period', 'power', line_width=1, color='#191919',\n source=bls_source, nonselection_line_color='#191919',\n nonselection_line_alpha=1.0)\n\n # Vertical line to indicate the current period\n vertical_line = Span(location=0, dimension='height',\n line_color='firebrick', line_width=3, line_alpha=0.5)\n fig.add_layout(vertical_line)\n\n # Help button\n question_mark = Text(x=\"period\", y=\"power\", text=\"helpme\", text_color=\"grey\",\n text_align='center', text_baseline=\"middle\",\n text_font_size='12px', text_font_style='bold',\n text_alpha=0.6)\n fig.add_glyph(help_source, question_mark)\n help = fig.circle('period', 'power', alpha=0.0, size=15, source=help_source,\n line_width=2, line_color='grey', line_alpha=0.6)\n tooltips = help_source.data['help'][0]\n fig.add_tools(HoverTool(tooltips=tooltips, renderers=[help],\n mode='mouse', point_policy=\"snap_to_data\"))\n\n return fig, vertical_line\n\n\ndef show_interact_widget(lc, notebook_url='localhost:8888', minimum_period=None,\n maximum_period=None, resolution=2000):\n \"\"\"Show the BLS interact widget.\n\n Parameters\n ----------\n notebook_url: str\n Location of the Jupyter notebook page (default: \"localhost:8888\")\n When showing Bokeh applications, the Bokeh server must be\n explicitly configured to allow connections originating from\n different URLs. This parameter defaults to the standard notebook\n host and port. If you are running on a different location, you\n will need to supply this value for the application to display\n properly. If no protocol is supplied in the URL, e.g. if it is\n of the form \"localhost:8888\", then \"http\" will be used.\n minimum_period : float or None\n Minimum period to assess the BLS to. If None, default value of 0.3 days\n will be used.\n maximum_period : float or None\n Maximum period to evaluate the BLS to. If None, the time coverage of the\n lightcurve / 4 will be used.\n resolution : int\n Number of points to use in the BLS panel. Lower this value to have a faster\n but less accurate compute time. You can also vary this value using the\n Resolution Slider.\n \"\"\"\n try:\n import bokeh\n if bokeh.__version__[0] == '0':\n warnings.warn(\"interact_bls() requires Bokeh version 1.0 or later\", LightkurveWarning)\n except ImportError:\n log.error(\"The interact_bls() tool requires the `bokeh` package; \"\n \"you can install bokeh using e.g. `conda install bokeh`.\")\n return None\n\n try:\n from astropy.timeseries import BoxLeastSquares\n except ImportError:\n try:\n from astropy.stats import BoxLeastSquares\n except ImportError:\n log.error(\"The `interact_bls()` tool requires AstroPy v3.1 or later.\")\n\n def _create_interact_ui(doc, minp=minimum_period, maxp=maximum_period, resolution=resolution):\n \"\"\"Create BLS interact user interface.\"\"\"\n if minp is None:\n minp = 0.3\n if maxp is None:\n maxp = (lc.time[-1] - lc.time[0])/2\n\n time_format = ''\n if lc.time_format == 'bkjd':\n time_format = ' - 2454833 days'\n if lc.time_format == 'btjd':\n time_format = ' - 2457000 days'\n\n # Some sliders\n duration_slider = Slider(start=0.01,\n end=0.5,\n value=0.05,\n step=0.01,\n title=\"Duration [Days]\",\n width=400)\n\n npoints_slider = Slider(start=500,\n end=10000,\n value=resolution,\n step=100,\n title=\"BLS Resolution\",\n width=400)\n\n # Set up the period values, BLS model and best period\n period_values = np.logspace(np.log10(minp), np.log10(maxp), npoints_slider.value)\n period_values = period_values[(period_values > duration_slider.value) &\n (period_values < maxp)]\n model = BoxLeastSquares(lc.time, lc.flux)\n result = model.power(period_values, duration_slider.value)\n loc = np.argmax(result.power)\n best_period = result.period[loc]\n best_t0 = result.transit_time[loc]\n\n # Some Buttons\n double_button = Button(label=\"Double Period\", button_type=\"danger\", width=100)\n half_button = Button(label=\"Half Period\", button_type=\"danger\", width=100)\n text_output = Paragraph(text=\"Period: {} days, T0: {}{}\".format(\n np.round(best_period, 7),\n np.round(best_t0, 7), time_format),\n width=350, height=40)\n\n # Set up BLS source\n bls_source = prepare_bls_datasource(result, loc)\n bls_help_source = prepare_bls_help_source(bls_source, npoints_slider.value)\n\n # Set up the model LC\n mf = model.model(lc.time, best_period, duration_slider.value, best_t0)\n mf /= np.median(mf)\n mask = ~(convolve(np.asarray(mf == np.median(mf)), Box1DKernel(2)) > 0.9)\n model_lc = LightCurve(lc.time[mask], mf[mask])\n model_lc = model_lc.append(LightCurve([(lc.time[0] - best_t0) + best_period/2], [1]))\n model_lc = model_lc.append(LightCurve([(lc.time[0] - best_t0) + 3*best_period/2], [1]))\n\n model_lc_source = ColumnDataSource(data=dict(\n time=np.sort(model_lc.time),\n flux=model_lc.flux[np.argsort(model_lc.time)]))\n\n # Set up the LC\n nb = int(np.ceil(len(lc.flux)/5000))\n lc_source = prepare_lightcurve_datasource(lc[::nb])\n lc_help_source = prepare_lc_help_source(lc)\n\n # Set up folded LC\n nb = int(np.ceil(len(lc.flux)/10000))\n f = lc.fold(best_period, best_t0)\n f_source = prepare_folded_datasource(f[::nb])\n f_help_source = prepare_f_help_source(f)\n\n f_model_lc = model_lc.fold(best_period, best_t0)\n f_model_lc = LightCurve([-0.5], [1]).append(f_model_lc)\n f_model_lc = f_model_lc.append(LightCurve([0.5], [1]))\n\n f_model_lc_source = ColumnDataSource(data=dict(\n phase=f_model_lc.time,\n flux=f_model_lc.flux))\n\n def _update_light_curve_plot(event):\n \"\"\"If we zoom in on LC plot, update the binning.\"\"\"\n mint, maxt = fig_lc.x_range.start, fig_lc.x_range.end\n inwindow = (lc.time > mint) & (lc.time < maxt)\n nb = int(np.ceil(inwindow.sum()/5000))\n temp_lc = lc[inwindow]\n lc_source.data = {'time': temp_lc.time[::nb],\n 'flux': temp_lc.flux[::nb]}\n\n def _update_folded_plot(event):\n loc = np.argmax(bls_source.data['power'])\n best_period = bls_source.data['period'][loc]\n best_t0 = bls_source.data['transit_time'][loc]\n # Otherwise, we can just update the best_period index\n minphase, maxphase = fig_folded.x_range.start, fig_folded.x_range.end\n f = lc.fold(best_period, best_t0)\n inwindow = (f.time > minphase) & (f.time < maxphase)\n nb = int(np.ceil(inwindow.sum()/10000))\n f_source.data = {'phase': f[inwindow].time[::nb],\n 'flux': f[inwindow].flux[::nb]}\n\n # Function to update the widget\n def _update_params(all=False, best_period=None, best_t0=None):\n if all:\n # If we're updating everything, recalculate the BLS model\n minp, maxp = fig_bls.x_range.start, fig_bls.x_range.end\n period_values = np.logspace(np.log10(minp), np.log10(maxp), npoints_slider.value)\n ok = (period_values > duration_slider.value) & (period_values < maxp)\n if ok.sum() == 0:\n return\n period_values = period_values[ok]\n result = model.power(period_values, duration_slider.value)\n ok = np.isfinite(result['power']) & np.isfinite(result['duration']) &\\\n np.isfinite(result['transit_time']) & np.isfinite(result['period'])\n bls_source.data = dict(\n period=result['period'][ok],\n power=result['power'][ok],\n duration=result['duration'][ok],\n transit_time=result['transit_time'][ok])\n loc = np.nanargmax(bls_source.data['power'])\n best_period = bls_source.data['period'][loc]\n best_t0 = bls_source.data['transit_time'][loc]\n\n minpow, maxpow = bls_source.data['power'].min()*0.95, bls_source.data['power'].max()*1.05\n fig_bls.y_range.start = minpow\n fig_bls.y_range.end = maxpow\n\n # Otherwise, we can just update the best_period index\n minphase, maxphase = fig_folded.x_range.start, fig_folded.x_range.end\n f = lc.fold(best_period, best_t0)\n inwindow = (f.time > minphase) & (f.time < maxphase)\n nb = int(np.ceil(inwindow.sum()/10000))\n f_source.data = {'phase': f[inwindow].time[::nb],\n 'flux': f[inwindow].flux[::nb]}\n\n mf = model.model(lc.time, best_period, duration_slider.value, best_t0)\n mf /= np.median(mf)\n mask = ~(convolve(np.asarray(mf == np.median(mf)), Box1DKernel(2)) > 0.9)\n model_lc = LightCurve(lc.time[mask], mf[mask])\n\n model_lc_source.data = {'time': np.sort(model_lc.time),\n 'flux': model_lc.flux[np.argsort(model_lc.time)]}\n\n f_model_lc = model_lc.fold(best_period, best_t0)\n f_model_lc = LightCurve([-0.5], [1]).append(f_model_lc)\n f_model_lc = f_model_lc.append(LightCurve([0.5], [1]))\n\n f_model_lc_source.data = {'phase': f_model_lc.time,\n 'flux': f_model_lc.flux}\n\n vertical_line.update(location=best_period)\n fig_folded.title.text = 'Period: {} days \\t T0: {}{}'.format(\n np.round(best_period, 7),\n np.round(best_t0, 7), time_format)\n text_output.text = \"Period: {} days, \\t T0: {}{}\".format(\n np.round(best_period, 7),\n np.round(best_t0, 7), time_format)\n\n # Callbacks\n def _update_upon_period_selection(attr, old, new):\n \"\"\"When we select a period we should just update a few things, but we should not recalculate model\n \"\"\"\n if len(new) > 0:\n new = new[0]\n best_period = bls_source.data['period'][new]\n best_t0 = bls_source.data['transit_time'][new]\n _update_params(best_period=best_period, best_t0=best_t0)\n\n def _update_model_slider(attr, old, new):\n \"\"\"If the duration slider is updated, then update the whole model set.\"\"\"\n _update_params(all=True)\n\n def _update_model_slider_EVENT(event):\n \"\"\"If we update the duration slider, we should update the whole model set.\n This is the same as the _update_model_slider but it has a different call signature...\n \"\"\"\n _update_params(all=True)\n\n def _double_period_event():\n fig_bls.x_range.start *= 2\n fig_bls.x_range.end *= 2\n _update_params(all=True)\n\n def _half_period_event():\n fig_bls.x_range.start /= 2\n fig_bls.x_range.end /= 2\n _update_params(all=True)\n\n # Help Hover Call Backs\n def _update_folded_plot_help_reset(event):\n f_help_source.data['phase'] = [(np.max(f.time) - np.min(f.time)) * 0.98 + np.min(f.time)]\n f_help_source.data['flux'] = [(np.max(f.flux) - np.min(f.flux)) * 0.98 + np.min(f.flux)]\n\n def _update_folded_plot_help(event):\n f_help_source.data['phase'] = [(fig_folded.x_range.end - fig_folded.x_range.start) * 0.95 + fig_folded.x_range.start]\n f_help_source.data['flux'] = [(fig_folded.y_range.end - fig_folded.y_range.start) * 0.95 + fig_folded.y_range.start]\n\n def _update_lc_plot_help_reset(event):\n lc_help_source.data['time'] = [(np.max(lc.time) - np.min(lc.time)) * 0.98 + np.min(lc.time)]\n lc_help_source.data['flux'] = [(np.max(lc.flux) - np.min(lc.flux)) * 0.9 + np.min(lc.flux)]\n\n def _update_lc_plot_help(event):\n lc_help_source.data['time'] = [(fig_lc.x_range.end - fig_lc.x_range.start) * 0.95 + fig_lc.x_range.start]\n lc_help_source.data['flux'] = [(fig_lc.y_range.end - fig_lc.y_range.start) * 0.9 + fig_lc.y_range.start]\n\n def _update_bls_plot_help_event(event):\n bls_help_source.data['period'] = [bls_source.data['period'][int(npoints_slider.value*0.95)]]\n bls_help_source.data['power'] = [(np.max(bls_source.data['power']) - np.min(bls_source.data['power'])) * 0.98\n + np.min(bls_source.data['power'])]\n\n def _update_bls_plot_help(attr, old, new):\n bls_help_source.data['period'] = [bls_source.data['period'][int(npoints_slider.value*0.95)]]\n bls_help_source.data['power'] = [(np.max(bls_source.data['power']) - np.min(bls_source.data['power'])) * 0.98\n + np.min(bls_source.data['power'])]\n\n # Create all the figures.\n fig_folded = make_folded_figure_elements(f, f_model_lc, f_source, f_model_lc_source, f_help_source)\n fig_folded.title.text = 'Period: {} days \\t T0: {}{}'.format(np.round(best_period, 7), np.round(best_t0, 5), time_format)\n fig_bls, vertical_line = make_bls_figure_elements(result, bls_source, bls_help_source)\n fig_lc = make_lightcurve_figure_elements(lc, model_lc, lc_source, model_lc_source, lc_help_source)\n\n # Map changes\n\n # If we click a new period, update\n bls_source.selected.on_change('indices', _update_upon_period_selection)\n\n # If we change the duration, update everything, including help button for BLS\n duration_slider.on_change('value', _update_model_slider)\n duration_slider.on_change('value', _update_bls_plot_help)\n\n # If we increase resolution, update everything\n npoints_slider.on_change('value', _update_model_slider)\n\n # Make sure the vertical line always goes to the best period.\n vertical_line.update(location=best_period)\n\n # If we pan in the BLS panel, update everything\n fig_bls.on_event(PanEnd, _update_model_slider_EVENT)\n fig_bls.on_event(Reset, _update_model_slider_EVENT)\n\n # If we pan in the LC panel, rebin the points\n fig_lc.on_event(PanEnd, _update_light_curve_plot)\n fig_lc.on_event(Reset, _update_light_curve_plot)\n\n # If we pan in the Folded panel, rebin the points\n fig_folded.on_event(PanEnd, _update_folded_plot)\n fig_folded.on_event(Reset, _update_folded_plot)\n\n # Deal with help button\n fig_bls.on_event(PanEnd, _update_bls_plot_help_event)\n fig_bls.on_event(Reset, _update_bls_plot_help_event)\n fig_folded.on_event(PanEnd, _update_folded_plot_help)\n fig_folded.on_event(Reset, _update_folded_plot_help_reset)\n fig_lc.on_event(PanEnd, _update_lc_plot_help)\n fig_lc.on_event(Reset, _update_lc_plot_help_reset)\n\n # Buttons\n double_button.on_click(_double_period_event)\n half_button.on_click(_half_period_event)\n\n # Layout the widget\n doc.add_root(layout([\n [fig_bls, fig_folded],\n fig_lc,\n [Spacer(width=70), duration_slider, Spacer(width=50), npoints_slider],\n [Spacer(width=70), double_button, Spacer(width=70), half_button, Spacer(width=300), text_output]\n ]))\n\n output_notebook(verbose=False, hide_banner=True)\n return show(_create_interact_ui, notebook_url=notebook_url)\n"
] |
[
[
"numpy.max",
"numpy.median",
"numpy.round",
"numpy.min",
"numpy.nanmin",
"numpy.nanargmax",
"numpy.argmax",
"numpy.sort",
"numpy.isfinite",
"numpy.argsort",
"numpy.log10",
"numpy.nanmax"
]
] |
RedHeadM/CCT
|
[
"bece91e7d2f84de96b0975aed12ef64bff833565"
] |
[
"base/base_dataset.py"
] |
[
"import random, math\nimport numpy as np\nimport cv2\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset\nfrom PIL import Image\nfrom torchvision import transforms\nfrom scipy import ndimage\nfrom math import ceil\n\nclass BaseDataSet(Dataset):\n def __init__(self, data_dir, split, mean, std, ignore_index, base_size=None, augment=True, val=False,\n jitter=False, use_weak_lables=False, weak_labels_output=None, crop_size=None, scale=False, flip=False, rotate=False,\n blur=False, return_id=False, n_labeled_examples=None,*args,**kwargs):\n\n self.root = data_dir\n self.split = split\n self.mean = mean\n self.std = std\n self.augment = augment\n self.crop_size = crop_size\n self.jitter = jitter\n self.image_padding = (np.array(mean)*255.).tolist()\n self.ignore_index = ignore_index\n self.return_id = return_id\n self.n_labeled_examples = n_labeled_examples\n self.val = val\n\n self.use_weak_lables = use_weak_lables\n self.weak_labels_output = weak_labels_output\n\n if self.augment:\n self.base_size = base_size\n self.scale = scale\n self.flip = flip\n self.rotate = rotate\n self.blur = blur\n\n self.jitter_tf = transforms.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1)\n self.to_tensor = transforms.ToTensor()\n self.normalize = transforms.Normalize(mean, std)\n\n self.files = []\n self._set_files()\n\n cv2.setNumThreads(0)\n\n def _set_files(self):\n raise NotImplementedError\n\n def _load_data(self, index):\n raise NotImplementedError\n\n def _rotate(self, image, label):\n # Rotate the image with an angle between -10 and 10\n h, w, _ = image.shape\n angle = random.randint(-10, 10)\n center = (w / 2, h / 2)\n rot_matrix = cv2.getRotationMatrix2D(center, angle, 1.0)\n image = cv2.warpAffine(image, rot_matrix, (w, h), flags=cv2.INTER_CUBIC)#, borderMode=cv2.BORDER_REFLECT)\n label = cv2.warpAffine(label, rot_matrix, (w, h), flags=cv2.INTER_NEAREST)#, borderMode=cv2.BORDER_REFLECT)\n return image, label\n\n def _crop(self, image, label):\n # Padding to return the correct crop size\n if (isinstance(self.crop_size, list) or isinstance(self.crop_size, tuple)) and len(self.crop_size) == 2:\n crop_h, crop_w = self.crop_size\n elif isinstance(self.crop_size, int):\n crop_h, crop_w = self.crop_size, self.crop_size\n else:\n raise ValueError\n\n h, w, _ = image.shape\n pad_h = max(crop_h - h, 0)\n pad_w = max(crop_w - w, 0)\n pad_kwargs = {\n \"top\": 0,\n \"bottom\": pad_h,\n \"left\": 0,\n \"right\": pad_w,\n \"borderType\": cv2.BORDER_CONSTANT,}\n if pad_h > 0 or pad_w > 0:\n image = cv2.copyMakeBorder(image, value=self.image_padding, **pad_kwargs)\n label = cv2.copyMakeBorder(label, value=self.ignore_index, **pad_kwargs)\n\n # Cropping\n h, w, _ = image.shape\n start_h = random.randint(0, h - crop_h)\n start_w = random.randint(0, w - crop_w)\n end_h = start_h + crop_h\n end_w = start_w + crop_w\n image = image[start_h:end_h, start_w:end_w]\n label = label[start_h:end_h, start_w:end_w]\n return image, label\n\n def _blur(self, image, label):\n # Gaussian Blud (sigma between 0 and 1.5)\n sigma = random.random() * 1.5\n ksize = int(3.3 * sigma)\n ksize = ksize + 1 if ksize % 2 == 0 else ksize\n image = cv2.GaussianBlur(image, (ksize, ksize), sigmaX=sigma, sigmaY=sigma, borderType=cv2.BORDER_REFLECT_101)\n return image, label\n\n def _flip(self, image, label):\n # Random H flip\n if random.random() > 0.5:\n image = np.fliplr(image).copy()\n label = np.fliplr(label).copy()\n return image, label\n\n def _resize(self, image, label, bigger_side_to_base_size=True):\n if isinstance(self.base_size, int):\n h, w, _ = image.shape\n if self.scale:\n longside = random.randint(int(self.base_size*0.5), int(self.base_size*2.0))\n #longside = random.randint(int(self.base_size*0.5), int(self.base_size*1))\n else:\n longside = self.base_size\n\n if bigger_side_to_base_size:\n h, w = (longside, int(1.0 * longside * w / h + 0.5)) if h > w else (int(1.0 * longside * h / w + 0.5), longside)\n else:\n h, w = (longside, int(1.0 * longside * w / h + 0.5)) if h < w else (int(1.0 * longside * h / w + 0.5), longside)\n image = np.asarray(Image.fromarray(np.uint8(image)).resize((w, h), Image.BICUBIC))\n label = cv2.resize(label, (w, h), interpolation=cv2.INTER_NEAREST)\n return image, label\n\n elif (isinstance(self.base_size, list) or isinstance(self.base_size, tuple)) and len(self.base_size) == 2:\n h, w, _ = image.shape\n if self.scale:\n scale = random.random() * 1.5 + 0.5 # Scaling between [0.5, 2]\n h, w = int(self.base_size[0] * scale), int(self.base_size[1] * scale)\n else:\n h, w = self.base_size\n image = np.asarray(Image.fromarray(np.uint8(image)).resize((w, h), Image.BICUBIC))\n label = cv2.resize(label, (w, h), interpolation=cv2.INTER_NEAREST)\n return image, label\n\n else:\n raise ValueError\n\n def _val_augmentation(self, image, label):\n if self.base_size is not None:\n image, label = self._resize(image, label)\n image = self.normalize(self.to_tensor(Image.fromarray(np.uint8(image))))\n return image, label\n\n image = self.normalize(self.to_tensor(Image.fromarray(np.uint8(image))))\n return image, label\n\n def _augmentation(self, image, label):\n h, w, _ = image.shape\n\n if self.base_size is not None:\n image, label = self._resize(image, label)\n\n if self.crop_size is not None:\n image, label = self._crop(image, label)\n\n if self.flip:\n image, label = self._flip(image, label)\n\n image = Image.fromarray(np.uint8(image))\n image = self.jitter_tf(image) if self.jitter else image\n\n return self.normalize(self.to_tensor(image)), label\n\n def __len__(self):\n return len(self.files)\n\n def __getitem__(self, index):\n image, label, image_id = self._load_data(index)\n if self.val:\n image, label = self._val_augmentation(image, label)\n elif self.augment:\n image, label = self._augmentation(image, label)\n\n label = torch.from_numpy(np.array(label, dtype=np.int32)).long()\n return image, label\n\n def __repr__(self):\n fmt_str = \"Dataset: \" + self.__class__.__name__ + \"\\n\"\n fmt_str += \" # data: {}\\n\".format(self.__len__())\n fmt_str += \" Split: {}\\n\".format(self.split)\n fmt_str += \" Root: {}\".format(self.root)\n return fmt_str\n\n"
] |
[
[
"numpy.array",
"numpy.uint8",
"numpy.fliplr"
]
] |
VidushB/Housing-Price-Prediction-with-feature-selection-and-linear-regression
|
[
"929dccf63d760e5ace3b74ed564014d80b674719"
] |
[
"model.py"
] |
[
"from sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nmodel = LinearRegression()\nX=df_train.drop(\"SalePrice\",axis=1)\ny = df_train['SalePrice'].reset_index(drop = True)\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.33, random_state=42)\nmodel.fit(X_train,y_train)\nr_sq=model.score(X_train,y_train)\nprint(\"Co-efficient of determination is : \",r_sq)\n\ny_predict=model.predict(X_val)\nfrom sklearn import metrics\nprint('Mean Squared Error:', metrics.mean_squared_error(y_val, y_predict)) \n"
] |
[
[
"sklearn.model_selection.train_test_split",
"sklearn.metrics.mean_squared_error",
"sklearn.linear_model.LinearRegression"
]
] |
robagar/teasneeze
|
[
"cff6a01de992162f69590decd935dedbcd2145c7"
] |
[
"test/digits/collect_data.py"
] |
[
"import json\nfrom itertools import count\nimport numpy as np\nfrom sklearn.datasets import load_digits\n\ncounters = []\nfor i in range(10):\n counters.append(count())\n\ndef make_entry(td):\n t,d = td\n i = next(counters[t])\n return {\n 'classification': str(t),\n 'image_path': 'images/{0}/{0}-{1}.png'.format(t,i),\n 'data_vector': list(d)\n }\n\ndigits = load_digits()\nout = {\n 'name': 'digits',\n 'data_points': list(map(make_entry, zip(digits.target, digits.data)))\n} \n\nwith open('digits.json', 'w') as f:\n json.dump(out, f, indent=4)\n\n "
] |
[
[
"sklearn.datasets.load_digits"
]
] |
woffett/pytorch-image-models
|
[
"d6ac5bbc481271efecee8bc8756caa864a253fdd"
] |
[
"train.py"
] |
[
"\nimport argparse\nimport time\nimport logging\nfrom datetime import datetime\n\ntry:\n from apex import amp\n from apex.parallel import DistributedDataParallel as DDP\n from apex.parallel import convert_syncbn_model\n has_apex = True\nexcept ImportError:\n from torch.nn.parallel import DistributedDataParallel as DDP\n has_apex = False\n\nfrom timm.data import Dataset, create_loader, resolve_data_config, FastCollateMixup, mixup_target\nfrom timm.models import create_model, resume_checkpoint\nfrom timm.utils import *\nfrom timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy\nfrom timm.optim import create_optimizer\nfrom timm.scheduler import create_scheduler\n\nimport torch\nimport torch.nn as nn\nimport torchvision.utils\n\ntorch.backends.cudnn.benchmark = True\n\nparser = argparse.ArgumentParser(description='Training')\n# Dataset / Model parameters\nparser.add_argument('data', metavar='DIR',\n help='path to dataset')\nparser.add_argument('--model', default='resnet101', type=str, metavar='MODEL',\n help='Name of model to train (default: \"countception\"')\nparser.add_argument('--pretrained', action='store_true', default=False,\n help='Start with pretrained version of specified network (if avail)')\nparser.add_argument('--initial-checkpoint', default='', type=str, metavar='PATH',\n help='Initialize model from this checkpoint (default: none)')\nparser.add_argument('--resume', default='', type=str, metavar='PATH',\n help='Resume full model and optimizer state from checkpoint (default: none)')\nparser.add_argument('--num-classes', type=int, default=1000, metavar='N',\n help='number of label classes (default: 1000)')\nparser.add_argument('--gp', default='avg', type=str, metavar='POOL',\n help='Type of global pool, \"avg\", \"max\", \"avgmax\", \"avgmaxc\" (default: \"avg\")')\nparser.add_argument('--img-size', type=int, default=None, metavar='N',\n help='Image patch size (default: None => model default)')\nparser.add_argument('--mean', type=float, nargs='+', default=None, metavar='MEAN',\n help='Override mean pixel value of dataset')\nparser.add_argument('--std', type=float, nargs='+', default=None, metavar='STD',\n help='Override std deviation of of dataset')\nparser.add_argument('--interpolation', default='', type=str, metavar='NAME',\n help='Image resize interpolation type (overrides model)')\nparser.add_argument('-b', '--batch-size', type=int, default=32, metavar='N',\n help='input batch size for training (default: 32)')\nparser.add_argument('--drop', type=float, default=0.0, metavar='DROP',\n help='Dropout rate (default: 0.)')\n# Optimizer parameters\nparser.add_argument('--opt', default='sgd', type=str, metavar='OPTIMIZER',\n help='Optimizer (default: \"sgd\"')\nparser.add_argument('--opt-eps', default=1e-8, type=float, metavar='EPSILON',\n help='Optimizer Epsilon (default: 1e-8)')\nparser.add_argument('--momentum', type=float, default=0.9, metavar='M',\n help='SGD momentum (default: 0.9)')\nparser.add_argument('--weight-decay', type=float, default=0.0001,\n help='weight decay (default: 0.0001)')\n# Learning rate schedule parameters\nparser.add_argument('--sched', default='step', type=str, metavar='SCHEDULER',\n help='LR scheduler (default: \"step\"')\nparser.add_argument('--lr', type=float, default=0.01, metavar='LR',\n help='learning rate (default: 0.01)')\nparser.add_argument('--warmup-lr', type=float, default=0.0001, metavar='LR',\n help='warmup learning rate (default: 0.0001)')\nparser.add_argument('--epochs', type=int, default=200, metavar='N',\n help='number of epochs to train (default: 2)')\nparser.add_argument('--start-epoch', default=None, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\nparser.add_argument('--decay-epochs', type=int, default=30, metavar='N',\n help='epoch interval to decay LR')\nparser.add_argument('--warmup-epochs', type=int, default=3, metavar='N',\n help='epochs to warmup LR, if scheduler supports')\nparser.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE',\n help='LR decay rate (default: 0.1)')\n# Augmentation parameters\nparser.add_argument('--color_jitter', type=float, default=0.4, metavar='PCT',\n help='Color jitter factor (default: 0.4)')\nparser.add_argument('--reprob', type=float, default=0., metavar='PCT',\n help='Random erase prob (default: 0.)')\nparser.add_argument('--remode', type=str, default='const',\n help='Random erase mode (default: \"const\")')\nparser.add_argument('--mixup', type=float, default=0.0,\n help='mixup alpha, mixup enabled if > 0. (default: 0.)')\nparser.add_argument('--mixup-off-epoch', default=0, type=int, metavar='N',\n help='turn off mixup after this epoch, disabled if 0 (default: 0)')\nparser.add_argument('--smoothing', type=float, default=0.1,\n help='label smoothing (default: 0.1)')\n# Batch norm parameters (only works with gen_efficientnet based models currently)\nparser.add_argument('--bn-tf', action='store_true', default=False,\n help='Use Tensorflow BatchNorm defaults for models that support it (default: False)')\nparser.add_argument('--bn-momentum', type=float, default=None,\n help='BatchNorm momentum override (if not None)')\nparser.add_argument('--bn-eps', type=float, default=None,\n help='BatchNorm epsilon override (if not None)')\n# Model Exponential Moving Average\nparser.add_argument('--model-ema', action='store_true', default=False,\n help='Enable tracking moving average of model weights')\nparser.add_argument('--model-ema-force-cpu', action='store_true', default=False,\n help='Force ema to be tracked on CPU, rank=0 node only. Disables EMA validation.')\nparser.add_argument('--model-ema-decay', type=float, default=0.9998,\n help='decay factor for model weights moving average (default: 0.9998)')\n# Misc\nparser.add_argument('--seed', type=int, default=42, metavar='S',\n help='random seed (default: 42)')\nparser.add_argument('--log-interval', type=int, default=50, metavar='N',\n help='how many batches to wait before logging training status')\nparser.add_argument('--recovery-interval', type=int, default=0, metavar='N',\n help='how many batches to wait before writing recovery checkpoint')\nparser.add_argument('-j', '--workers', type=int, default=4, metavar='N',\n help='how many training processes to use (default: 1)')\nparser.add_argument('--num-gpu', type=int, default=1,\n help='Number of GPUS to use')\nparser.add_argument('--save-images', action='store_true', default=False,\n help='save images of input bathes every log interval for debugging')\nparser.add_argument('--amp', action='store_true', default=False,\n help='use NVIDIA amp for mixed precision training')\nparser.add_argument('--sync-bn', action='store_true',\n help='enabling apex sync BN.')\nparser.add_argument('--no-prefetcher', action='store_true', default=False,\n help='disable fast prefetcher')\nparser.add_argument('--output', default='', type=str, metavar='PATH',\n help='path to output folder (default: none, current dir)')\nparser.add_argument('--eval-metric', default='prec1', type=str, metavar='EVAL_METRIC',\n help='Best metric (default: \"prec1\"')\nparser.add_argument('--tta', type=int, default=0, metavar='N',\n help='Test/inference time augmentation (oversampling) factor. 0=None (default: 0)')\nparser.add_argument(\"--local_rank\", default=0, type=int)\n\n\ndef main():\n setup_default_logging()\n args = parser.parse_args()\n args.prefetcher = not args.no_prefetcher\n args.distributed = False\n if 'WORLD_SIZE' in os.environ:\n args.distributed = int(os.environ['WORLD_SIZE']) > 1\n if args.distributed and args.num_gpu > 1:\n logging.warning('Using more than one GPU per process in distributed mode is not allowed. Setting num_gpu to 1.')\n args.num_gpu = 1\n\n args.device = 'cuda:0'\n args.world_size = 1\n args.rank = 0 # global rank\n if args.distributed:\n args.num_gpu = 1\n args.device = 'cuda:%d' % args.local_rank\n torch.cuda.set_device(args.local_rank)\n torch.distributed.init_process_group(backend='nccl', init_method='env://')\n args.world_size = torch.distributed.get_world_size()\n args.rank = torch.distributed.get_rank()\n assert args.rank >= 0\n\n if args.distributed:\n logging.info('Training in distributed mode with multiple processes, 1 GPU per process. Process %d, total %d.'\n % (args.rank, args.world_size))\n else:\n logging.info('Training with a single process on %d GPUs.' % args.num_gpu)\n\n torch.manual_seed(args.seed + args.rank)\n\n model = create_model(\n args.model,\n pretrained=args.pretrained,\n num_classes=args.num_classes,\n drop_rate=args.drop,\n global_pool=args.gp,\n bn_tf=args.bn_tf,\n bn_momentum=args.bn_momentum,\n bn_eps=args.bn_eps,\n checkpoint_path=args.initial_checkpoint)\n\n if args.local_rank == 0:\n logging.info('Model %s created, param count: %d' %\n (args.model, sum([m.numel() for m in model.parameters()])))\n\n data_config = resolve_data_config(vars(args), model=model, verbose=args.local_rank == 0)\n\n # optionally resume from a checkpoint\n optimizer_state = None\n resume_epoch = None\n if args.resume:\n optimizer_state, resume_epoch = resume_checkpoint(model, args.resume)\n\n if args.num_gpu > 1:\n if args.amp:\n logging.warning(\n 'AMP does not work well with nn.DataParallel, disabling. Use distributed mode for multi-GPU AMP.')\n args.amp = False\n model = nn.DataParallel(model, device_ids=list(range(args.num_gpu))).cuda()\n else:\n model.cuda()\n\n optimizer = create_optimizer(args, model)\n if optimizer_state is not None:\n optimizer.load_state_dict(optimizer_state)\n\n use_amp = False\n if has_apex and args.amp:\n model, optimizer = amp.initialize(model, optimizer, opt_level='O1')\n use_amp = True\n if args.local_rank == 0:\n logging.info('NVIDIA APEX {}. AMP {}.'.format(\n 'installed' if has_apex else 'not installed', 'on' if use_amp else 'off'))\n\n model_ema = None\n if args.model_ema:\n # Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper\n model_ema = ModelEma(\n model,\n decay=args.model_ema_decay,\n device='cpu' if args.model_ema_force_cpu else '',\n resume=args.resume)\n\n if args.distributed:\n if args.sync_bn:\n try:\n if has_apex:\n model = convert_syncbn_model(model)\n else:\n model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)\n if args.local_rank == 0:\n logging.info('Converted model to use Synchronized BatchNorm.')\n except Exception as e:\n logging.error('Failed to enable Synchronized BatchNorm. Install Apex or Torch >= 1.1')\n if has_apex:\n model = DDP(model, delay_allreduce=True)\n else:\n if args.local_rank == 0:\n logging.info(\"Using torch DistributedDataParallel. Install NVIDIA Apex for Apex DDP.\")\n model = DDP(model, device_ids=[args.local_rank]) # can use device str in Torch >= 1.1\n # NOTE: EMA model does not need to be wrapped by DDP\n\n lr_scheduler, num_epochs = create_scheduler(args, optimizer)\n start_epoch = 0\n if args.start_epoch is not None:\n # a specified start_epoch will always override the resume epoch\n start_epoch = args.start_epoch\n elif resume_epoch is not None:\n start_epoch = resume_epoch\n if start_epoch > 0:\n lr_scheduler.step(start_epoch)\n\n if args.local_rank == 0:\n logging.info('Scheduled epochs: {}'.format(num_epochs))\n\n train_dir = os.path.join(args.data, 'train')\n if not os.path.exists(train_dir):\n logging.error('Training folder does not exist at: {}'.format(train_dir))\n exit(1)\n dataset_train = Dataset(train_dir)\n\n collate_fn = None\n if args.prefetcher and args.mixup > 0:\n collate_fn = FastCollateMixup(args.mixup, args.smoothing, args.num_classes)\n\n loader_train = create_loader(\n dataset_train,\n input_size=data_config['input_size'],\n batch_size=args.batch_size,\n is_training=True,\n use_prefetcher=args.prefetcher,\n rand_erase_prob=args.reprob,\n rand_erase_mode=args.remode,\n color_jitter=args.color_jitter,\n interpolation='random', # FIXME cleanly resolve this? data_config['interpolation'],\n mean=data_config['mean'],\n std=data_config['std'],\n num_workers=args.workers,\n distributed=args.distributed,\n collate_fn=collate_fn,\n )\n\n eval_dir = os.path.join(args.data, 'validation')\n if not os.path.isdir(eval_dir):\n logging.error('Validation folder does not exist at: {}'.format(eval_dir))\n exit(1)\n dataset_eval = Dataset(eval_dir)\n\n loader_eval = create_loader(\n dataset_eval,\n input_size=data_config['input_size'],\n batch_size=4 * args.batch_size,\n is_training=False,\n use_prefetcher=args.prefetcher,\n interpolation=data_config['interpolation'],\n mean=data_config['mean'],\n std=data_config['std'],\n num_workers=args.workers,\n distributed=args.distributed,\n )\n\n if args.mixup > 0.:\n # smoothing is handled with mixup label transform\n train_loss_fn = SoftTargetCrossEntropy().cuda()\n validate_loss_fn = nn.CrossEntropyLoss().cuda()\n elif args.smoothing:\n train_loss_fn = LabelSmoothingCrossEntropy(smoothing=args.smoothing).cuda()\n validate_loss_fn = nn.CrossEntropyLoss().cuda()\n else:\n train_loss_fn = nn.CrossEntropyLoss().cuda()\n validate_loss_fn = train_loss_fn\n\n eval_metric = args.eval_metric\n best_metric = None\n best_epoch = None\n saver = None\n output_dir = ''\n if args.local_rank == 0:\n output_base = args.output if args.output else './output'\n exp_name = '-'.join([\n datetime.now().strftime(\"%Y%m%d-%H%M%S\"),\n args.model,\n str(data_config['input_size'][-1])\n ])\n output_dir = get_outdir(output_base, 'train', exp_name)\n decreasing = True if eval_metric == 'loss' else False\n saver = CheckpointSaver(checkpoint_dir=output_dir, decreasing=decreasing)\n\n try:\n for epoch in range(start_epoch, num_epochs):\n if args.distributed:\n loader_train.sampler.set_epoch(epoch)\n\n train_metrics = train_epoch(\n epoch, model, loader_train, optimizer, train_loss_fn, args,\n lr_scheduler=lr_scheduler, saver=saver, output_dir=output_dir,\n use_amp=use_amp, model_ema=model_ema)\n\n eval_metrics = validate(model, loader_eval, validate_loss_fn, args)\n\n if model_ema is not None and not args.model_ema_force_cpu:\n ema_eval_metrics = validate(\n model_ema.ema, loader_eval, validate_loss_fn, args, log_suffix=' (EMA)')\n eval_metrics = ema_eval_metrics\n\n if lr_scheduler is not None:\n # step LR for next epoch\n lr_scheduler.step(epoch + 1, eval_metrics[eval_metric])\n\n update_summary(\n epoch, train_metrics, eval_metrics, os.path.join(output_dir, 'summary.csv'),\n write_header=best_metric is None)\n\n if saver is not None:\n # save proper checkpoint with eval metric\n save_metric = eval_metrics[eval_metric]\n best_metric, best_epoch = saver.save_checkpoint(\n model, optimizer, args,\n epoch=epoch, model_ema=model_ema, metric=save_metric)\n\n except KeyboardInterrupt:\n pass\n if best_metric is not None:\n logging.info('*** Best metric: {0} (epoch {1})'.format(best_metric, best_epoch))\n\n\ndef train_epoch(\n epoch, model, loader, optimizer, loss_fn, args,\n lr_scheduler=None, saver=None, output_dir='', use_amp=False, model_ema=None):\n\n if args.prefetcher and args.mixup > 0 and loader.mixup_enabled:\n if args.mixup_off_epoch and epoch >= args.mixup_off_epoch:\n loader.mixup_enabled = False\n\n batch_time_m = AverageMeter()\n data_time_m = AverageMeter()\n losses_m = AverageMeter()\n\n model.train()\n\n end = time.time()\n last_idx = len(loader) - 1\n num_updates = epoch * len(loader)\n for batch_idx, (input, target) in enumerate(loader):\n last_batch = batch_idx == last_idx\n data_time_m.update(time.time() - end)\n if not args.prefetcher:\n input = input.cuda()\n target = target.cuda()\n if args.mixup > 0.:\n lam = 1.\n if not args.mixup_off_epoch or epoch < args.mixup_off_epoch:\n lam = np.random.beta(args.mixup, args.mixup)\n input.mul_(lam).add_(1 - lam, input.flip(0))\n target = mixup_target(target, args.num_classes, lam, args.smoothing)\n\n output = model(input)\n\n loss = loss_fn(output, target)\n if not args.distributed:\n losses_m.update(loss.item(), input.size(0))\n\n optimizer.zero_grad()\n if use_amp:\n with amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n else:\n loss.backward()\n optimizer.step()\n\n torch.cuda.synchronize()\n if model_ema is not None:\n model_ema.update(model)\n num_updates += 1\n\n batch_time_m.update(time.time() - end)\n if last_batch or batch_idx % args.log_interval == 0:\n lrl = [param_group['lr'] for param_group in optimizer.param_groups]\n lr = sum(lrl) / len(lrl)\n\n if args.distributed:\n reduced_loss = reduce_tensor(loss.data, args.world_size)\n losses_m.update(reduced_loss.item(), input.size(0))\n\n if args.local_rank == 0:\n logging.info(\n 'Train: {} [{:>4d}/{} ({:>3.0f}%)] '\n 'Loss: {loss.val:>9.6f} ({loss.avg:>6.4f}) '\n 'Time: {batch_time.val:.3f}s, {rate:>7.2f}/s '\n '({batch_time.avg:.3f}s, {rate_avg:>7.2f}/s) '\n 'LR: {lr:.3e} '\n 'Data: {data_time.val:.3f} ({data_time.avg:.3f})'.format(\n epoch,\n batch_idx, len(loader),\n 100. * batch_idx / last_idx,\n loss=losses_m,\n batch_time=batch_time_m,\n rate=input.size(0) * args.world_size / batch_time_m.val,\n rate_avg=input.size(0) * args.world_size / batch_time_m.avg,\n lr=lr,\n data_time=data_time_m))\n\n if args.save_images and output_dir:\n torchvision.utils.save_image(\n input,\n os.path.join(output_dir, 'train-batch-%d.jpg' % batch_idx),\n padding=0,\n normalize=True)\n\n if saver is not None and args.recovery_interval and (\n last_batch or (batch_idx + 1) % args.recovery_interval == 0):\n saver.save_recovery(\n model, optimizer, args, epoch, model_ema=model_ema, batch_idx=batch_idx)\n\n if lr_scheduler is not None:\n lr_scheduler.step_update(num_updates=num_updates, metric=losses_m.avg)\n\n end = time.time()\n\n return OrderedDict([('loss', losses_m.avg)])\n\n\ndef validate(model, loader, loss_fn, args, log_suffix=''):\n batch_time_m = AverageMeter()\n losses_m = AverageMeter()\n prec1_m = AverageMeter()\n prec5_m = AverageMeter()\n\n model.eval()\n\n end = time.time()\n last_idx = len(loader) - 1\n with torch.no_grad():\n for batch_idx, (input, target) in enumerate(loader):\n last_batch = batch_idx == last_idx\n if not args.prefetcher:\n input = input.cuda()\n target = target.cuda()\n\n output = model(input)\n if isinstance(output, (tuple, list)):\n output = output[0]\n\n # augmentation reduction\n reduce_factor = args.tta\n if reduce_factor > 1:\n output = output.unfold(0, reduce_factor, reduce_factor).mean(dim=2)\n target = target[0:target.size(0):reduce_factor]\n\n loss = loss_fn(output, target)\n prec1, prec5 = accuracy(output, target, topk=(1, 5))\n\n if args.distributed:\n reduced_loss = reduce_tensor(loss.data, args.world_size)\n prec1 = reduce_tensor(prec1, args.world_size)\n prec5 = reduce_tensor(prec5, args.world_size)\n else:\n reduced_loss = loss.data\n\n torch.cuda.synchronize()\n\n losses_m.update(reduced_loss.item(), input.size(0))\n prec1_m.update(prec1.item(), output.size(0))\n prec5_m.update(prec5.item(), output.size(0))\n\n batch_time_m.update(time.time() - end)\n end = time.time()\n if args.local_rank == 0 and (last_batch or batch_idx % args.log_interval == 0):\n log_name = 'Test' + log_suffix\n logging.info(\n '{0}: [{1:>4d}/{2}] '\n 'Time: {batch_time.val:.3f} ({batch_time.avg:.3f}) '\n 'Loss: {loss.val:>7.4f} ({loss.avg:>6.4f}) '\n 'Prec@1: {top1.val:>7.4f} ({top1.avg:>7.4f}) '\n 'Prec@5: {top5.val:>7.4f} ({top5.avg:>7.4f})'.format(\n log_name, batch_idx, last_idx,\n batch_time=batch_time_m, loss=losses_m,\n top1=prec1_m, top5=prec5_m))\n\n metrics = OrderedDict([('loss', losses_m.avg), ('prec1', prec1_m.avg), ('prec5', prec5_m.avg)])\n\n return metrics\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"torch.distributed.get_world_size",
"torch.cuda.synchronize",
"torch.nn.SyncBatchNorm.convert_sync_batchnorm",
"torch.distributed.init_process_group",
"torch.no_grad",
"torch.nn.parallel.DistributedDataParallel",
"torch.manual_seed",
"torch.cuda.set_device",
"torch.distributed.get_rank",
"torch.nn.CrossEntropyLoss"
]
] |
ParkerLab/PillowNet
|
[
"b511c38d62e6b847d6fe0bd9ef855dc458d94b91"
] |
[
"predict.py"
] |
[
"#!/usr/bin/env python\n\"\"\"\nScript for generating predictions from a trained model.\nUse `predict.py -h` to see an auto-generated description of advanced options.\n\"\"\"\n\nimport argparse\nimport numpy as np\n\nfrom keras.models import load_model\nfrom tqdm import tqdm, trange\nimport pybedtools as pbt\nimport pyBigWig as pbw\n\nfrom genomeloader.wrapper import TwoBitWrapper, FastaWrapper, BedWrapper, BigWigWrapper\nfrom genomeloader.generator import MultiBedGenerator\n\nfrom pillownet.layer import ReverseComplement, Reverse\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description='Generating predictions.',\n epilog='\\n'.join(__doc__.strip().split('\\n')[1:]).strip(),\n formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument('-w', '--weights', required=True,\n help='Input model weights.', type=str)\n parser.add_argument('-o', '--output', required=True,\n help='Output bigWig file of predictions.', type=str)\n parser.add_argument('-bl', '--blacklist', required=False,\n default='resources/blacklist.bed.gz',\n help='Blacklist BED file.', type=str)\n parser.add_argument('-bw', '--bigwigs', type=str, required=False, nargs='*',\n default=None,\n help='Input bigwig files.')\n parser.add_argument('-s', '--step',\n help='Step size and window size to make predictions for.',\n type=int, default=50)\n parser.add_argument('-ch', '--channel',\n help='If the model is multi-task, select which channel will be output (default: 0).',\n type=int, default=0)\n parser.add_argument('-t', '--threshold',\n help='Remove all signal values below threshold (default: 1e-2).',\n type=float, default=1e-2)\n parser.add_argument('-at', '--autothreshold', action='store_true', default=False,\n help='Automatically set threshold.')\n parser.add_argument('-p', '--processes',\n help='Number of parallel process workers (default: 3. If set to 0, then multiprocessing will '\n 'not be used).',\n type=int, default=3)\n group = parser.add_mutually_exclusive_group(required=False)\n group.add_argument('-c', '--chroms', type=str, nargs='+',\n default=['chr1', 'chr8', 'chr21'],\n help='Chromosome(s) to make predictions for.')\n group.add_argument('-wg', '--wholegenome', action='store_true', default=False,\n help='Make predictions for the whole genome.')\n group.add_argument('-ax', '--autox', action='store_true', default=False,\n help='Predict on autosomes and X chromosome.')\n group.add_argument('-a', '--auto', action='store_true', default=False,\n help='Predict on autosomes.')\n group = parser.add_mutually_exclusive_group(required=False)\n group.add_argument('-gf', '--genomefasta', type=str,\n help='Genome FASTA file.')\n group.add_argument('-gt', '--genometwobit', type=str,\n help='Genome twobit file.')\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = get_args()\n weights_file = args.weights\n output_file = args.output\n step = args.step\n channel = args.channel\n workers = args.processes\n threshold = args.threshold\n autothreshold = args.autothreshold\n\n bw = pbw.open(output_file, 'w')\n\n if workers > 0:\n use_multiprocessing = True\n thread_safe = True\n else:\n workers = 0\n use_multiprocessing = False\n thread_safe = False\n\n signals = []\n\n if args.genometwobit is not None:\n genome = TwoBitWrapper(args.genometwobit, thread_safe=thread_safe)\n signals.append(genome)\n elif args.genomefasta is not None:\n genome = FastaWrapper(args.genomefasta, thread_safe=thread_safe)\n signals.append(genome)\n else:\n genome = None\n\n # Load bigwigs\n bigwig_files = args.bigwigs\n bigwigs = [] if bigwig_files is None else [BigWigWrapper(bigwig_file, thread_safe=thread_safe) for bigwig_file in\n bigwig_files]\n signals.extend(bigwigs)\n\n chroms_size = signals[0].chroms_size()\n\n # Load blacklist file\n blacklist_file = args.blacklist\n blacklist = None if blacklist_file is None else BedWrapper(blacklist_file)\n\n if args.wholegenome:\n chroms = signals[0].chroms()\n elif args.autox:\n chroms = ['chr1', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15', 'chr16', 'chr17', 'chr18', 'chr19',\n 'chr2', 'chr20', 'chr21', 'chr22', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8', 'chr9', 'chrX']\n elif args.auto:\n chroms = ['chr1', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15', 'chr16', 'chr17', 'chr18', 'chr19',\n 'chr2', 'chr20', 'chr21', 'chr22', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8', 'chr9']\n else:\n chroms = args.chroms\n\n header = []\n for chrom in chroms:\n chrom_size = chroms_size[chrom]\n header.append((chrom, chrom_size))\n bw.addHeader(header)\n\n model = load_model(weights_file, custom_objects={'ReverseComplement': ReverseComplement,\n 'Reverse': Reverse}, compile=False)\n\n if autothreshold:\n input_shape = model.input_shape\n if type(input_shape) is list:\n input_shape = [np.array(i) for i in input_shape]\n for i in input_shape:\n i[0] = 1\n input_zeros = [np.zeros(i) for i in input_shape]\n else:\n input_shape = np.array(input_shape)\n input_shape[0] = 1\n input_zeros = np.zeros(input_shape)\n output_zeros = model.predict(input_zeros)\n threshold = output_zeros.max() * 1.01\n print('The new threshold is: %f' % threshold)\n\n return_sequences = len(model.output_shape) == 3\n multi_task = model.output_shape[-1] > 1\n\n dna_input_shape = model.input_shape[0] if isinstance(model.input_shape, list) else model.input_shape\n seq_len = dna_input_shape[1]\n output_seq_len = None\n\n if return_sequences:\n step = model.output_shape[1]\n output_seq_len = model.output_shape[1]\n\n pbar = tqdm(chroms)\n for chrom in pbar:\n pbar.set_description('Processing %s' % chrom)\n chrom_size = chroms_size[chrom]\n chrom_windows_bt = pbt.BedTool().window_maker(genome={chrom: (0, chrom_size)}, w=step, s=step)\n chrom_windows = BedWrapper(chrom_windows_bt.fn, sort_bed=False)\n generator = MultiBedGenerator(beds=[chrom_windows], signals=signals, seq_len=seq_len,\n output_seq_len=output_seq_len, negatives_ratio=0, jitter_mode=None,\n shuffle=False, return_sequences=return_sequences, return_output=False,\n left_justify=True)\n chrom_start = 0\n for i in trange(len(generator)):\n batch = generator[i]\n #chrom_end = chrom_start + step * len(batch)\n predictions_batch = model.predict(batch)\n if multi_task:\n predictions_batch = predictions_batch[:, :, channel]\n values = predictions_batch.ravel()\n chrom_end = chrom_start + len(values)\n starts = np.arange(chrom_start, chrom_end)\n if blacklist is not None:\n values_blacklist = blacklist[chrom, chrom_start:chrom_end].ravel()\n values[values_blacklist] = 0\n if chrom_end > chrom_size:\n crop_size = chrom_size - chrom_end\n values = values[:crop_size]\n starts = starts[:crop_size]\n chrom_start = chrom_end\n above_threshold = values >= threshold\n values = values[above_threshold]\n if len(values) == 0:\n continue\n starts = starts[above_threshold]\n bw.addEntries(chroms=chrom, starts=starts, span=1, values=values)\n\n bw.close()\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"numpy.array",
"numpy.arange",
"numpy.zeros"
]
] |
moneypi/SSD-pytorch
|
[
"25dc91db133a3575d656b2df68ffdf4ef1135233"
] |
[
"utils/augmentations.py"
] |
[
"import torch\nfrom torchvision import transforms\nimport cv2\nimport numpy as np\nimport types\nfrom numpy import random\n\n\ndef intersect(box_a, box_b):\n max_xy = np.minimum(box_a[:, 2:], box_b[2:])\n min_xy = np.maximum(box_a[:, :2], box_b[:2])\n inter = np.clip((max_xy - min_xy), a_min=0, a_max=np.inf)\n return inter[:, 0] * inter[:, 1]\n\n\ndef jaccard_numpy(box_a, box_b):\n \"\"\"Compute the jaccard overlap of two sets of boxes. The jaccard overlap\n is simply the intersection over union of two boxes.\n E.g.:\n A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)\n Args:\n box_a: Multiple bounding boxes, Shape: [num_boxes,4]\n box_b: Single bounding box, Shape: [4]\n Return:\n jaccard overlap: Shape: [box_a.shape[0], box_a.shape[1]]\n \"\"\"\n inter = intersect(box_a, box_b)\n area_a = ((box_a[:, 2]-box_a[:, 0]) *\n (box_a[:, 3]-box_a[:, 1])) # [A,B]\n area_b = ((box_b[2]-box_b[0]) *\n (box_b[3]-box_b[1])) # [A,B]\n union = area_a + area_b - inter\n return inter / union # [A,B]\n\n\nclass Compose(object):\n \"\"\"Composes several augmentations together.\n Args:\n transforms (List[Transform]): list of transforms to compose.\n Example:\n >>> augmentations.Compose([\n >>> transforms.CenterCrop(10),\n >>> transforms.ToTensor(),\n >>> ])\n \"\"\"\n\n def __init__(self, transforms):\n self.transforms = transforms\n\n def __call__(self, img, boxes=None, labels=None):\n for t in self.transforms:\n img, boxes, labels = t(img, boxes, labels)\n return img, boxes, labels\n\n\nclass Lambda(object):\n \"\"\"Applies a lambda as a transform.\"\"\"\n\n def __init__(self, lambd):\n assert isinstance(lambd, types.LambdaType)\n self.lambd = lambd\n\n def __call__(self, img, boxes=None, labels=None):\n return self.lambd(img, boxes, labels)\n\n\nclass ConvertFromInts(object):\n def __call__(self, image, boxes=None, labels=None):\n return image.astype(np.float32), boxes, labels\n\n\nclass SubtractMeans(object):\n def __init__(self, mean):\n self.mean = np.array(mean, dtype=np.float32)\n\n def __call__(self, image, boxes=None, labels=None):\n image = image.astype(np.float32)\n image -= self.mean\n return image.astype(np.float32), boxes, labels\n\n\nclass ToAbsoluteCoords(object):\n def __call__(self, image, boxes=None, labels=None):\n height, width, channels = image.shape\n boxes[:, 0] *= width\n boxes[:, 2] *= width\n boxes[:, 1] *= height\n boxes[:, 3] *= height\n\n return image, boxes, labels\n\n\nclass ToPercentCoords(object):\n def __call__(self, image, boxes=None, labels=None):\n height, width, channels = image.shape\n boxes[:, 0] /= width\n boxes[:, 2] /= width\n boxes[:, 1] /= height\n boxes[:, 3] /= height\n\n return image, boxes, labels\n\n\nclass Resize(object):\n def __init__(self, size=300):\n self.size = size\n\n def __call__(self, image, boxes=None, labels=None):\n image = cv2.resize(image, (self.size,\n self.size))\n return image, boxes, labels\n\n\nclass RandomSaturation(object):\n def __init__(self, lower=0.5, upper=1.5):\n self.lower = lower\n self.upper = upper\n assert self.upper >= self.lower, \"contrast upper must be >= lower.\"\n assert self.lower >= 0, \"contrast lower must be non-negative.\"\n\n def __call__(self, image, boxes=None, labels=None):\n if random.randint(2):\n image[:, :, 1] *= random.uniform(self.lower, self.upper)\n\n return image, boxes, labels\n\n\nclass RandomHue(object):\n def __init__(self, delta=18.0):\n assert delta >= 0.0 and delta <= 360.0\n self.delta = delta\n\n def __call__(self, image, boxes=None, labels=None):\n if random.randint(2):\n image[:, :, 0] += random.uniform(-self.delta, self.delta)\n image[:, :, 0][image[:, :, 0] > 360.0] -= 360.0\n image[:, :, 0][image[:, :, 0] < 0.0] += 360.0\n return image, boxes, labels\n\n\nclass RandomLightingNoise(object):\n def __init__(self):\n self.perms = ((0, 1, 2), (0, 2, 1),\n (1, 0, 2), (1, 2, 0),\n (2, 0, 1), (2, 1, 0))\n\n def __call__(self, image, boxes=None, labels=None):\n if random.randint(2):\n # 随机选取一个通道的交换顺序,交换图像三个通道的值\n swap = self.perms[random.randint(len(self.perms))]\n shuffle = SwapChannels(swap) # shuffle channels\n image = shuffle(image)\n return image, boxes, labels\n\n\nclass ConvertColor(object):\n def __init__(self, current='BGR', transform='HSV'):\n self.transform = transform\n self.current = current\n\n def __call__(self, image, boxes=None, labels=None):\n if self.current == 'BGR' and self.transform == 'HSV':\n image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n elif self.current == 'HSV' and self.transform == 'BGR':\n image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)\n else:\n raise NotImplementedError\n return image, boxes, labels\n\n\nclass RandomContrast(object):\n def __init__(self, lower=0.5, upper=1.5):\n self.lower = lower\n self.upper = upper\n assert self.upper >= self.lower, \"contrast upper must be >= lower.\"\n assert self.lower >= 0, \"contrast lower must be non-negative.\"\n\n # expects float image\n def __call__(self, image, boxes=None, labels=None):\n if random.randint(2):\n alpha = random.uniform(self.lower, self.upper)\n image *= alpha\n return image, boxes, labels\n\n\nclass RandomBrightness(object):\n def __init__(self, delta=32):\n assert delta >= 0.0\n assert delta <= 255.0\n self.delta = delta\n\n def __call__(self, image, boxes=None, labels=None):\n if random.randint(2):\n # 随机选取一个位于[-32, 32)区间的数,相加到图像上\n delta = random.uniform(-self.delta, self.delta)\n image += delta\n return image, boxes, labels\n\n\nclass ToCV2Image(object):\n def __call__(self, tensor, boxes=None, labels=None):\n return tensor.cpu().numpy().astype(np.float32).transpose((1, 2, 0)), boxes, labels\n\n\nclass ToTensor(object):\n def __call__(self, cvimage, boxes=None, labels=None):\n return torch.from_numpy(cvimage.astype(np.float32)).permute(2, 0, 1), boxes, labels\n\n\nclass RandomSampleCrop(object):\n \"\"\"Crop\n Arguments:\n img (Image): the image being input during training\n boxes (Tensor): the original bounding boxes in pt form\n labels (Tensor): the class labels for each bbox\n mode (float tuple): the min and max jaccard overlaps\n Return:\n (img, boxes, classes)\n img (Image): the cropped image\n boxes (Tensor): the adjusted bounding boxes in pt form\n labels (Tensor): the class labels for each bbox\n \"\"\"\n def __init__(self):\n self.sample_options = (\n # using entire original input image\n None,\n # sample a patch s.t. MIN jaccard w/ obj in .1,.3,.4,.7,.9\n (0.1, None),\n (0.3, None),\n (0.7, None),\n (0.9, None),\n # randomly sample a patch\n (None, None),\n )\n\n def __call__(self, image, boxes=None, labels=None):\n height, width, _ = image.shape\n while True:\n # randomly choose a mode\n mode = random.choice(self.sample_options)\n if mode is None:\n return image, boxes, labels\n\n min_iou, max_iou = mode\n if min_iou is None:\n min_iou = float('-inf')\n if max_iou is None:\n max_iou = float('inf')\n\n # max trails (50)\n for _ in range(50):\n current_image = image\n\n w = random.uniform(0.3 * width, width)\n h = random.uniform(0.3 * height, height)\n\n # aspect ratio constraint b/t .5 & 2\n if h / w < 0.5 or h / w > 2:\n continue\n\n left = random.uniform(width - w)\n top = random.uniform(height - h)\n\n # convert to integer rect x1,y1,x2,y2\n rect = np.array([int(left), int(top), int(left+w), int(top+h)])\n\n # calculate IoU (jaccard overlap) b/t the cropped and gt boxes\n overlap = jaccard_numpy(boxes, rect)\n\n # is min and max overlap constraint satisfied? if not try again\n if overlap.min() < min_iou and max_iou < overlap.max():\n continue\n\n # cut the crop from the image\n current_image = current_image[rect[1]:rect[3], rect[0]:rect[2],\n :]\n\n # keep overlap with gt box IF center in sampled patch\n centers = (boxes[:, :2] + boxes[:, 2:]) / 2.0\n\n # mask in all gt boxes that above and to the left of centers\n m1 = (rect[0] < centers[:, 0]) * (rect[1] < centers[:, 1])\n\n # mask in all gt boxes that under and to the right of centers\n m2 = (rect[2] > centers[:, 0]) * (rect[3] > centers[:, 1])\n\n # mask in that both m1 and m2 are true\n mask = m1 * m2\n\n # have any valid boxes? try again if not\n if not mask.any():\n continue\n\n # take only matching gt boxes\n current_boxes = boxes[mask, :].copy()\n\n # take only matching gt labels\n current_labels = labels[mask]\n\n # should we use the box left and top corner or the crop's\n current_boxes[:, :2] = np.maximum(current_boxes[:, :2],\n rect[:2])\n # adjust to crop (by substracting crop's left,top)\n current_boxes[:, :2] -= rect[:2]\n\n current_boxes[:, 2:] = np.minimum(current_boxes[:, 2:],\n rect[2:])\n # adjust to crop (by substracting crop's left,top)\n current_boxes[:, 2:] -= rect[:2]\n\n return current_image, current_boxes, current_labels\n\n\nclass Expand(object):\n def __init__(self, mean):\n self.mean = mean\n\n def __call__(self, image, boxes, labels):\n if random.randint(2):\n return image, boxes, labels\n # 求取原图像在新图像中的左上角坐标值\n height, width, depth = image.shape\n ratio = random.uniform(1, 4)\n left = random.uniform(0, width*ratio - width)\n top = random.uniform(0, height*ratio - height)\n\n # 建立新的图像,并依次赋值\n expand_image = np.zeros(\n (int(height*ratio), int(width*ratio), depth),\n dtype=image.dtype)\n expand_image[:, :, :] = self.mean\n expand_image[int(top):int(top + height),\n int(left):int(left + width)] = image\n image = expand_image\n\n # 对边框也进行相应变换\n boxes = boxes.copy()\n boxes[:, :2] += (int(left), int(top))\n boxes[:, 2:] += (int(left), int(top))\n\n return image, boxes, labels\n\n\nclass RandomMirror(object):\n def __call__(self, image, boxes, classes):\n _, width, _ = image.shape\n if random.randint(2):\n # 这里的::代表反向,即将每一行的数据反向遍历,完成镜像\n image = image[:, ::-1]\n boxes = boxes.copy()\n boxes[:, 0::2] = width - boxes[:, 2::-2]\n return image, boxes, classes\n\n\nclass SwapChannels(object):\n \"\"\"Transforms a tensorized image by swapping the channels in the order\n specified in the swap tuple.\n Args:\n swaps (int triple): final order of channels\n eg: (2, 1, 0)\n \"\"\"\n\n def __init__(self, swaps):\n self.swaps = swaps\n\n def __call__(self, image):\n \"\"\"\n Args:\n image (Tensor): image tensor to be transformed\n Return:\n a tensor with channels swapped according to swap\n \"\"\"\n # if torch.is_tensor(image):\n # image = image.data.cpu().numpy()\n # else:\n # image = np.array(image)\n image = image[:, :, self.swaps]\n return image\n\n\nclass PhotometricDistort(object):\n def __init__(self):\n self.pd = [\n RandomContrast(),\n ConvertColor(transform='HSV'),\n RandomSaturation(),\n RandomHue(),\n ConvertColor(current='HSV', transform='BGR'),\n RandomContrast()\n ]\n self.rand_brightness = RandomBrightness()\n self.rand_light_noise = RandomLightingNoise()\n\n def __call__(self, image, boxes, labels):\n im = image.copy()\n im, boxes, labels = self.rand_brightness(im, boxes, labels)\n if random.randint(2):\n distort = Compose(self.pd[:-1])\n else:\n distort = Compose(self.pd[1:])\n im, boxes, labels = distort(im, boxes, labels)\n return self.rand_light_noise(im, boxes, labels)\n\n\nclass SSDAugmentation(object):\n def __init__(self, size=300, mean=(104, 117, 123)):\n self.mean = mean\n self.size = size\n self.augment = Compose([\n # 首先将图像像素值从整型变成浮点型\n ConvertFromInts(),\n # 将标签中的边框从比例坐标变换为真实坐标\n ToAbsoluteCoords(),\n # 因此进行亮度、对比度、色相与饱和度的随机调整,然后随机调换通道\n PhotometricDistort(),\n Expand(self.mean), # 随机扩展图像大小,图像仅靠右下方\n RandomSampleCrop(), # 随机裁剪图像\n RandomMirror(), # 随机左右镜像\n ToPercentCoords(), # 从真实坐标变回比例坐标\n Resize(self.size), # 缩放到固定的300*300大小\n SubtractMeans(self.mean) # 最后进行均值化\n ])\n\n def __call__(self, img, boxes, labels):\n return self.augment(img, boxes, labels)\n"
] |
[
[
"numpy.array",
"numpy.random.choice",
"numpy.minimum",
"numpy.random.uniform",
"numpy.random.randint",
"numpy.clip",
"numpy.maximum"
]
] |
DataverseLabs/pyinterpolate
|
[
"5e0caf0fd839324932918bb50bf0464fffbefb78"
] |
[
"pyinterpolate/test/transform/test_prepare_kriging_data.py"
] |
[
"import unittest\nimport numpy as np\nfrom pyinterpolate.transform.prepare_kriging_data import prepare_kriging_data\n\n\nclass TestPrepareKrigingData(unittest.TestCase):\n\n def test_prepare_kriging_data(self):\n EXPECTED_NUMBER_OF_NEIGHBORS = 1\n EXPECTED_OUTPUT = np.array([[13, 10, 9, 3]])\n unknown_pos = (10, 10)\n pos = [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [13, 10, 9]]\n pos = np.array(pos)\n d = prepare_kriging_data(unknown_pos, pos, neighbors_range=4)\n d = d.astype(np.int)\n\n test_output = np.array_equal(d, EXPECTED_OUTPUT)\n test_length = len(d) == EXPECTED_NUMBER_OF_NEIGHBORS\n\n self.assertTrue(test_length, \"Length of prepared dataset should be 1 (one neighbour)\")\n self.assertTrue(test_output, \"Output array should be [[13, 10, 9, 3]]\")\n\n def test_prepare_kriging_data_no_neighb_in_range(self):\n EXPECTED_OUTPUT = np.array([[13, 10, 9, 3]])\n unknown_pos = (10, 10)\n pos = [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [13, 10, 9]]\n pos = np.array(pos)\n d = prepare_kriging_data(unknown_pos, pos, neighbors_range=2)\n d = d.astype(np.int)\n test_output = np.array_equal(d, EXPECTED_OUTPUT)\n self.assertTrue(test_output, \"Output array should be [[13, 10, 9, 3]]\")\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"numpy.array",
"numpy.array_equal"
]
] |
ArthurMor4is/grad-cam-covid-19-ct
|
[
"14474a635e7633c8382839582d2a2cd9ff98eb62"
] |
[
"my_functions.py"
] |
[
"import os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nimport matplotlib.pyplot as plt\nimport tensorflow_datasets as tfds\nfrom tensorflow.keras import layers\nimport matplotlib.cm as cm\nimport random\nimport glob\nfrom skimage.segmentation import chan_vese\nfrom shutil import copy\nfrom skimage.morphology import white_tophat, black_tophat, disk\n\n\ndef random_split_patients(unique_patients_ids, validation_split, seed):\n \"\"\"\n Randomly splits the patients.\n\n Args:\n unique_patients_ids (_type_): Unique patients ids.\n validation_split (_type_): Validation split.\n seed (_type_): Seed.\n\n Returns:\n _type_: Train, validation and test ids.\n \"\"\"\n np.random.seed(seed)\n number_of_patients = len(unique_patients_ids)\n number_of_train_patients = int(number_of_patients * (1 - validation_split))\n \n np.random.shuffle(unique_patients_ids)\n train_patients_ids = unique_patients_ids[:number_of_train_patients]\n val_patients_ids = unique_patients_ids[number_of_train_patients:]\n \n return train_patients_ids, val_patients_ids\n\ndef copy_all_images_from_one_patient(patient_id, src_folder, dst_folder, metadata):\n \"\"\"\n Copies all images from one patient.\n\n Args:\n patient_id (_type_): Patient id.\n src_folder (_type_): Source folder.\n dst_folder (_type_): Destination folder.\n metadata (_type_): Metadata.\n\n Returns:\n _type_: None.\n \"\"\"\n try:\n patient_dataset = metadata.loc[metadata['Patient ID'] == patient_id]\n files = patient_dataset['File name']\n for file in files:\n src = src_folder + '\\\\' + file\n copy(src, dst_folder)\n except Exception as e:\n print('Copy error: {}'.format(e))\n\ndef check_dataset(dataset, color_map='viridis'):\n \"\"\"\n Checks the dataset.\n\n Args:\n dataset (_type_): Dataset.\n color_map (str, optional): Color map. Defaults to 'viridis'.\n\n Returns:\n _type_: None.\n \"\"\"\n plt.figure(figsize=(10, 10))\n for images, labels in dataset.take(1):\n for i in range(9):\n ax = plt.subplot(3, 3, i + 1)\n plt.imshow(images[i].numpy().astype(\"uint8\"), cmap=color_map)\n plt.title('...' + dataset.file_paths[i][-20:])\n plt.axis(\"off\")\n\nroot_logdir = os.path.join(os.curdir, \"my_logs\")\ndef get_run_logdir():\n \"\"\"\n Returns the logdir for the current run.\n\n Returns:\n _type_: str.\n \"\"\"\n import time\n run_id = time.strftime(\"run_%Y_%m_%d-%H_%M_%S\")\n return os.path.join(root_logdir, run_id)\n\nroot_modeldir = os.path.join(os.curdir, \"my_models\")\ndef get_model_dir():\n \"\"\"\n Returns the model dir for the current run.\n\n Returns:\n _type_: str.\n \"\"\"\n\n import time\n run_id = time.strftime(\"run_%Y_%m_%d-%H_%M_%S\")\n return os.path.join(root_modeldir, run_id)\n\ndef find_target_layer(model):\n \"\"\"\n Finds the target layer.\n\n Args:\n model (_type_): Model.\n\n Returns:\n _type_: Target layer.\n \"\"\"\n for layer in reversed(model.layers):\n if len(layer.output_shape) == 4:\n return layer.name\n raise ValueError(\"Could not find 4D layer. Cannot apply GradCAM.\")\n\ndef get_img_array(img_path, size):\n \"\"\"\n Returns the image array.\n\n Args:\n img_path (_type_): Image path.\n size (_type_): Size.\n\n Returns:\n _type_: Image array.\n \"\"\"\n img = keras.preprocessing.image.load_img(img_path, target_size=size)\n array = keras.preprocessing.image.img_to_array(img)\n array = np.expand_dims(array, axis=0)\n return array\n \ndef make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=None):\n \"\"\"\n Makes the gradcam heatmap.\n\n Args:\n img_array (_type_): Image array.\n model (_type_): Model.\n last_conv_layer_name (_type_): Last conv layer name.\n pred_index (_type_, optional): Prediction index. Defaults to None.\n\n Returns:\n _type_: Gradcam heatmap.\n \"\"\"\n grad_model = tf.keras.models.Model(\n [model.inputs], [model.get_layer(last_conv_layer_name).output, model.output]\n )\n\n with tf.GradientTape() as tape:\n last_conv_layer_output, preds = grad_model(img_array)\n if pred_index is None:\n pred_index = tf.argmax(preds[0])\n class_channel = preds[:, pred_index]\n\n grads = tape.gradient(class_channel, last_conv_layer_output)\n\n pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))\n\n last_conv_layer_output = last_conv_layer_output[0]\n heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]\n heatmap = tf.squeeze(heatmap)\n\n heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)\n return heatmap.numpy()\n\ndef build_gradcam(img_path, heatmap, color_map, original_image_colormap, alpha=0.5):\n \"\"\"\n Builds the gradcam.\n\n Args:\n img_path (_type_): Image path.\n heatmap (_type_): Heatmap.\n color_map (_type_): Color map.\n original_image_colormap (_type_): Original image colormap.\n alpha (float, optional): Alpha. Defaults to 0.5.\n\n Returns:\n _type_: Gradcam.\n \"\"\"\n img = keras.preprocessing.image.load_img(img_path, color_mode=original_image_colormap)\n img = keras.preprocessing.image.img_to_array(img)\n\n heatmap = np.uint8(255 * heatmap)\n\n jet = cm.get_cmap(color_map)\n \n jet_colors = jet(np.arange(256))[:, :3]\n jet_heatmap = jet_colors[heatmap]\n\n jet_heatmap = keras.preprocessing.image.array_to_img(jet_heatmap)\n jet_heatmap = jet_heatmap.resize((img.shape[1], img.shape[0]))\n jet_heatmap = keras.preprocessing.image.img_to_array(jet_heatmap)\n\n superimposed_img = jet_heatmap * alpha + img\n superimposed_img = keras.preprocessing.image.array_to_img(superimposed_img)\n\n return superimposed_img\n\ndef superimpose_gradcam(img_path, image_size, current_model, grad_colormap, original_image_colormap, last_layer_grad_cam):\n \"\"\"\n Superimposes the gradcam.\n\n Args:\n img_path (_type_): Image path.\n image_size (_type_): Image size.\n current_model (_type_): Current model.\n grad_colormap (_type_): Grad colormap.\n original_image_colormap (_type_): Original image colormap.\n last_layer_grad_cam (_type_): Last layer grad cam.\n\n Returns:\n _type_: Superimposed gradcam.\n \"\"\"\n preprocess_input = keras.applications.xception.preprocess_input\n img_array = preprocess_input(get_img_array(img_path, size=image_size))\n\n current_model.layers[-1].activation = None\n\n last_conv_layer_name = find_target_layer(current_model)\n heatmap = make_gradcam_heatmap(img_array, current_model, last_conv_layer_name=last_layer_grad_cam)\n return build_gradcam(img_path, heatmap, color_map=grad_colormap, original_image_colormap=original_image_colormap)\n\ndef test_grad_cam_in_path(current_model, default_images_path, image_size, grad_colormap, original_image_colormap, last_layer_grad_cam):\n \"\"\"\n Tests the grad cam in path.\n\n Args:\n current_model (_type_): Current model.\n default_images_path (_type_): Default images path.\n image_size (_type_): Image size.\n grad_colormap (_type_): Grad colormap.\n original_image_colormap (_type_): Original image colormap.\n last_layer_grad_cam (_type_): Last layer grad cam.\n\n Returns:\n _type_: Superimposed gradcam.\n \"\"\"\n plt.figure(figsize=(10, 10))\n list_images = glob.glob(default_images_path + \"*\")\n for i in range(9):\n ax = plt.subplot(3, 3, i + 1)\n img_path = random.choice(list_images)\n superimposed_img = superimpose_gradcam( \n current_model=current_model, \n img_path=img_path,\n image_size=image_size,\n grad_colormap=grad_colormap,\n original_image_colormap=original_image_colormap,\n last_layer_grad_cam=last_layer_grad_cam\n )\n plt.imshow(superimposed_img)\n plt.title('{}'.format(img_path[-20:]))\n plt.axis(\"off\")\n\ndef aply_segmentation_to_image(original_image_path, init_level_set='disk', mu=0.25):\n \"\"\"\n Aply segmentation to image.\n\n Args:\n original_image_path (_type_): Original image path.\n init_level_set (str, optional): Initial level set. Defaults to 'disk'.\n mu (float, optional): Mu. Defaults to 0.25.\n\n Returns:\n _type_: Segmented image.\n \"\"\"\n img_path = original_image_path\n img = keras.preprocessing.image.load_img(img_path)\n img_array = keras.preprocessing.image.img_to_array(img)\n \n # from 3d to 2d\n sample_slice = img_array[:, :, 0]\n\n # from 0-255 to 0-1\n normalize_slice = np.true_divide(sample_slice, [255.0], out=None)\n\n # aplyng chen algorithm\n lung_mask = chan_vese(\n normalize_slice, \n mu=mu, \n lambda1=1.0, \n lambda2=1.0, \n tol=0.001, \n dt=0.5, \n init_level_set=init_level_set, \n extended_output=False).astype(int)\n\n extend_lung_mask = lung_mask[:, :, np.newaxis]\n\n lung_segmentation_result = extend_lung_mask * img_array[:, :, :]\n return lung_segmentation_result\n\ndef aply_segmentation_to_folder(original_folder_path, destination_folder_path, mu=0.25, init_level_set='disk'):\n \"\"\"\n Aply segmentation to folder.\n\n Args:\n original_folder_path (_type_): Original folder path.\n destination_folder_path (_type_): Destination folder path.\n mu (float, optional): Mu. Defaults to 0.25.\n init_level_set (str, optional): Initial level set. Defaults to 'disk'.\n\n Returns:\n _type_: Segmented folder.\n \"\"\"\n list_images_paths = glob.glob(original_folder_path + \"*\")\n for current_image_path in list_images_paths:\n image_name = current_image_path.split('\\\\')[-1]\n result_image = aply_segmentation_to_image(\n original_image_path=current_image_path, \n init_level_set=init_level_set,\n mu=mu)\n tf.keras.utils.save_img(\n path=\"{}seg_version_{}\".format(destination_folder_path, image_name),\n x=result_image, \n data_format=None, \n file_format='png', \n scale=True\n )\n\ndef find_last_layer(model):\n \"\"\"\n Find last layer.\n\n Args:\n model (_type_): Model.\n\n Returns:\n _type_: Last layer.\n \"\"\"\n for layer in reversed(model.layers):\n return layer\n \ndef aply_white_tophat_to_folder(original_folder_path, destination_folder_path, disk_size):\n \"\"\"\n Aply white tophat to folder.\n\n Args:\n original_folder_path (_type_): Original folder path.\n destination_folder_path (_type_): Destination folder path.\n disk_size (_type_): Disk size.\n\n \"\"\"\n list_images_paths = glob.glob(original_folder_path + \"*\")\n for current_image_path in list_images_paths:\n image_name = current_image_path.split('\\\\')[-1]\n print(\"Current_image: {}\".format(current_image_path))\n result_image = aply_white_tophat_to_image(original_image_path=current_image_path, disk_size=disk_size)\n tf.keras.utils.save_img(\n path=\"{}seg_version_{}\".format(destination_folder_path, image_name),\n x=result_image, \n data_format=None, \n file_format='png', \n scale=True\n )\n\ndef aply_white_tophat_to_image(original_image_path, disk_size):\n \"\"\"\n Aply white tophat to image.\n\n Args:\n original_image_path (_type_): Original image path.\n disk_size (_type_): Disk size.\n\n Returns:\n _type_: White tophat image.\n \"\"\"\n img_path = original_image_path\n img = keras.preprocessing.image.load_img(img_path)\n img_array = keras.preprocessing.image.img_to_array(img)\n sample_slice = img_array[:, :, 0]\n normalize_slice = np.true_divide(sample_slice, [255.0], out=None)\n footprint = disk(disk_size)\n w_tophat = white_tophat(normalize_slice, footprint)\n w_tophat = np.uint8(255 * w_tophat)\n return w_tophat[:, :, np.newaxis]\n\ndef aply_black_tophat_to_image(original_image_path, disk_size):\n \"\"\"\n Aply black tophat to image.\n\n Args:\n original_image_path (_type_): Original image path.\n disk_size (_type_): Disk size.\n\n Returns:\n _type_: Black tophat image.\n \"\"\"\n img_path = original_image_path\n img = keras.preprocessing.image.load_img(img_path)\n img_array = keras.preprocessing.image.img_to_array(img)\n sample_slice = img_array[:, :, 0]\n normalize_slice = np.true_divide(sample_slice, [255.0], out=None)\n footprint = disk(disk_size)\n w_tophat = black_tophat(normalize_slice, footprint)\n w_tophat = np.uint8(255 * w_tophat)\n return w_tophat[:, :, np.newaxis]\n\ndef aply_black_tophat_to_folder(original_folder_path, destination_folder_path, disk_size):\n \"\"\"\n Aply black tophat to folder.\n\n Args:\n original_folder_path (_type_): Original folder path.\n destination_folder_path (_type_): Destination folder path.\n disk_size (_type_): Disk size.\n \"\"\"\n list_images_paths = glob.glob(original_folder_path + \"*\")\n for current_image_path in list_images_paths:\n image_name = current_image_path.split('\\\\')[-1]\n print(\"Current_image: {}\".format(current_image_path))\n result_image = aply_black_tophat_to_image(original_image_path=current_image_path, disk_size=disk_size)\n tf.keras.utils.save_img(\n path=\"{}seg_version_{}\".format(destination_folder_path, image_name),\n x=result_image, \n data_format=None, \n file_format='png', \n scale=True\n )\n"
] |
[
[
"tensorflow.keras.preprocessing.image.load_img",
"numpy.true_divide",
"tensorflow.keras.preprocessing.image.array_to_img",
"numpy.uint8",
"tensorflow.GradientTape",
"tensorflow.argmax",
"tensorflow.squeeze",
"numpy.arange",
"matplotlib.pyplot.axis",
"numpy.expand_dims",
"matplotlib.pyplot.subplot",
"matplotlib.cm.get_cmap",
"matplotlib.pyplot.title",
"numpy.random.shuffle",
"matplotlib.pyplot.figure",
"tensorflow.keras.preprocessing.image.img_to_array",
"numpy.random.seed",
"tensorflow.math.reduce_max",
"tensorflow.maximum",
"tensorflow.reduce_mean",
"matplotlib.pyplot.imshow"
]
] |
JoshDumo/qiskit-terra
|
[
"6a2602a9ecf9b1a3345de1516b873ac7b3da587f"
] |
[
"test/python/circuit/test_circuit_properties.py"
] |
[
"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2018.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Test Qiskit's inverse gate operation.\"\"\"\n\nimport unittest\nimport numpy as np\nfrom qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, pulse\nfrom qiskit.circuit import Clbit\nfrom qiskit.circuit.library import RXGate, RYGate\nfrom qiskit.test import QiskitTestCase\nfrom qiskit.circuit.exceptions import CircuitError\nfrom qiskit.extensions.simulator import Snapshot\n\n\nclass TestCircuitProperties(QiskitTestCase):\n \"\"\"QuantumCircuit properties tests.\"\"\"\n\n def test_qarg_numpy_int(self):\n \"\"\"Test castable to integer args for QuantumCircuit.\"\"\"\n n = np.int64(12)\n qc1 = QuantumCircuit(n)\n self.assertEqual(qc1.num_qubits, 12)\n self.assertEqual(type(qc1), QuantumCircuit)\n\n def test_carg_numpy_int(self):\n \"\"\"Test castable to integer cargs for QuantumCircuit.\"\"\"\n n = np.int64(12)\n c1 = ClassicalRegister(n)\n qc1 = QuantumCircuit(c1)\n c_regs = qc1.cregs\n self.assertEqual(c_regs[0], c1)\n self.assertEqual(type(qc1), QuantumCircuit)\n\n def test_carg_numpy_int_2(self):\n \"\"\"Test castable to integer cargs for QuantumCircuit.\"\"\"\n qc1 = QuantumCircuit(12, np.int64(12))\n self.assertEqual(len(qc1.clbits), 12)\n self.assertTrue(all(isinstance(bit, Clbit) for bit in qc1.clbits))\n self.assertEqual(type(qc1), QuantumCircuit)\n\n def test_qarg_numpy_int_exception(self):\n \"\"\"Test attempt to pass non-castable arg to QuantumCircuit.\"\"\"\n self.assertRaises(CircuitError, QuantumCircuit, \"string\")\n\n def test_warning_on_noninteger_float(self):\n \"\"\"Test warning when passing non-integer float to QuantumCircuit\"\"\"\n self.assertRaises(CircuitError, QuantumCircuit, 2.2)\n # but an integer float should pass\n qc = QuantumCircuit(2.0)\n self.assertEqual(qc.num_qubits, 2)\n\n def test_circuit_depth_empty(self):\n \"\"\"Test depth of empty circuity\"\"\"\n q = QuantumRegister(5, \"q\")\n qc = QuantumCircuit(q)\n self.assertEqual(qc.depth(), 0)\n\n def test_circuit_depth_no_reg(self):\n \"\"\"Test depth of no register circuits\"\"\"\n qc = QuantumCircuit()\n self.assertEqual(qc.depth(), 0)\n\n def test_circuit_depth_meas_only(self):\n \"\"\"Test depth of measurement only\"\"\"\n q = QuantumRegister(1, \"q\")\n c = ClassicalRegister(1, \"c\")\n qc = QuantumCircuit(q, c)\n qc.measure(q, c)\n self.assertEqual(qc.depth(), 1)\n\n def test_circuit_depth_barrier(self):\n \"\"\"Make sure barriers do not add to depth\"\"\"\n q = QuantumRegister(5, \"q\")\n c = ClassicalRegister(5, \"c\")\n qc = QuantumCircuit(q, c)\n qc.h(q[0])\n qc.h(q[1])\n qc.h(q[2])\n qc.h(q[3])\n qc.h(q[4])\n qc.cx(q[0], q[1])\n qc.cx(q[1], q[4])\n qc.cx(q[4], q[2])\n qc.cx(q[2], q[3])\n qc.barrier(q)\n qc.measure(q, c)\n self.assertEqual(qc.depth(), 6)\n\n def test_circuit_depth_simple(self):\n \"\"\"Test depth for simple circuit\"\"\"\n q = QuantumRegister(5, \"q\")\n c = ClassicalRegister(1, \"c\")\n qc = QuantumCircuit(q, c)\n qc.h(q[0])\n qc.cx(q[0], q[4])\n qc.x(q[2])\n qc.x(q[2])\n qc.x(q[2])\n qc.x(q[4])\n qc.cx(q[4], q[1])\n qc.measure(q[1], c[0])\n self.assertEqual(qc.depth(), 5)\n\n def test_circuit_depth_multi_reg(self):\n \"\"\"Test depth for multiple registers\"\"\"\n q1 = QuantumRegister(3, \"q1\")\n q2 = QuantumRegister(2, \"q2\")\n c = ClassicalRegister(5, \"c\")\n qc = QuantumCircuit(q1, q2, c)\n qc.h(q1[0])\n qc.h(q1[1])\n qc.h(q1[2])\n qc.h(q2[0])\n qc.h(q2[1])\n qc.cx(q1[0], q1[1])\n qc.cx(q1[1], q2[1])\n qc.cx(q2[1], q1[2])\n qc.cx(q1[2], q2[0])\n self.assertEqual(qc.depth(), 5)\n\n def test_circuit_depth_3q_gate(self):\n \"\"\"Test depth for 3q gate\"\"\"\n q1 = QuantumRegister(3, \"q1\")\n q2 = QuantumRegister(2, \"q2\")\n c = ClassicalRegister(5, \"c\")\n qc = QuantumCircuit(q1, q2, c)\n qc.h(q1[0])\n qc.h(q1[1])\n qc.h(q1[2])\n qc.h(q2[0])\n qc.h(q2[1])\n qc.ccx(q2[1], q1[0], q2[0])\n qc.cx(q1[0], q1[1])\n qc.cx(q1[1], q2[1])\n qc.cx(q2[1], q1[2])\n qc.cx(q1[2], q2[0])\n self.assertEqual(qc.depth(), 6)\n\n def test_circuit_depth_conditionals1(self):\n \"\"\"Test circuit depth for conditional gates #1.\"\"\"\n size = 4\n q = QuantumRegister(size, \"q\")\n c = ClassicalRegister(size, \"c\")\n qc = QuantumCircuit(q, c)\n\n qc.h(q[0])\n qc.h(q[1])\n qc.h(q[2])\n qc.h(q[3])\n qc.cx(q[0], q[1])\n qc.cx(q[2], q[3])\n qc.measure(q[0], c[0])\n qc.measure(q[1], c[1])\n qc.h(q[2]).c_if(c, 2)\n qc.h(q[3]).c_if(c, 4)\n self.assertEqual(qc.depth(), 5)\n\n def test_circuit_depth_conditionals2(self):\n \"\"\"Test circuit depth for conditional gates #2.\"\"\"\n size = 4\n q = QuantumRegister(size, \"q\")\n c = ClassicalRegister(size, \"c\")\n qc = QuantumCircuit(q, c)\n\n qc.h(q[0])\n qc.h(q[1])\n qc.h(q[2])\n qc.h(q[3])\n qc.cx(q[0], q[1])\n qc.cx(q[2], q[3])\n qc.measure(q[0], c[0])\n qc.measure(q[0], c[0])\n qc.h(q[2]).c_if(c, 2)\n qc.h(q[3]).c_if(c, 4)\n self.assertEqual(qc.depth(), 6)\n\n def test_circuit_depth_conditionals3(self):\n \"\"\"Test circuit depth for conditional gates #3.\"\"\"\n size = 4\n q = QuantumRegister(size, \"q\")\n c = ClassicalRegister(size, \"c\")\n qc = QuantumCircuit(q, c)\n\n qc.h(q[0])\n qc.h(q[1])\n qc.h(q[2])\n qc.h(q[3])\n qc.measure(q[0], c[0])\n qc.cx(q[0], q[3]).c_if(c, 2)\n\n qc.measure(q[1], c[1])\n qc.measure(q[2], c[2])\n qc.measure(q[3], c[3])\n self.assertEqual(qc.depth(), 4)\n\n def test_circuit_depth_measurements1(self):\n \"\"\"Test circuit depth for measurements #1.\"\"\"\n size = 4\n q = QuantumRegister(size, \"q\")\n c = ClassicalRegister(size, \"c\")\n qc = QuantumCircuit(q, c)\n\n qc.h(q[0])\n qc.h(q[1])\n qc.h(q[2])\n qc.h(q[3])\n qc.measure(q[0], c[0])\n qc.measure(q[1], c[1])\n qc.measure(q[2], c[2])\n qc.measure(q[3], c[3])\n self.assertEqual(qc.depth(), 2)\n\n def test_circuit_depth_measurements2(self):\n \"\"\"Test circuit depth for measurements #2.\"\"\"\n size = 4\n q = QuantumRegister(size, \"q\")\n c = ClassicalRegister(size, \"c\")\n qc = QuantumCircuit(q, c)\n\n qc.h(q[0])\n qc.h(q[1])\n qc.h(q[2])\n qc.h(q[3])\n qc.measure(q[0], c[0])\n qc.measure(q[0], c[1])\n qc.measure(q[0], c[2])\n qc.measure(q[0], c[3])\n self.assertEqual(qc.depth(), 5)\n\n def test_circuit_depth_measurements3(self):\n \"\"\"Test circuit depth for measurements #3.\"\"\"\n size = 4\n q = QuantumRegister(size, \"q\")\n c = ClassicalRegister(size, \"c\")\n qc = QuantumCircuit(q, c)\n\n qc.h(q[0])\n qc.h(q[1])\n qc.h(q[2])\n qc.h(q[3])\n qc.measure(q[0], c[0])\n qc.measure(q[1], c[0])\n qc.measure(q[2], c[0])\n qc.measure(q[3], c[0])\n self.assertEqual(qc.depth(), 5)\n\n def test_circuit_depth_barriers1(self):\n \"\"\"Test circuit depth for barriers #1.\"\"\"\n q = QuantumRegister(4, \"q\")\n c = ClassicalRegister(4, \"c\")\n circ = QuantumCircuit(q, c)\n circ.h(0)\n circ.cx(0, 1)\n circ.barrier(q)\n circ.h(2)\n circ.cx(2, 3)\n self.assertEqual(circ.depth(), 4)\n\n def test_circuit_depth_barriers2(self):\n \"\"\"Test circuit depth for barriers #2.\"\"\"\n q = QuantumRegister(4, \"q\")\n c = ClassicalRegister(4, \"c\")\n circ = QuantumCircuit(q, c)\n circ.h(0)\n circ.barrier(q)\n circ.cx(0, 1)\n circ.barrier(q)\n circ.h(2)\n circ.barrier(q)\n circ.cx(2, 3)\n self.assertEqual(circ.depth(), 4)\n\n def test_circuit_depth_barriers3(self):\n \"\"\"Test circuit depth for barriers #3.\"\"\"\n q = QuantumRegister(4, \"q\")\n c = ClassicalRegister(4, \"c\")\n circ = QuantumCircuit(q, c)\n circ.h(0)\n circ.barrier(q)\n circ.cx(0, 1)\n circ.barrier(q)\n circ.barrier(q)\n circ.barrier(q)\n circ.h(2)\n circ.barrier(q)\n circ.cx(2, 3)\n self.assertEqual(circ.depth(), 4)\n\n def test_circuit_depth_snap1(self):\n \"\"\"Test circuit depth for snapshots #1.\"\"\"\n q = QuantumRegister(4, \"q\")\n c = ClassicalRegister(4, \"c\")\n circ = QuantumCircuit(q, c)\n circ.h(0)\n circ.cx(0, 1)\n circ.append(Snapshot(\"snap\", num_qubits=4), [0, 1, 2, 3])\n circ.h(2)\n circ.cx(2, 3)\n self.assertEqual(circ.depth(), 4)\n\n def test_circuit_depth_snap2(self):\n \"\"\"Test circuit depth for snapshots #2.\"\"\"\n q = QuantumRegister(4, \"q\")\n c = ClassicalRegister(4, \"c\")\n circ = QuantumCircuit(q, c)\n circ.h(0)\n circ.append(Snapshot(\"snap0\", num_qubits=4), [0, 1, 2, 3])\n circ.cx(0, 1)\n circ.append(Snapshot(\"snap1\", num_qubits=4), [0, 1, 2, 3])\n circ.h(2)\n circ.append(Snapshot(\"snap2\", num_qubits=4), [0, 1, 2, 3])\n circ.cx(2, 3)\n self.assertEqual(circ.depth(), 4)\n\n def test_circuit_depth_snap3(self):\n \"\"\"Test circuit depth for snapshots #3.\"\"\"\n q = QuantumRegister(4, \"q\")\n c = ClassicalRegister(4, \"c\")\n circ = QuantumCircuit(q, c)\n circ.h(0)\n circ.cx(0, 1)\n circ.append(Snapshot(\"snap0\", num_qubits=4), [0, 1, 2, 3])\n circ.append(Snapshot(\"snap1\", num_qubits=4), [0, 1, 2, 3])\n circ.h(2)\n circ.cx(2, 3)\n self.assertEqual(circ.depth(), 4)\n\n def test_circuit_size_empty(self):\n \"\"\"Circuit.size should return 0 for an empty circuit.\"\"\"\n size = 4\n q = QuantumRegister(size, \"q\")\n c = ClassicalRegister(size, \"c\")\n qc = QuantumCircuit(q, c)\n\n self.assertEqual(qc.size(), 0)\n\n def test_circuit_size_single_qubit_gates(self):\n \"\"\"Circuit.size should increment for each added single qubit gate.\"\"\"\n size = 4\n q = QuantumRegister(size, \"q\")\n c = ClassicalRegister(size, \"c\")\n qc = QuantumCircuit(q, c)\n\n qc.h(q[0])\n self.assertEqual(qc.size(), 1)\n qc.h(q[1])\n self.assertEqual(qc.size(), 2)\n\n def test_circuit_size_two_qubit_gates(self):\n \"\"\"Circuit.size should increment for each added two qubit gate.\"\"\"\n size = 4\n q = QuantumRegister(size, \"q\")\n c = ClassicalRegister(size, \"c\")\n qc = QuantumCircuit(q, c)\n\n qc.cx(q[0], q[1])\n self.assertEqual(qc.size(), 1)\n qc.cx(q[2], q[3])\n self.assertEqual(qc.size(), 2)\n\n def test_circuit_size_ignores_barriers_snapshots(self):\n \"\"\"Circuit.size should not count barriers or snapshots.\"\"\"\n q = QuantumRegister(4, \"q\")\n c = ClassicalRegister(4, \"c\")\n qc = QuantumCircuit(q, c)\n\n qc.h(q[0])\n qc.cx(q[0], q[1])\n self.assertEqual(qc.size(), 2)\n qc.barrier(q)\n self.assertEqual(qc.size(), 2)\n qc.append(Snapshot(\"snapshot_label\", num_qubits=4), [0, 1, 2, 3])\n self.assertEqual(qc.size(), 2)\n\n def test_circuit_count_ops(self):\n \"\"\"Test circuit count ops.\"\"\"\n q = QuantumRegister(6, \"q\")\n qc = QuantumCircuit(q)\n qc.h(q)\n qc.x(q[1])\n qc.y(q[2:4])\n qc.z(q[3:])\n result = qc.count_ops()\n\n expected = dict([(\"h\", 6), (\"z\", 3), (\"y\", 2), (\"x\", 1)])\n\n self.assertIsInstance(result, dict)\n self.assertEqual(expected, result)\n\n def test_circuit_nonlocal_gates(self):\n \"\"\"Test num_nonlocal_gates.\"\"\"\n q = QuantumRegister(6, \"q\")\n c = ClassicalRegister(2, \"c\")\n qc = QuantumCircuit(q, c)\n qc.h(q)\n qc.x(q[1])\n qc.cry(0.1, q[2], q[4])\n qc.z(q[3:])\n qc.cswap(q[1], q[2], q[3])\n qc.iswap(q[0], q[4]).c_if(c, 2)\n result = qc.num_nonlocal_gates()\n expected = 3\n self.assertEqual(expected, result)\n\n def test_circuit_nonlocal_gates_no_instruction(self):\n \"\"\"Verify num_nunlocal_gates does not include barriers.\"\"\"\n # ref: https://github.com/Qiskit/qiskit-terra/issues/4500\n n = 3\n qc = QuantumCircuit(n)\n qc.h(range(n))\n\n qc.barrier()\n\n self.assertEqual(qc.num_nonlocal_gates(), 0)\n\n def test_circuit_connected_components_empty(self):\n \"\"\"Verify num_connected_components is width for empty\"\"\"\n q = QuantumRegister(7, \"q\")\n qc = QuantumCircuit(q)\n self.assertEqual(7, qc.num_connected_components())\n\n def test_circuit_connected_components_multi_reg(self):\n \"\"\"Test tensor factors works over multi registers\"\"\"\n q1 = QuantumRegister(3, \"q1\")\n q2 = QuantumRegister(2, \"q2\")\n qc = QuantumCircuit(q1, q2)\n qc.h(q1[0])\n qc.h(q1[1])\n qc.h(q1[2])\n qc.h(q2[0])\n qc.h(q2[1])\n qc.cx(q1[0], q1[1])\n qc.cx(q1[1], q2[1])\n qc.cx(q2[1], q1[2])\n qc.cx(q1[2], q2[0])\n self.assertEqual(qc.num_connected_components(), 1)\n\n def test_circuit_connected_components_multi_reg2(self):\n \"\"\"Test tensor factors works over multi registers #2.\"\"\"\n q1 = QuantumRegister(3, \"q1\")\n q2 = QuantumRegister(2, \"q2\")\n qc = QuantumCircuit(q1, q2)\n qc.cx(q1[0], q2[1])\n qc.cx(q2[0], q1[2])\n qc.cx(q1[1], q2[0])\n self.assertEqual(qc.num_connected_components(), 2)\n\n def test_circuit_connected_components_disconnected(self):\n \"\"\"Test tensor factors works with 2q subspaces.\"\"\"\n q1 = QuantumRegister(5, \"q1\")\n q2 = QuantumRegister(5, \"q2\")\n qc = QuantumCircuit(q1, q2)\n qc.cx(q1[0], q2[4])\n qc.cx(q1[1], q2[3])\n qc.cx(q1[2], q2[2])\n qc.cx(q1[3], q2[1])\n qc.cx(q1[4], q2[0])\n self.assertEqual(qc.num_connected_components(), 5)\n\n def test_circuit_connected_components_with_clbits(self):\n \"\"\"Test tensor components with classical register.\"\"\"\n size = 4\n q = QuantumRegister(size, \"q\")\n c = ClassicalRegister(size, \"c\")\n qc = QuantumCircuit(q, c)\n qc.h(q[0])\n qc.h(q[1])\n qc.h(q[2])\n qc.h(q[3])\n qc.measure(q[0], c[0])\n qc.measure(q[1], c[1])\n qc.measure(q[2], c[2])\n qc.measure(q[3], c[3])\n self.assertEqual(qc.num_connected_components(), 4)\n\n def test_circuit_connected_components_with_cond(self):\n \"\"\"Test tensor components with conditional gate.\"\"\"\n size = 4\n q = QuantumRegister(size, \"q\")\n c = ClassicalRegister(size, \"c\")\n qc = QuantumCircuit(q, c)\n qc.h(q[0])\n qc.h(q[1])\n qc.h(q[2])\n qc.h(q[3])\n qc.measure(q[0], c[0])\n qc.cx(q[0], q[3]).c_if(c, 2)\n qc.measure(q[1], c[1])\n qc.measure(q[2], c[2])\n qc.measure(q[3], c[3])\n self.assertEqual(qc.num_connected_components(), 1)\n\n def test_circuit_unitary_factors1(self):\n \"\"\"Test unitary factors empty circuit.\"\"\"\n size = 4\n q = QuantumRegister(size, \"q\")\n c = ClassicalRegister(size, \"c\")\n qc = QuantumCircuit(q, c)\n self.assertEqual(qc.num_unitary_factors(), 4)\n\n def test_circuit_unitary_factors2(self):\n \"\"\"Test unitary factors multi qregs\"\"\"\n q1 = QuantumRegister(2, \"q1\")\n q2 = QuantumRegister(2, \"q2\")\n c = ClassicalRegister(4, \"c\")\n qc = QuantumCircuit(q1, q2, c)\n self.assertEqual(qc.num_unitary_factors(), 4)\n\n def test_circuit_unitary_factors3(self):\n \"\"\"Test unitary factors measurements and conditionals.\"\"\"\n size = 4\n q = QuantumRegister(size, \"q\")\n c = ClassicalRegister(size, \"c\")\n qc = QuantumCircuit(q, c)\n qc.h(q[0])\n qc.h(q[1])\n qc.h(q[2])\n qc.h(q[3])\n qc.cx(q[1], q[2])\n qc.cx(q[1], q[2])\n qc.cx(q[0], q[3]).c_if(c, 2)\n qc.cx(q[0], q[3])\n qc.cx(q[0], q[3])\n qc.cx(q[0], q[3])\n qc.measure(q[0], c[0])\n qc.measure(q[1], c[1])\n qc.measure(q[2], c[2])\n qc.measure(q[3], c[3])\n self.assertEqual(qc.num_unitary_factors(), 2)\n\n def test_circuit_unitary_factors4(self):\n \"\"\"Test unitary factors measurements go to same cbit.\"\"\"\n size = 5\n q = QuantumRegister(size, \"q\")\n c = ClassicalRegister(size, \"c\")\n qc = QuantumCircuit(q, c)\n qc.h(q[0])\n qc.h(q[1])\n qc.h(q[2])\n qc.h(q[3])\n qc.measure(q[0], c[0])\n qc.measure(q[1], c[0])\n qc.measure(q[2], c[0])\n qc.measure(q[3], c[0])\n self.assertEqual(qc.num_unitary_factors(), 5)\n\n def test_num_qubits_qubitless_circuit(self):\n \"\"\"Check output in absence of qubits.\"\"\"\n c_reg = ClassicalRegister(3)\n circ = QuantumCircuit(c_reg)\n self.assertEqual(circ.num_qubits, 0)\n\n def test_num_qubits_qubitfull_circuit(self):\n \"\"\"Check output in presence of qubits\"\"\"\n q_reg = QuantumRegister(4)\n c_reg = ClassicalRegister(3)\n circ = QuantumCircuit(q_reg, c_reg)\n self.assertEqual(circ.num_qubits, 4)\n\n def test_num_qubits_registerless_circuit(self):\n \"\"\"Check output for circuits with direct argument for qubits.\"\"\"\n circ = QuantumCircuit(5)\n self.assertEqual(circ.num_qubits, 5)\n\n def test_num_qubits_multiple_register_circuit(self):\n \"\"\"Check output for circuits with multiple quantum registers.\"\"\"\n q_reg1 = QuantumRegister(5)\n q_reg2 = QuantumRegister(6)\n q_reg3 = QuantumRegister(7)\n circ = QuantumCircuit(q_reg1, q_reg2, q_reg3)\n self.assertEqual(circ.num_qubits, 18)\n\n def test_calibrations_basis_gates(self):\n \"\"\"Check if the calibrations for basis gates provided are added correctly.\"\"\"\n circ = QuantumCircuit(2)\n\n with pulse.build() as q0_x180:\n pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))\n with pulse.build() as q1_y90:\n pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), pulse.DriveChannel(1))\n\n # Add calibration\n circ.add_calibration(RXGate(3.14), [0], q0_x180)\n circ.add_calibration(RYGate(1.57), [1], q1_y90)\n\n self.assertEqual(set(circ.calibrations.keys()), {\"rx\", \"ry\"})\n self.assertEqual(set(circ.calibrations[\"rx\"].keys()), {((0,), (3.14,))})\n self.assertEqual(set(circ.calibrations[\"ry\"].keys()), {((1,), (1.57,))})\n self.assertEqual(\n circ.calibrations[\"rx\"][((0,), (3.14,))].instructions, q0_x180.instructions\n )\n self.assertEqual(circ.calibrations[\"ry\"][((1,), (1.57,))].instructions, q1_y90.instructions)\n\n def test_calibrations_custom_gates(self):\n \"\"\"Check if the calibrations for custom gates with params provided are added correctly.\"\"\"\n circ = QuantumCircuit(3)\n\n with pulse.build() as q0_x180:\n pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))\n\n # Add calibrations with a custom gate 'rxt'\n circ.add_calibration(\"rxt\", [0], q0_x180, params=[1.57, 3.14, 4.71])\n\n self.assertEqual(set(circ.calibrations.keys()), {\"rxt\"})\n self.assertEqual(set(circ.calibrations[\"rxt\"].keys()), {((0,), (1.57, 3.14, 4.71))})\n self.assertEqual(\n circ.calibrations[\"rxt\"][((0,), (1.57, 3.14, 4.71))].instructions, q0_x180.instructions\n )\n\n def test_calibrations_no_params(self):\n \"\"\"Check calibrations if the no params is provided with just gate name.\"\"\"\n circ = QuantumCircuit(3)\n\n with pulse.build() as q0_x180:\n pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))\n\n circ.add_calibration(\"h\", [0], q0_x180)\n\n self.assertEqual(set(circ.calibrations.keys()), {\"h\"})\n self.assertEqual(set(circ.calibrations[\"h\"].keys()), {((0,), ())})\n self.assertEqual(circ.calibrations[\"h\"][((0,), ())].instructions, q0_x180.instructions)\n\n def test_metadata_copy_does_not_share_state(self):\n \"\"\"Verify mutating the metadata of a circuit copy does not impact original.\"\"\"\n # ref: https://github.com/Qiskit/qiskit-terra/issues/6057\n\n qc1 = QuantumCircuit(1)\n qc1.metadata = {\"a\": 0}\n\n qc2 = qc1.copy()\n qc2.metadata[\"a\"] = 1000\n\n self.assertEqual(qc1.metadata[\"a\"], 0)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] |
[
[
"numpy.int64"
]
] |
JackLonergan97/SOLikeT
|
[
"314fe3df3a3ccdda69a2b1142b433c5dd5997e44"
] |
[
"soliket/gaussian.py"
] |
[
"import numpy as np\nfrom typing import Optional, Sequence\n\nfrom cobaya.likelihood import Likelihood\nfrom cobaya.input import merge_info\nfrom cobaya.tools import recursive_update\n# from cobaya.conventions import empty_dict\n\nfrom collections import namedtuple\nfrom types import MappingProxyType\nempty_dict = MappingProxyType({})\n\nfrom .gaussian_data import GaussianData, MultiGaussianData\nfrom .utils import get_likelihood\n\n\nclass GaussianLikelihood(Likelihood):\n name: str = \"Gaussian\"\n datapath: Optional[str] = None\n covpath: Optional[str] = None\n\n def initialize(self):\n x, y = self._get_data()\n cov = self._get_cov()\n self.data = GaussianData(self.name, x, y, cov)\n\n def _get_data(self):\n x, y = np.loadtxt(self.datapath, unpack=True)\n return x, y\n\n def _get_cov(self):\n cov = np.loadtxt(self.covpath)\n return cov\n\n def _get_theory(self, **kwargs):\n raise NotImplementedError\n\n def logp(self, **params_values):\n theory = self._get_theory(**params_values)\n return self.data.loglike(theory)\n\n\nclass CrossCov(dict):\n def save(self, path):\n np.savez(path, **{str(k): v for k, v in self.items()})\n\n @classmethod\n def load(cls, path):\n if path is None:\n return None\n return cls({eval(k): v for k, v in np.load(path).items()})\n\n\nclass MultiGaussianLikelihood(GaussianLikelihood):\n components: Optional[Sequence] = None\n options: Optional[Sequence] = None\n cross_cov_path: Optional[str] = None\n\n def __init__(self, info=empty_dict, **kwargs):\n\n if 'components' in info:\n self.likelihoods = [get_likelihood(*kv) for kv in zip(info['components'], info['options'])]\n\n default_info = merge_info(*[like.get_defaults() for like in self.likelihoods])\n default_info.update(info)\n\n super().__init__(info=default_info, **kwargs)\n\n def initialize(self):\n self.cross_cov = CrossCov.load(self.cross_cov_path)\n\n data_list = [like.data for like in self.likelihoods]\n self.data = MultiGaussianData(data_list, self.cross_cov)\n\n self.log.info('Initialized.')\n\n def initialize_with_provider(self, provider):\n for like in self.likelihoods:\n like.initialize_with_provider(provider)\n # super().initialize_with_provider(provider)\n\n def get_helper_theories(self):\n helpers = {}\n for like in self.likelihoods:\n helpers.update(like.get_helper_theories())\n\n return helpers\n\n def _get_theory(self, **kwargs):\n return np.concatenate([like._get_theory(**kwargs) for like in self.likelihoods])\n\n def get_requirements(self):\n\n # Reqs with arguments like 'lmax', etc. may have to be carefully treated here to merge\n reqs = {}\n for like in self.likelihoods:\n new_reqs = like.get_requirements()\n\n # Deal with special cases requiring careful merging\n # Make sure the max of the lmax/union of Cls is taken.\n # (should make a unit test for this)\n if \"Cl\" in new_reqs and \"Cl\" in reqs:\n new_cl_spec = new_reqs[\"Cl\"]\n old_cl_spec = reqs[\"Cl\"]\n merged_cl_spec = {}\n all_keys = set(new_cl_spec.keys()).union(set(old_cl_spec.keys()))\n for k in all_keys:\n new_lmax = new_cl_spec.get(k, 0)\n old_lmax = old_cl_spec.get(k, 0)\n merged_cl_spec[k] = max(new_lmax, old_lmax)\n new_reqs[\"Cl\"] = merged_cl_spec\n\n reqs = recursive_update(reqs, new_reqs)\n return reqs\n"
] |
[
[
"numpy.loadtxt",
"numpy.load"
]
] |
yanhann10/afprop
|
[
"e7ebf8541d5224f417eb4e9209cf5012ebfe78b7"
] |
[
"tests/test_afprop.py"
] |
[
"import numpy as np\nimport pandas as pd\nimport pytest\nfrom afprop import afprop_vec\n\n\n# sample data with clusters for testing\nC1 = np.random.multivariate_normal(mean=[0, 0], cov=np.eye(2), size=30)\nC2 = np.random.multivariate_normal(mean=[4, 4], cov=np.eye(2), size=30)\nmydata = np.r_[C1, C2]\n\n\ndef test_n_cluster():\n # test n_cluster equals #unique cluster labels\n clusters, exemplars, cluster_plot, num_clusters, final_iter = afprop_vec(\n mydata=mydata\n )\n assert len(set(clusters)) == num_clusters\n assert num_clusters == 2\n\n\ndef test_cluster_pref():\n # test valid specification of cluster preference\n with pytest.raises(ValueError):\n afprop_vec(mydata=mydata, num_cluster_pref=0)\n\n\ndef test_valid_damping():\n # test valid specification of cluster preference\n with pytest.raises(ValueError):\n afprop_vec(mydata=mydata, damp_c=2)\n"
] |
[
[
"numpy.eye"
]
] |
dani-lbnl/chainercv
|
[
"223fab7dd0045d57db02041d44368fe3e60ea433"
] |
[
"chainercv/datasets/cityscapes/cityscapes_semantic_segmentation_dataset.py"
] |
[
"import glob\nimport os\n\nimport numpy as np\n\nfrom chainer import dataset\nfrom chainer.dataset import download\nfrom chainercv.datasets.cityscapes.cityscapes_utils import cityscapes_labels\nfrom chainercv.utils import read_image\n\n\nclass CityscapesSemanticSegmentationDataset(dataset.DatasetMixin):\n\n \"\"\"Dataset class for a semantic segmentation task on `Cityscapes dataset`_.\n\n .. _`Cityscapes dataset`: https://www.cityscapes-dataset.com\n\n .. note::\n\n Please manually downalod the data because it is not allowed to\n re-distribute Cityscapes dataset.\n\n Args:\n data_dir (string): Path to the dataset directory. The directory should\n contain at least two directories, :obj:`leftImg8bit` and either\n :obj:`gtFine` or :obj:`gtCoarse`. If :obj:`None` is given, it uses\n :obj:`$CHAINER_DATSET_ROOT/pfnet/chainercv/cityscapes` by default.\n label_resolution ({'fine', 'coarse'}): The resolution of the labels. It\n should be either :obj:`fine` or :obj:`coarse`.\n split ({'train', 'val'}): Select from dataset splits used in\n Cityscapes dataset.\n ignore_labels (bool): If True, the labels marked :obj:`ignoreInEval`\n defined in the original\n `cityscapesScripts<https://github.com/mcordts/cityscapesScripts>_`\n will be replaced with :obj:`-1` in the :meth:`get_example` method.\n The default value is :obj:`True`.\n\n \"\"\"\n\n def __init__(self, data_dir=None, label_resolution=None, split='train',\n ignore_labels=True):\n if data_dir is None:\n data_dir = download.get_dataset_directory(\n 'pfnet/chainercv/cityscapes')\n if label_resolution not in ['fine', 'coarse']:\n raise ValueError('\\'label_resolution\\' argment should be eighter '\n '\\'fine\\' or \\'coarse\\'.')\n\n img_dir = os.path.join(data_dir, os.path.join('leftImg8bit', split))\n resol = 'gtFine' if label_resolution == 'fine' else 'gtCoarse'\n label_dir = os.path.join(data_dir, resol)\n if not os.path.exists(img_dir) or not os.path.exists(label_dir):\n raise ValueError(\n 'Cityscapes dataset does not exist at the expected location.'\n 'Please download it from https://www.cityscapes-dataset.com/.'\n 'Then place directory leftImg8bit at {} and {} at {}.'.format(\n os.path.join(data_dir, 'leftImg8bit'), resol, label_dir))\n\n self.ignore_labels = ignore_labels\n\n self.label_paths = list()\n self.img_paths = list()\n city_dnames = list()\n for dname in glob.glob(os.path.join(label_dir, '*')):\n if split in dname:\n for city_dname in glob.glob(os.path.join(dname, '*')):\n for label_path in glob.glob(\n os.path.join(city_dname, '*_labelIds.png')):\n self.label_paths.append(label_path)\n city_dnames.append(os.path.basename(city_dname))\n for city_dname, label_path in zip(city_dnames, self.label_paths):\n label_path = os.path.basename(label_path)\n img_path = label_path.replace(\n '{}_labelIds'.format(resol), 'leftImg8bit')\n img_path = os.path.join(img_dir, city_dname, img_path)\n self.img_paths.append(img_path)\n\n def __len__(self):\n return len(self.img_paths)\n\n def get_example(self, i):\n \"\"\"Returns the i-th example.\n\n Returns a color image and a label image. The color image is in CHW\n format and the label image is in HW format.\n\n Args:\n i (int): The index of the example.\n\n Returns:\n tuple of a color image and a label whose shapes are (3, H, W) and\n (H, W) respectively. H and W are height and width of the image.\n The dtype of the color image is :obj:`numpy.float32` and\n the dtype of the label image is :obj:`numpy.int32`.\n\n \"\"\"\n img = read_image(self.img_paths[i])\n label_orig = read_image(\n self.label_paths[i], dtype=np.int32, color=False)[0]\n if self.ignore_labels:\n label_out = np.ones(label_orig.shape, dtype=np.int32) * -1\n for label in cityscapes_labels:\n if not label.ignoreInEval:\n label_out[label_orig == label.id] = label.trainId\n else:\n label_out = label_orig\n return img, label_out\n"
] |
[
[
"numpy.ones"
]
] |
faheemali1997/SelfDrivingCar
|
[
"386cdaa063d51dab0409a114fa4b8a3a26b22302"
] |
[
"pyipcam.py"
] |
[
"import cv2\nimport urllib2\nimport numpy as np\nimport sys\n\nhost = \"192.168.0.220:8080\"\nif len(sys.argv)>1:\n host = sys.argv[1]\n\nhoststr = 'http://' + host + '/video'\nprint ('Streaming ' + hoststr)\n\nstream=urllib2.urlopen(hoststr)\n\nbytes=''\nwhile True:\n bytes+=stream.read(1024)\n a = bytes.find('\\xff\\xd8')\n b = bytes.find('\\xff\\xd9')\n if a!=-1 and b!=-1:\n jpg = bytes[a:b+2]\n bytes= bytes[b+2:]\n i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR)\n cv2.imshow(hoststr,i)\n if cv2.waitKey(1) ==27:\n exit(0)"
] |
[
[
"numpy.fromstring"
]
] |
NeerajBhadani/tensorflow
|
[
"8c849c65503fef22f49f7ab843803fca9c439bdf"
] |
[
"tensorflow/python/framework/sparse_tensor_test.py"
] |
[
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Tests for tensorflow.python.framework.sparse_tensor.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.platform import googletest\n\n\nclass SparseTensorTest(test_util.TensorFlowTestCase):\n\n def testPythonConstruction(self):\n indices = [[1, 2], [2, 0], [3, 4]]\n values = [b\"a\", b\"b\", b\"c\"]\n shape = [4, 5]\n sp_value = sparse_tensor.SparseTensorValue(indices, values, shape)\n for sp in [\n sparse_tensor.SparseTensor(indices, values, shape),\n sparse_tensor.SparseTensor.from_value(sp_value),\n sparse_tensor.SparseTensor.from_value(\n sparse_tensor.SparseTensor(indices, values, shape))]:\n self.assertEqual(sp.indices.dtype, dtypes.int64)\n self.assertEqual(sp.values.dtype, dtypes.string)\n self.assertEqual(sp.dense_shape.dtype, dtypes.int64)\n self.assertEqual(sp.get_shape(), (4, 5))\n\n with self.cached_session() as sess:\n value = self.evaluate(sp)\n self.assertAllEqual(indices, value.indices)\n self.assertAllEqual(values, value.values)\n self.assertAllEqual(shape, value.dense_shape)\n sess_run_value = self.evaluate(sp)\n self.assertAllEqual(sess_run_value.indices, value.indices)\n self.assertAllEqual(sess_run_value.values, value.values)\n self.assertAllEqual(sess_run_value.dense_shape, value.dense_shape)\n\n def testShape(self):\n\n @def_function.function\n def test_fn(tensor):\n tensor = sparse_ops.sparse_transpose(tensor)\n self.assertEqual(tensor.shape.rank, 2)\n return tensor\n\n tensor = sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]], values=[1., 2], dense_shape=[3, 4])\n test_fn(tensor)\n\n def testIsSparse(self):\n self.assertFalse(sparse_tensor.is_sparse(3))\n self.assertFalse(sparse_tensor.is_sparse(\"foo\"))\n self.assertFalse(sparse_tensor.is_sparse(np.array(3)))\n self.assertTrue(\n sparse_tensor.is_sparse(sparse_tensor.SparseTensor([[0]], [0], [1])))\n self.assertTrue(\n sparse_tensor.is_sparse(\n sparse_tensor.SparseTensorValue([[0]], [0], [1])))\n\n def testConsumers(self):\n with context.graph_mode():\n sp = sparse_tensor.SparseTensor([[0, 0], [1, 2]], [1.0, 3.0], [3, 4])\n w = ops.convert_to_tensor(np.ones([4, 1], np.float32))\n out = sparse_ops.sparse_tensor_dense_matmul(sp, w)\n self.assertEqual(len(sp.consumers()), 1)\n self.assertEqual(sp.consumers()[0], out.op)\n\n dense = sparse_ops.sparse_tensor_to_dense(sp)\n self.assertEqual(len(sp.consumers()), 2)\n self.assertIn(dense.op, sp.consumers())\n self.assertIn(out.op, sp.consumers())\n\n\nclass ConvertToTensorOrSparseTensorTest(test_util.TensorFlowTestCase):\n\n def test_convert_dense(self):\n with self.cached_session():\n value = [42, 43]\n from_value = sparse_tensor.convert_to_tensor_or_sparse_tensor(\n value)\n self.assertAllEqual(value, self.evaluate(from_value))\n\n @test_util.run_deprecated_v1\n def test_convert_sparse(self):\n with self.cached_session():\n indices = [[0, 1], [1, 0]]\n values = [42, 43]\n shape = [2, 2]\n sparse_tensor_value = sparse_tensor.SparseTensorValue(\n indices, values, shape)\n st = sparse_tensor.SparseTensor.from_value(sparse_tensor_value)\n from_value = sparse_tensor.convert_to_tensor_or_sparse_tensor(\n sparse_tensor_value).eval()\n from_tensor = sparse_tensor.convert_to_tensor_or_sparse_tensor(st).eval()\n for convertee in [from_value, from_tensor]:\n self.assertAllEqual(sparse_tensor_value.indices, convertee.indices)\n self.assertAllEqual(sparse_tensor_value.values, convertee.values)\n self.assertAllEqual(\n sparse_tensor_value.dense_shape, convertee.dense_shape)\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass SparseTensorSpecTest(test_util.TensorFlowTestCase,\n parameterized.TestCase):\n\n def assertAllTensorsEqual(self, list1, list2):\n self.assertLen(list1, len(list2))\n for (t1, t2) in zip(list1, list2):\n self.assertAllEqual(t1, t2)\n\n def testConstruction(self):\n spec1 = sparse_tensor.SparseTensorSpec()\n self.assertEqual(spec1.shape.rank, None)\n self.assertEqual(spec1.dtype, dtypes.float32)\n\n spec2 = sparse_tensor.SparseTensorSpec([None, None], dtypes.string)\n self.assertEqual(spec2.shape.as_list(), [None, None])\n self.assertEqual(spec2.dtype, dtypes.string)\n\n def testValueType(self):\n spec1 = sparse_tensor.SparseTensorSpec()\n self.assertEqual(spec1.value_type, sparse_tensor.SparseTensor)\n\n @parameterized.parameters([\n (sparse_tensor.SparseTensorSpec(),\n (tensor_shape.TensorShape(None), dtypes.float32)),\n (sparse_tensor.SparseTensorSpec(shape=[5, None, None]),\n (tensor_shape.TensorShape([5, None, None]), dtypes.float32)),\n (sparse_tensor.SparseTensorSpec(dtype=dtypes.int32),\n (tensor_shape.TensorShape(None), dtypes.int32)),\n ]) # pyformat: disable\n def testSerialize(self, st_spec, expected):\n serialization = st_spec._serialize()\n # TensorShape has an unconventional definition of equality, so we can't use\n # assertEqual directly here. But repr() is deterministic and lossless for\n # the expected values, so we can use that instead.\n self.assertEqual(repr(serialization), repr(expected))\n\n @parameterized.parameters([\n (sparse_tensor.SparseTensorSpec(dtype=dtypes.string), [\n tensor_spec.TensorSpec([None, None], dtypes.int64),\n tensor_spec.TensorSpec([None], dtypes.string),\n tensor_spec.TensorSpec([None], dtypes.int64)\n ]),\n (sparse_tensor.SparseTensorSpec(shape=[5, None, None]), [\n tensor_spec.TensorSpec([None, 3], dtypes.int64),\n tensor_spec.TensorSpec([None], dtypes.float32),\n tensor_spec.TensorSpec([3], dtypes.int64)\n ]),\n ])\n def testComponentSpecs(self, st_spec, expected):\n self.assertEqual(st_spec._component_specs, expected)\n\n @parameterized.parameters([\n {\n \"st_spec\": sparse_tensor.SparseTensorSpec(),\n \"indices\": [[0, 1], [10, 8]],\n \"values\": [3.0, 5.0],\n \"dense_shape\": [100, 100]\n },\n {\n \"st_spec\": sparse_tensor.SparseTensorSpec([100, None, None]),\n \"indices\": [[0, 1, 3], [10, 8, 2]],\n \"values\": [3.0, 5.0],\n \"dense_shape\": [100, 20, 20]\n },\n ])\n def testToFromComponents(self, st_spec, indices, values, dense_shape):\n st = sparse_tensor.SparseTensor(indices, values, dense_shape)\n actual_components = st_spec._to_components(st)\n self.assertAllTensorsEqual(actual_components,\n [indices, values, dense_shape])\n st_reconstructed = st_spec._from_components(actual_components)\n self.assertAllEqual(st.indices, st_reconstructed.indices)\n self.assertAllEqual(st.values, st_reconstructed.values)\n self.assertAllEqual(st.dense_shape, st_reconstructed.dense_shape)\n\n @test_util.run_v1_only(\"SparseTensorValue is deprecated in v2\")\n def testFromNumpyComponents(self):\n indices = np.array([[0], [8]])\n values = np.array([1.0, 9.0])\n dense_shape = np.array([100])\n spec = sparse_tensor.SparseTensorSpec()\n st = spec._from_components([indices, values, dense_shape])\n self.assertIsInstance(st, sparse_tensor.SparseTensorValue)\n self.assertAllEqual(st.indices, indices)\n self.assertAllEqual(st.values, values)\n self.assertAllEqual(st.dense_shape, dense_shape)\n\n @parameterized.parameters([\n sparse_tensor.SparseTensorSpec(dtype=dtypes.string),\n sparse_tensor.SparseTensorSpec(shape=[5, None, None]),\n ])\n def testFlatTensorSpecs(self, st_spec):\n self.assertEqual(st_spec._flat_tensor_specs,\n [tensor_spec.TensorSpec(None, dtypes.variant)])\n\n @parameterized.parameters([\n {\n \"st_spec\": sparse_tensor.SparseTensorSpec(),\n \"indices\": [[0, 1], [10, 8]],\n \"values\": [3.0, 5.0],\n \"dense_shape\": [100, 100]\n },\n {\n \"st_spec\": sparse_tensor.SparseTensorSpec([100, None, None]),\n \"indices\": [[0, 1, 3], [10, 8, 2]],\n \"values\": [3.0, 5.0],\n \"dense_shape\": [100, 20, 20]\n },\n ])\n def testToFromTensorList(self, st_spec, indices, values, dense_shape):\n st = sparse_tensor.SparseTensor(indices, values, dense_shape)\n tensor_list = st_spec._to_tensor_list(st)\n st_reconstructed = st_spec._from_tensor_list(tensor_list)\n self.assertAllEqual(st.indices, st_reconstructed.indices)\n self.assertAllEqual(st.values, st_reconstructed.values)\n self.assertAllEqual(st.dense_shape, st_reconstructed.dense_shape)\n\n @parameterized.parameters([\n (sparse_tensor.SparseTensorSpec([2, None], dtypes.float32), 32,\n sparse_tensor.SparseTensorSpec([32, 2, None], dtypes.float32)),\n (sparse_tensor.SparseTensorSpec([4, None], dtypes.float32), None,\n sparse_tensor.SparseTensorSpec([None, 4, None], dtypes.float32)),\n (sparse_tensor.SparseTensorSpec([2], dtypes.float32), 32,\n sparse_tensor.SparseTensorSpec([32, 2], dtypes.float32)),\n ])\n def testBatch(self, spec, batch_size, expected):\n self.assertEqual(spec._batch(batch_size), expected)\n\n @parameterized.parameters([\n (sparse_tensor.SparseTensorSpec([32, None, None], dtypes.float32),\n sparse_tensor.SparseTensorSpec([None, None], dtypes.float32)),\n (sparse_tensor.SparseTensorSpec([None, None, None], dtypes.float32),\n sparse_tensor.SparseTensorSpec([None, None], dtypes.float32)),\n (sparse_tensor.SparseTensorSpec([32, 2], dtypes.float32),\n sparse_tensor.SparseTensorSpec([2], dtypes.float32)),\n ])\n def testUnbatch(self, spec, expected):\n self.assertEqual(spec._unbatch(), expected)\n\n\nif __name__ == \"__main__\":\n googletest.main()\n"
] |
[
[
"tensorflow.python.ops.sparse_ops.sparse_tensor_dense_matmul",
"tensorflow.python.framework.sparse_tensor.is_sparse",
"numpy.array",
"tensorflow.python.eager.context.graph_mode",
"tensorflow.python.platform.googletest.main",
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.python.ops.sparse_ops.sparse_transpose",
"tensorflow.python.framework.sparse_tensor.convert_to_tensor_or_sparse_tensor",
"tensorflow.python.ops.sparse_ops.sparse_tensor_to_dense",
"numpy.ones",
"tensorflow.python.framework.sparse_tensor.SparseTensor.from_value",
"tensorflow.python.framework.tensor_spec.TensorSpec",
"tensorflow.python.framework.sparse_tensor.SparseTensorValue",
"tensorflow.python.framework.test_util.run_v1_only",
"tensorflow.python.framework.sparse_tensor.SparseTensor",
"tensorflow.python.framework.sparse_tensor.SparseTensorSpec"
]
] |
scottrdavid/landlab
|
[
"bb8414df55b4e5fb9198468fadbe3c725ef60601"
] |
[
"tests/io/shapefile/test_infer_dtype.py"
] |
[
"import hypothesis.extra.numpy as hynp\nimport numpy as np\nimport pytest\nfrom hypothesis import assume, given\nfrom hypothesis.strategies import integers\nfrom numpy.testing import assert_array_equal\n\nfrom landlab.io.shapefile.read_shapefile import _infer_data_type\n\n\n@pytest.mark.parametrize(\"src_type\", [np.int32, np.int64, float, bool])\n@pytest.mark.parametrize(\"as_iterable\", [list, tuple, np.asarray])\ndef test_infer_dtype(as_iterable, src_type):\n values = np.asarray([1, 2, 3], dtype=src_type)\n array = _infer_data_type(as_iterable(values))\n assert array.dtype == src_type\n assert_array_equal(array, values)\n\n\n@pytest.mark.parametrize(\n \"values,dst_type\",\n [\n ([1, 2, 3], np.int_),\n ([1, 2, 3.0], float),\n ([1.0, 2.0, 3.0], float),\n ([1j, 2j, 3j], complex),\n ([True, True, False], bool),\n ],\n)\ndef test_infer_dtype_from_object(values, dst_type):\n values = np.asarray(values, dtype=object)\n array = _infer_data_type(values)\n assert array.dtype == dst_type\n assert_array_equal(array, values)\n\n\n@pytest.mark.parametrize(\n \"values,dst_type,expected\",\n [\n ([1, 2, 3.0], float, [1.0, 2.0, 3.0]),\n ([1.0, 2.0, 3j], complex, [1 + 0j, 2 + 0j, 3j]),\n ([1, 2, 3j], complex, [1 + 0j, 2 + 0j, 3j]),\n ([True, False, 1], int, [1, 0, 1]),\n ([True, False, 1.0], float, [1.0, 0.0, 1.0]),\n ([None, 1.0, 2.0], float, [np.nan, 1.0, 2.0]),\n ([None, 1.0, 2j], complex, [np.nan * 1j, 1.0, 2j]),\n ],\n)\ndef test_infer_dtype_from_mixed(values, dst_type, expected):\n values = np.asarray(values, dtype=object)\n array = _infer_data_type(values)\n assert array.dtype == dst_type\n assert_array_equal(array, expected)\n\n\n@given(\n values=hynp.arrays(\n dtype=hynp.floating_dtypes()\n | hynp.integer_dtypes()\n | hynp.complex_number_dtypes(),\n shape=hynp.array_shapes(),\n elements=integers(0, 2 ** 7 - 1),\n ),\n dst_type=hynp.floating_dtypes()\n | hynp.integer_dtypes()\n | hynp.complex_number_dtypes(),\n)\n@pytest.mark.parametrize(\"as_iterable\", [list, tuple, np.asarray])\ndef test_dtype_keyword(as_iterable, values, dst_type):\n array = _infer_data_type(as_iterable(values), dtype=dst_type)\n assert array.dtype == dst_type\n assert_array_equal(array, values)\n\n\n@given(\n values=hynp.arrays(\n dtype=hynp.floating_dtypes()\n | hynp.integer_dtypes()\n | hynp.complex_number_dtypes(),\n shape=hynp.array_shapes(),\n elements=integers(0, 2 ** 7 - 1),\n ),\n dst_type=hynp.floating_dtypes()\n | hynp.integer_dtypes()\n | hynp.complex_number_dtypes(),\n)\ndef test_object_arrays(values, dst_type):\n assume(\n not np.issubdtype(values.dtype, np.complexfloating)\n or np.issubdtype(dst_type, np.complexfloating)\n )\n values = np.asarray(values, dtype=object)\n array = _infer_data_type(values, dtype=dst_type)\n assert array.dtype == dst_type\n assert_array_equal(array, values)\n\n\n@given(\n values=hynp.arrays(\n dtype=hynp.complex_number_dtypes(),\n shape=hynp.array_shapes(),\n elements=integers(0, 8),\n ),\n dst_type=hynp.floating_dtypes() | hynp.integer_dtypes(),\n)\ndef test_from_complex(values, dst_type):\n array = _infer_data_type(values, dtype=dst_type)\n assert_array_equal(array.real, values.real)\n\n\n@given(values=hynp.arrays(dtype=hynp.array_dtypes(), shape=hynp.array_shapes()))\ndef test_array_not_copied(values):\n array = _infer_data_type(values, dtype=values.dtype)\n assert array is values\n"
] |
[
[
"numpy.testing.assert_array_equal",
"numpy.asarray",
"numpy.issubdtype"
]
] |
bh107/bohrium
|
[
"5b83e7117285fefc7779ed0e9acb0f8e74c7e068"
] |
[
"bridge/npbackend/bohrium/contexts.py"
] |
[
"\"\"\"\nBohrium Contexts\n================\n\"\"\"\nimport sys\nimport os\nfrom . import backend_messaging as messaging\n\n\nclass EnableBohrium:\n \"\"\"Enable Bohrium within the context\"\"\"\n\n def __init__(self):\n # In order to avoid complications, we import common libraries BEFORE enabling Bohrium\n try:\n import matplotlib\n if os.environ.get(\"DISPLAY\", \"\") == \"\":\n matplotlib.use('Agg') # When no DISPLAY, we assume a headless matplotlib is used\n import matplotlib.pyplot\n import matplotlib.pylab\n except ImportError:\n pass\n try:\n import scipy\n import scipy.sparse\n import scipy.io\n except ImportError:\n pass\n try:\n import netCDF4\n except ImportError:\n pass\n try:\n import sklearn\n import sklearn.preprocessing\n except ImportError:\n pass\n\n # Let's save to real NumPy module\n self.__numpy = sys.modules['numpy']\n self.__numpy_random = sys.modules['numpy.random']\n self.__numpy_linalg = sys.modules['numpy.linalg']\n\n # Sub-module matlib has to be imported explicitly once in order to be available through bohrium\n try:\n import numpy.matlib\n except ImportError:\n pass\n\n def __enter__(self):\n import numpy\n import bohrium\n # Overwrite with Bohrium\n sys.modules['numpy_force'] = numpy\n sys.modules['numpy'] = bohrium\n sys.modules['numpy.random'] = bohrium.random\n sys.modules['numpy.linalg'] = bohrium.linalg\n\n def __exit__(self, *args):\n # Put NumPy back together\n sys.modules.pop('numpy_force', None)\n sys.modules['numpy'] = self.__numpy\n sys.modules['numpy.random'] = self.__numpy_random\n sys.modules['numpy.linalg'] = self.__numpy_linalg\n\n\nclass DisableBohrium:\n \"\"\"Disable Bohrium within the context\"\"\"\n\n def __enter__(self):\n # Save current state\n import numpy\n self._numpy = sys.modules['numpy']\n self._numpy_random = sys.modules['numpy.random']\n self._numpy_linalg = sys.modules['numpy.linalg']\n # Make sure that numpy points to numpy (and not Bohrium)\n sys.modules['numpy'] = sys.modules.get(\"numpy_force\", self._numpy)\n\n def __exit__(self, *args):\n # Load the state before entering context\n sys.modules['numpy'] = self._numpy\n sys.modules['numpy.random'] = self._numpy_random\n sys.modules['numpy.linalg'] = self._numpy_linalg\n\n\nclass Profiling:\n \"\"\"Profiling the Bohrium backends within the context.\"\"\"\n\n def __init__(self):\n pass\n\n def __enter__(self):\n messaging.statistic_enable_and_reset()\n\n def __exit__(self, *args):\n print(messaging.statistic())\n\n\nclass DisableGPU:\n \"\"\"Disable the GPU backend within the context.\"\"\"\n\n def __init__(self):\n pass\n\n def __enter__(self):\n messaging.gpu_disable()\n\n def __exit__(self, *args):\n messaging.gpu_enable()\n"
] |
[
[
"matplotlib.use"
]
] |
BraunPenguin/InstanceSegmentation-Detectron2
|
[
"f26036bffa96901f55f2bbc2fcbdf77839bd5161"
] |
[
"Utility/AnalyzeTiltInstance.py"
] |
[
"import sys\nimport os\nimport pickle\nimport joblib\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nfrom shapely.geometry import Point, LineString, MultiLineString, Polygon\nfrom shapely.strtree import STRtree\nfrom shapely import affinity\nfrom skimage.measure import label, regionprops\nfrom collections import OrderedDict\nfrom polylidarutil import (plot_points, plot_polygons, get_point)\nfrom polylidar import extractPolygons\n# from Utility.CropScaleSave import importRawImageAndScale, getNakedNameFromFilePath\n# from Utility.AnalyzeOutputUI import SetupOptions\nfrom Utility.Utilities import *\n\n\n# @profile\ndef centerXPercentofWire(npMaskFunc, setupOptions: SetupOptions):\n # TODO: This is the limiting factor at this point in speed, but it is entirely in the skimage (label_image and allRegionProperties lines) and polylidar (polygonsList line) calls\n assert 0 <= setupOptions.centerFractionToMeasure <= 1, \"Percent size of section has to be between 0 and 1\"\n assert isinstance(setupOptions.isVerticalSubSection, bool), \"isVerticalSubSection must be a boolean, True if you want a vertical subsection, False if you want a horizontal subsection\"\n label_image = label(npMaskFunc, connectivity=1)\n allRegionProperties = regionprops(label_image)\n largeRegionsNums = set()\n regionNum = 0\n for region in allRegionProperties:\n # Ignore small regions or if an instance got split into a major and minor part\n if region.area > 100:\n largeRegionsNums.add(regionNum)\n regionNum += 1\n if len(largeRegionsNums) == 1:\n region = allRegionProperties[list(largeRegionsNums)[0]]\n ymin, xmin, ymax, xmax = region.bbox # may not need this line\n\n # maskCords as [row, col] ie [y, x]\n maskCoords = np.array(region.coords)\n flippedMaskCoords = maskCoords.copy()\n flippedMaskCoords[:, 0], flippedMaskCoords[:, 1] = flippedMaskCoords[:, 1], flippedMaskCoords[:, 0].copy()\n maskAngle = np.rad2deg(region.orientation)\n\n polygonsList = extractPolygons(flippedMaskCoords)\n # assert len(polygonsList) == 1, \"There was more than 1 polygon extracted from extractPolygons.\"\n # Just take the first polygon no matter what\n shell_coords = [get_point(pi, flippedMaskCoords) for pi in polygonsList[0].shell]\n maskPolygon = Polygon(shell=shell_coords)\n if setupOptions.plotPolylidar and not setupOptions.parallelProcessing:\n fig, ax = plt.subplots(figsize=(8, 8), nrows=1, ncols=1)\n # plot points\n plot_points(flippedMaskCoords, ax)\n # plot polygons...doesn't use 2nd argument\n plot_polygons(polygonsList, 0, flippedMaskCoords, ax)\n plt.axis('equal')\n plt.show()\n\n # Scale the width/height and then skew the squared bounding box by skimage ellipse fitted mask angle about skimage mask centroid\n # This should ensure a measurement line passes through the centroid, at the ellipse angle, and never starts within the mask itself\n # This also means the lengths measured are the real lengths, don't need to do trig later\n centroidCoords = region.centroid\n if setupOptions.isVerticalSubSection:\n scaledBoundingBoxPoly = affinity.scale(maskPolygon.envelope, 1, setupOptions.centerFractionToMeasure)\n # Coords are row, col ie (y, x)\n subBoundingBoxPoly = affinity.skew(scaledBoundingBoxPoly.envelope, ys=-maskAngle, origin=(centroidCoords[1], centroidCoords[0]))\n else:\n # Coords are row, col ie (y, x)\n scaledBoundingBoxPoly = affinity.scale(maskPolygon.envelope, setupOptions.centerFractionToMeasure, 1)\n subBoundingBoxPoly = affinity.skew(scaledBoundingBoxPoly.envelope, xs=maskAngle, origin=(centroidCoords[1], centroidCoords[0]))\n outputSubMaskPoly = maskPolygon.intersection(subBoundingBoxPoly)\n\n if setupOptions.showBoundingBoxPlots and not setupOptions.parallelProcessing:\n # Blue rectangle is standard bounding box\n # Red rectangle is rotated bounding box from MinimumBoundingBox\n # Multicolored points are either standard (setupOptions.isVerticalSubsection=True) or rotated bounding box (setupOptions.isVerticalSubsection=False)\n fig = plt.figure(figsize=(15, 12))\n ax = fig.add_subplot(111)\n ax.imshow(npMaskFunc)\n r1 = mpatches.Rectangle((xmin, ymax), xmax - xmin, -(ymax - ymin), fill=False, edgecolor=\"blue\", alpha=1, linewidth=1)\n\n ax.axis('equal')\n ax.add_patch(r1)\n\n # 5, since we have 4 points for a rectangle but don't want to have 1st = 4th\n phi = -1 * np.linspace(0, 2*np.pi, 5)\n rgb_cycle = np.vstack((.5 * (1. + np.cos(phi)), .5 * (1. + np.cos(phi + 2 * np.pi / 3)), .5 * (1. + np.cos(phi - 2 * np.pi / 3)))).T\n plt.scatter(subBoundingBoxPoly.exterior.coords.xy[0][:-1], subBoundingBoxPoly.exterior.coords.xy[1][:-1], c=rgb_cycle[:4])\n plt.plot(subBoundingBoxPoly.exterior.coords.xy[0], subBoundingBoxPoly.exterior.coords.xy[1])\n plt.autoscale()\n plt.show()\n\n return outputSubMaskPoly, subBoundingBoxPoly, maskAngle\n # else:\n return None, None, None\n\n\ndef bboxToPoly(xmin, ymin, xmax, ymax):\n return [[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]\n\n\ndef isValidLine(strTree, instanceBoxCoords, imageHeight, instanceLine):\n # Check if line is contained in a different bounding box, need to check which instance is in front (below)\n # Don't check for the current instanceNum (key in boundingBoxDict)\n validForInstanceList = []\n bottomLeft, bottomRight, topLeft, topRight = instanceBoxCoords\n lineIntersectingBoxes = strTree.query(instanceLine)\n if lineIntersectingBoxes:\n for bbox in lineIntersectingBoxes:\n # This is faster than doing a index lookup into a list of bounding box polygons then coords\n bottomLeftCheck, bottomRightCheck, topLeftCheck, topRightCheck = getXYFromPolyBox(bbox)\n imageBottom = imageHeight\n instanceBottom = bottomLeft[1]\n checkInstanceBottom = bottomLeftCheck[1]\n if abs(imageBottom - instanceBottom) < 20:\n # the box of interest is too close to the bottom\n instanceTop = topLeft[1]\n checkInstanceTop = topLeftCheck[1]\n if instanceTop < checkInstanceTop:\n # Good assumption that instance of interest is in front, since all wires ~same length and the top is lower than the check instance\n validForInstanceList.append(True)\n else:\n # Maybe need to add more checks if too many lines are being eliminated\n # intersectingMask = maskDict[checkNumber]\n validForInstanceList.append(False)\n elif instanceBottom > checkInstanceBottom:\n # the instance of interest is lower in the image, thus in front due to substrate tilt\n validForInstanceList.append(True)\n else:\n validForInstanceList.append(False)\n else:\n validForInstanceList.append(True)\n\n if all(validForInstanceList):\n return True\n # else:\n return False\n\n\n# @profile\ndef longestLineAndLengthInPolygon(maskPolygon, lineTest):\n # TODO: This is slow, just the lineTest.intersection line\n testSegments = lineTest.intersection(maskPolygon) # without .boundary, get the lines immediately\n outputLine = None\n LineLength = None\n if isinstance(testSegments, LineString):\n if not testSegments.is_empty:\n # The line is entirely inside the mask polygon\n LineLength = testSegments.length\n outputLine = testSegments\n elif isinstance(testSegments, MultiLineString):\n # The line crosses the boundary of the mask polygon\n LineLength = 0\n for segment in testSegments:\n if segment.length > LineLength:\n LineLength = segment.length\n outputLine = segment\n return outputLine, LineLength\n\n\ndef getLinePoints(startXY, endXY):\n startPoint = Point(startXY)\n endPoint = Point(endXY)\n lineOfInterest = LineString([startPoint, endPoint])\n\n if sys.version_info < (3, 7):\n xyPoints = OrderedDict()\n else:\n # in Python 3.7 and newer dicts are ordered by default\n xyPoints = {}\n for pos in range(int(np.ceil(lineOfInterest.length)) + 1):\n interpolatedPoint = lineOfInterest.interpolate(pos).coords[0]\n roundedPoint = map(round, interpolatedPoint)\n xyPoints[tuple(roundedPoint)] = None\n return xyPoints\n\n\n# @profile\ndef analyzeSingleTiltInstance(maskDict, boundingBoxPolyDict, instanceNumber, setupOptions: SetupOptions):\n if not setupOptions.parallelProcessing:\n print(\"Working on instance number: \", instanceNumber)\n\n mask = maskDict[instanceNumber]\n imageWidth = mask.shape[1]\n imageHeight = mask.shape[0]\n\n measLineList = []\n lineLengthList = []\n filteredLineLengthList = []\n lineStd = None\n lineAvg = None\n\n outputSubMaskPoly, subBoundingBoxPoly, maskAngle = centerXPercentofWire(mask, setupOptions)\n if outputSubMaskPoly is not None:\n if -5 < maskAngle < 5:\n strTree = STRtree([poly for i, poly in boundingBoxPolyDict.items() if i != instanceNumber])\n subStrTree = STRtree(strTree.query(boundingBoxPolyDict[instanceNumber]))\n\n bottomLeft, bottomRight, topLeft, topRight = getXYFromPolyBox(subBoundingBoxPoly)\n instanceBoxCoords = getXYFromPolyBox(boundingBoxPolyDict[instanceNumber])\n\n if not isEdgeInstance(imageWidth, imageHeight, instanceBoxCoords, setupOptions.isVerticalSubSection):\n if setupOptions.isVerticalSubSection:\n lineStartPoints = getLinePoints(bottomLeft, topLeft) # Left line\n lineEndPoints = getLinePoints(bottomRight, topRight) # Right line\n else:\n lineStartPoints = getLinePoints(bottomLeft, bottomRight) # Bottom line\n lineEndPoints = getLinePoints(topLeft, topRight) # Top line\n\n for startPoint, endPoint in zip(lineStartPoints, lineEndPoints):\n instanceLine = LineString([startPoint, endPoint])\n longestLine, lineLength = longestLineAndLengthInPolygon(outputSubMaskPoly, instanceLine)\n if longestLine is not None:\n if isValidLine(subStrTree, instanceBoxCoords, imageHeight, longestLine):\n measLineList.append(longestLine)\n lineLengthList.append(lineLength)\n if len(lineLengthList) > 2:\n # The first and last lines sometimes have issues, remove them\n measLineList = measLineList[1:-1]\n lineLengthList = np.asarray(lineLengthList[1:-1])\n if setupOptions.isVerticalSubSection:\n filteredLineLengthList = lineLengthList\n\n else:\n filteredLineLengthList = lineLengthList[lineLengthList > (np.max(lineLengthList)-0.5*np.std(lineLengthList))]\n measLineList = [measLineListItem for measLineListItem, lineLength in zip(measLineList, lineLengthList) if lineLength > (np.max(lineLengthList) - 0.5 * np.std(lineLengthList))]\n\n if len(filteredLineLengthList) == 2:\n lineStd = np.std(filteredLineLengthList, ddof=1)\n elif len(filteredLineLengthList) == 1:\n lineStd = 0\n else:\n lineStd = np.std(filteredLineLengthList, ddof=0)\n lineAvg = np.mean(filteredLineLengthList)\n else:\n # else there are no valid lines\n measLineList = []\n\n return measLineList, filteredLineLengthList, lineStd, lineAvg, maskAngle\n\n\n\n\n"
] |
[
[
"numpy.max",
"numpy.array",
"numpy.ceil",
"numpy.asarray",
"matplotlib.pyplot.autoscale",
"numpy.rad2deg",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.figure",
"numpy.linspace",
"numpy.mean",
"numpy.std",
"matplotlib.pyplot.scatter",
"numpy.cos",
"matplotlib.pyplot.show",
"matplotlib.patches.Rectangle",
"matplotlib.pyplot.axis"
]
] |
dmitryvinn/pytext
|
[
"43373462d1b9bada3ba02072aed78338d3bb3a12"
] |
[
"pytext/models/representations/transformer/luna_sentence_encoder.py"
] |
[
"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\nimport math\nfrom typing import Callable, Optional\n\nimport torch\nfrom fairseq import utils\nfrom fairseq.modules import LayerNorm, PositionalEmbedding, LayerDropModuleList\nfrom fairseq.modules.fairseq_dropout import FairseqDropout\nfrom pytext.utils.usage import log_class_usage\nfrom torch import nn\nfrom torch.nn import Parameter\n\nfrom . import LunarMultiheadAttention\n\n\nclass LunaSentenceEncoderLayer(nn.Module):\n \"\"\"\n Implements a Luna Encoder Layer used in masked pre-trained language models\n and fine-tuned classication/regression mdoel\n \"\"\"\n\n def __init__(\n self,\n embedding_dim: int = 768,\n ffn_embedding_dim: int = 3072,\n num_attention_heads: int = 8,\n num_projected_attention_heads: int = 8,\n dropout: float = 0.1,\n attention_dropout: float = 0.1,\n activation_dropout: float = 0.1,\n activation_fn: str = \"relu\",\n normalize_before: bool = False,\n tie_kv=True,\n export: bool = False,\n init_fn: Callable = None,\n ) -> None:\n super().__init__()\n\n if init_fn is not None:\n init_fn()\n\n # Initialize parameters\n self.embedding_dim = embedding_dim\n self.dropout_module = FairseqDropout(\n dropout, module_name=self.__class__.__name__\n )\n self.activation_dropout_module = FairseqDropout(\n activation_dropout, module_name=self.__class__.__name__\n )\n\n # Initialize blocks\n self.activation_fn = utils.get_activation_fn(activation_fn)\n self.self_attn = self.build_self_attention(\n self.embedding_dim,\n num_attention_heads,\n num_projected_attention_heads,\n dropout=attention_dropout,\n tie_kv=tie_kv,\n )\n\n # layer norm associated with the self attention layer\n self.normalize_before = normalize_before\n self.self_attn_layer_norm = LayerNorm(self.embedding_dim, export=export)\n self.self_atten_proj_layer_norm = LayerNorm(self.embedding_dim, export=export)\n\n self.fc1 = self.build_fc1(\n self.embedding_dim,\n ffn_embedding_dim,\n )\n self.fc2 = self.build_fc2(\n ffn_embedding_dim,\n self.embedding_dim,\n )\n\n # layer norm associated with the position wise feed-forward NN\n self.final_layer_norm = LayerNorm(self.embedding_dim, export=export)\n\n def build_fc1(self, input_dim, output_dim):\n return nn.Linear(input_dim, output_dim)\n\n def build_fc2(self, input_dim, output_dim):\n return nn.Linear(input_dim, output_dim)\n\n def build_self_attention(\n self,\n embed_dim,\n num_attention_heads,\n num_projected_attention_heads,\n dropout,\n tie_kv,\n q_noise,\n qn_block_size,\n ):\n return LunarMultiheadAttention(\n embed_dim,\n num_attention_heads,\n num_projected_attention_heads,\n dropout=dropout,\n self_attention=True,\n tie_kv=tie_kv,\n q_noise=q_noise,\n qn_block_size=qn_block_size,\n )\n\n def forward(\n self,\n x: torch.Tensor,\n px: torch.Tensor,\n x_padding_mask: Optional[torch.Tensor] = None,\n px_padding_mask: Optional[torch.Tensor] = None,\n ):\n \"\"\"\n LayerNorm is applied either before or after the self-attention/ffn\n modules similar to the original Transformer implementation.\n \"\"\"\n residual = x\n presidual = px\n # apply prev layer norm\n if self.normalize_before:\n x = self.self_attn_layer_norm(x)\n px = self.self_atten_proj_layer_norm(px)\n\n x, px, attn = self.self_attn(\n query=x,\n pquery=px,\n context=x,\n context_padding_mask=x_padding_mask,\n pcontext_padding_mask=px_padding_mask,\n need_weights=False,\n )\n # apply dropout\n x = self.dropout_module(x)\n px = self.dropout_module(px)\n # residual\n x = residual + x\n px = presidual + px\n\n # apply post layer norm\n if not self.normalize_before:\n x = self.self_attn_layer_norm(x)\n px = self.self_atten_proj_layer_norm(px)\n\n #######################################################################\n # Feed-Forward Network\n residual = x\n # apply prev layer norm\n if self.normalize_before:\n x = self.final_layer_norm(x)\n\n x = self.activation_fn(self.fc1(x))\n x = self.activation_dropout_module(x)\n x = self.fc2(x)\n x = self.dropout_module(x)\n x = residual + x\n\n # apply post layer norm\n if not self.normalize_before:\n x = self.final_layer_norm(x)\n return x, px, attn\n\n\ndef init_bert_params(module):\n \"\"\"\n Initialize the weights specific to the BERT Model.\n This overrides the default initializations depending on the specified arguments.\n 1. If normal_init_linear_weights is set then weights of linear\n layer will be initialized using the normal distribution and\n bais will be set to the specified value.\n 2. If normal_init_embed_weights is set then weights of embedding\n layer will be initialized using the normal distribution.\n 3. If normal_init_proj_weights is set then weights of\n in_project_weight for MultiHeadAttention initialized using\n the normal distribution (to be validated).\n \"\"\"\n\n if isinstance(module, LunaSentenceEncoder):\n module.projected_embeddings.data.normal_(mean=0.0, std=0.02)\n if isinstance(module, nn.Linear):\n module.weight.data.normal_(mean=0.0, std=0.02)\n if module.bias is not None:\n module.bias.data.zero_()\n if isinstance(module, nn.Embedding):\n module.weight.data.normal_(mean=0.0, std=0.02)\n if module.padding_idx is not None:\n module.weight.data[module.padding_idx].zero_()\n if isinstance(module, LunarMultiheadAttention):\n module.pq_proj.weight.data.normal_(mean=0.0, std=0.02)\n module.q_proj.weight.data.normal_(mean=0.0, std=0.02)\n if module.pc_proj is not None:\n module.pc_proj.weight.data.normal_(mean=0.0, std=0.02)\n module.c_proj.weight.data.normal_(mean=0.0, std=0.02)\n else:\n module.pk_proj.weight.data.normal_(mean=0.0, std=0.02)\n module.pv_proj.weight.data.normal_(mean=0.0, std=0.02)\n module.k_proj.weight.data.normal_(mean=0.0, std=0.02)\n module.v_proj.weight.data.normal_(mean=0.0, std=0.02)\n\n\nclass LunaSentenceEncoder(nn.Module):\n \"\"\"\n Implementation for a Bi-directional Luna based Sentence Encoder used\n in masked pre-trained language models.\n This first computes the token embedding using the token embedding matrix,\n position embeddings (if specified) and segment embeddings\n (if specified). After applying the specified number of\n TransformerEncoderLayers, it outputs all the internal states of the\n encoder as well as the final representation associated with the first\n token (usually CLS token).\n Input:\n - tokens: B x T matrix representing sentences\n - segment_labels: B x T matrix representing segment label for tokens\n Output:\n - a tuple of the following:\n - a list of internal model states used to compute the\n predictions where each tensor has shape T x B x C\n - sentence representation associated with first input token\n in format B x C.\n \"\"\"\n\n def __init__(\n self,\n padding_idx: int,\n vocab_size: int,\n projection_length: int = 128,\n num_encoder_layers: int = 12,\n embedding_dim: int = 768,\n ffn_embedding_dim: int = 3072,\n num_attention_heads: int = 12,\n num_projected_attention_heads: int = 12,\n dropout: float = 0.1,\n attention_dropout: float = 0.1,\n activation_dropout: float = 0.1,\n layerdrop: float = 0.0,\n max_seq_len: int = 512,\n num_segments: int = 0,\n use_position_embeddings: bool = True,\n offset_positions_by_padding: bool = True,\n layernorm_embedding: bool = False,\n normalize_before: bool = False,\n dynamic_projection: bool = True,\n tie_kv=False,\n apply_bert_init: bool = False,\n activation_fn: str = \"gelu\",\n learned_pos_embedding: bool = True,\n embed_scale: float = None,\n freeze_embeddings: bool = False,\n n_trans_layers_to_freeze: int = 0,\n export: bool = False,\n traceable: bool = False,\n ) -> None:\n\n super().__init__()\n self.padding_idx = padding_idx\n self.vocab_size = vocab_size\n self.proj_len = projection_length\n self.dynamic_projection = dynamic_projection\n self.dropout_module = FairseqDropout(\n dropout, module_name=self.__class__.__name__\n )\n self.layerdrop = layerdrop\n self.max_seq_len = max_seq_len\n self.embedding_dim = embedding_dim\n self.num_segments = num_segments\n self.use_position_embeddings = use_position_embeddings\n self.apply_bert_init = apply_bert_init\n self.learned_pos_embedding = learned_pos_embedding\n self.traceable = traceable\n self.tpu = False # whether we're on TPU\n\n self.embed_tokens = self.build_embedding(\n self.vocab_size, self.embedding_dim, self.padding_idx\n )\n self.embed_scale = embed_scale\n\n if self.num_segments > 0:\n self.segment_embeddings = nn.Embedding(\n self.num_segments, self.embedding_dim, padding_idx=None\n )\n nn.init.normal_(\n self.segment_embeddings.weight, mean=0.0, std=self.embedding_dim ** -0.5\n )\n else:\n self.segment_embeddings = None\n\n self.embed_positions = (\n PositionalEmbedding(\n self.max_seq_len,\n self.embedding_dim,\n padding_idx=(self.padding_idx if offset_positions_by_padding else None),\n learned=self.learned_pos_embedding,\n )\n if self.use_position_embeddings\n else None\n )\n\n self.projected_embeddings = Parameter(\n torch.Tensor(self.proj_len, self.embedding_dim)\n )\n nn.init.normal_(\n self.projected_embeddings, mean=0.0, std=self.embedding_dim ** -0.5\n )\n if self.use_position_embeddings and not self.learned_pos_embedding:\n projected_positions = get_sinusoidal_positional_embedding(\n self.proj_len, self.embedding_dim\n )\n if self.embed_scale is None:\n self.embed_scale = math.sqrt(self.embedding_dim)\n else:\n projected_positions = None\n self.register_buffer(\"projected_positions\", projected_positions)\n\n if self.layerdrop > 0.0:\n self.layers = LayerDropModuleList(p=self.layerdrop)\n else:\n self.layers = nn.ModuleList([])\n\n self.layers.extend(\n [\n self.build_luna_sentence_encoder_layer(\n embedding_dim=self.embedding_dim,\n ffn_embedding_dim=ffn_embedding_dim,\n num_attention_heads=num_attention_heads,\n num_projected_attention_heads=num_projected_attention_heads,\n dropout=self.dropout_module.p,\n attention_dropout=attention_dropout,\n activation_dropout=activation_dropout,\n activation_fn=activation_fn,\n normalize_before=normalize_before,\n tie_kv=tie_kv,\n export=export,\n )\n for _ in range(num_encoder_layers)\n ]\n )\n\n assert not layernorm_embedding or not normalize_before\n\n if layernorm_embedding:\n self.emb_layer_norm = LayerNorm(self.embedding_dim, export=export)\n self.proj_emb_layer_norm = LayerNorm(self.embedding_dim, export=export)\n else:\n self.emb_layer_norm = None\n self.proj_emb_layer_norm = None\n\n if normalize_before:\n self.layer_norm = LayerNorm(self.embedding_dim, export=export)\n self.proj_layer_norm = LayerNorm(self.embedding_dim, export=export)\n else:\n self.layer_norm = None\n self.proj_layer_norm = None\n\n # Apply initialization of model params after building the model\n if self.apply_bert_init:\n self.apply(init_bert_params)\n\n def freeze_module_params(m):\n if m is not None:\n for p in m.parameters():\n p.requires_grad = False\n\n if freeze_embeddings:\n self.projected_embeddings.requires_grad = False\n freeze_module_params(self.embed_tokens)\n freeze_module_params(self.segment_embeddings)\n freeze_module_params(self.embed_positions)\n freeze_module_params(self.emb_layer_norm)\n freeze_module_params(self.proj_emb_layer_norm)\n\n for layer in range(n_trans_layers_to_freeze):\n freeze_module_params(self.layers[layer])\n\n log_class_usage(__class__)\n\n def build_embedding(self, vocab_size, embedding_dim, padding_idx):\n embed_tokens = nn.Embedding(vocab_size, embedding_dim, padding_idx)\n nn.init.normal_(embed_tokens.weight, mean=0, std=embedding_dim ** -0.5)\n return embed_tokens\n\n def build_luna_sentence_encoder_layer(\n self,\n embedding_dim,\n ffn_embedding_dim,\n num_attention_heads,\n num_projected_attention_heads,\n dropout,\n attention_dropout,\n activation_dropout,\n activation_fn,\n normalize_before,\n tie_kv,\n export,\n q_noise,\n qn_block_size,\n ):\n return LunaSentenceEncoderLayer(\n embedding_dim=embedding_dim,\n ffn_embedding_dim=ffn_embedding_dim,\n num_attention_heads=num_attention_heads,\n num_projected_attention_heads=num_projected_attention_heads,\n dropout=dropout,\n attention_dropout=attention_dropout,\n activation_dropout=activation_dropout,\n activation_fn=activation_fn,\n normalize_before=normalize_before,\n tie_kv=tie_kv,\n export=export,\n q_noise=q_noise,\n qn_block_size=qn_block_size,\n )\n\n def prepare_for_tpu_(self, **kwargs):\n self.tpu = True\n\n def forward(\n self,\n tokens: torch.Tensor,\n segment_labels: torch.Tensor = None,\n last_state_only: bool = False,\n positions: Optional[torch.Tensor] = None,\n ):\n\n # compute padding mask. This is needed for multi-head attention\n # B x T\n x_padding_mask = tokens.eq(self.padding_idx)\n lengths = tokens.size(1) - x_padding_mask.sum(1)\n max_len = lengths.max() if self.dynamic_projection else self.proj_len\n\n x = self.embed_tokens(tokens)\n px = self.projected_embeddings[:max_len]\n\n if self.embed_scale is not None:\n x *= self.embed_scale\n px *= self.embed_scale\n\n if self.embed_positions is not None:\n x += self.embed_positions(tokens, positions=positions)\n if self.projected_positions is not None:\n px += self.projected_positions[:max_len]\n\n if self.segment_embeddings is not None and segment_labels is not None:\n x += self.segment_embeddings(segment_labels)\n\n if self.quant_noise is not None:\n x = self.quant_noise(x)\n\n if self.emb_layer_norm is not None:\n x = self.emb_layer_norm(x)\n px = self.proj_emb_layer_norm(px)\n\n bsz = x.size(0)\n len, dim = px.size()\n # L x C -> B x L x C\n px = px.unsqueeze(0).expand(bsz, len, dim)\n\n if self.dynamic_projection:\n pidx = torch.arange(len).unsqueeze(0).to(x.device)\n # B x L\n px_padding_mask = pidx.ge(lengths.unsqueeze(1))\n else:\n px_padding_mask = None\n\n if not self.traceable and not self.tpu:\n if not x_padding_mask.any():\n x_padding_mask = None\n if px_padding_mask is not None and not px_padding_mask.any():\n px_padding_mask = None\n\n x = self.dropout_module(x)\n px = self.dropout_module(px)\n\n # account for padding while computing the representation\n if x_padding_mask is not None:\n x = x * (1 - x_padding_mask.unsqueeze(-1).type_as(x))\n if px_padding_mask is not None:\n px = px * (1 - px_padding_mask.unsqueeze(-1).type_as(px))\n\n # B x T x C -> T x B x C\n x = x.transpose(0, 1)\n # B x L x C -> L x B x C\n px = px.transpose(0, 1)\n\n inner_states = []\n if not last_state_only:\n inner_states.append(x)\n\n for layer in self.layers:\n x, px, _ = layer(\n x, px, x_padding_mask=x_padding_mask, px_padding_mask=px_padding_mask\n )\n if not last_state_only:\n inner_states.append(x)\n\n if self.layer_norm is not None:\n x = self.layer_norm(x)\n px = self.proj_layer_norm(px)\n\n # sentence_cls_rep = x[0, :, :]\n # sentence_proj_rep = px\n\n if last_state_only:\n inner_states = [x]\n\n return inner_states\n\n\ndef get_sinusoidal_positional_embedding(length, embed_dim):\n half_dim = embed_dim // 2\n emb = math.log(10000) / (half_dim - 1)\n emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb)\n emb = torch.arange(length, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0)\n emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(length, -1)\n if embed_dim % 2 == 1:\n emb = torch.cat([emb, torch.zeros(length, 1)], dim=1)\n return emb\n"
] |
[
[
"torch.nn.Linear",
"torch.zeros",
"torch.cos",
"torch.nn.ModuleList",
"torch.arange",
"torch.sin",
"torch.nn.init.normal_",
"torch.Tensor",
"torch.nn.Embedding"
]
] |
me-manu/fastespy
|
[
"7bf1fef68239c7d69c0917a51f24d48e9ad14728",
"7bf1fef68239c7d69c0917a51f24d48e9ad14728"
] |
[
"fastespy/io/rootdata.py",
"fastespy/mlkeras/models.py"
] |
[
"from __future__ import absolute_import, division, print_function\nimport ROOT as root\nimport glob\nimport os\nimport numpy as np\nimport time\nimport logging\n\n\ndef readgraph(directory, split = '-', overwrite = False, inputid = 'in', prefix = ''):\n \"\"\"\n Read data from a ROOT graph and save as numpy npz file.\n\n :param directory: str\n Directory containing the root files.\n\n :return:\n \"\"\"\n files = glob.glob(os.path.join(directory, \"{0:s}*.root\".format(prefix)))\n try:\n files = sorted(files, key=lambda f: int(os.path.basename(f).split(\".\")[0].split(split)[-1]))\n except ValueError as e:\n print(\"Warning: could not sort root files by name: {0}\".format(e))\n\n npzfiles = [f.replace('.root', '.npz') for f in files]\n\n t = []\n v = []\n tin = []\n vin = []\n\n for i, rootfile in enumerate(files):\n if os.path.isfile(npzfiles[i]) and not overwrite:\n print(\"Reading file {0:n} of {1:n}: {2:s}\".format(i + 1, len(files), npzfiles[i]))\n r = np.load(npzfiles[i])\n x = r['x']\n y = r['y']\n\n else:\n t1 = time.time()\n print(\"Reading file {0:n} of {1:n}: {2:s}\".format(i + 1, len(files), rootfile))\n f = root.TFile.Open(rootfile)\n hh = root.TGraph()\n if inputid in rootfile:\n root.gDirectory.GetObject('Data of channel ChB', hh)\n x = np.array([hh.GetX()[i] for i in range(len(hh.GetX()))])\n y = np.array([hh.GetY()[i] for i in range(len(hh.GetY()))])\n else:\n root.gDirectory.GetObject('Data of channel ChA', hh)\n x = np.array([hh.GetX()[i] for i in range(len(hh.GetX()))])\n y = np.array([hh.GetY()[i] for i in range(len(hh.GetY()))])\n f.Close()\n print(\"Reading root file took {0:.2f} minutes\".format((time.time() - t1) / 60.))\n\n np.savez(npzfiles[i], x=x, y=y)\n\n if inputid in rootfile:\n tin.append(x)\n vin.append(y)\n else:\n t.append(x)\n v.append(y)\n\n return t, v, tin, vin\n\n\ndef root2py_fit_results_axel(path,\n tree_name=\"TES_fits\",\n features=(\"ampli\", \"peak\", \"rise\", \"decay\", \"const\", \"chi2\")):\n \"\"\"\n Read in Axel's fit results obtained with ROOT\n and save as npy file\n\n Parameters\n ----------\n path: str\n path containing the root files\n\n tree_name: str\n Name of root tree where results are stored\n\n features: list of strings\n feature names that are extracted from root tree\n \"\"\"\n data_files = glob.glob(os.path.join(path, '*.root'))\n if not len(data_files):\n raise ValueError(\"No files found!\")\n\n for i, d in enumerate(data_files):\n\n logging.info(\"Reading file {0:s}, assigning event id {1:n}\".format(d, i))\n r = root.TFile(d)\n t = root.TTree()\n r.GetObject(tree_name, t)\n n_events = t.GetEntries()\n\n result = dict()\n for k in features:\n t.Draw(k)\n vals = t.GetVal(0)\n result[k] = np.zeros(n_events)\n for j in range(n_events):\n result[k][j] = vals[j]\n result['type'] = np.full(n_events, i)\n\n del r, t\n filename = os.path.join(os.path.dirname(d), os.path.basename(d).replace('root','npy'))\n logging.info(f\"Saving fit results to {filename}\")\n np.save(filename, result)\n",
"from __future__ import absolute_import, division, print_function\nfrom tensorflow import keras\nimport time\nimport numpy as np\n\nmetrics = (\n keras.metrics.TruePositives(name='tp'),\n keras.metrics.FalsePositives(name='fp'),\n keras.metrics.TrueNegatives(name='tn'),\n keras.metrics.FalseNegatives(name='fn'),\n keras.metrics.BinaryAccuracy(name='accuracy'),\n keras.metrics.Precision(name='precision'),\n keras.metrics.Recall(name='recall'),\n keras.metrics.AUC(name='auc'),\n keras.metrics.AUC(name='prc', curve='PR'), # precision-recall curve\n)\n\n\ndef make_mlp_model(n_features,\n metrics=metrics,\n activation='relu',\n output_bias=None,\n learning_rate=3e-4,\n n_layers=3,\n n_nodes=100,\n dropout=0.,\n l2_regularizer=None):\n \"\"\"\n Make a keras model for a multilayer perceptron\n for binary classification.\n\n Parameters\n ----------\n n_features: int\n number of features\n metrics: list\n list of metrics to be saved during training\n\n activation: string\n name of activation function\n\n output_bias: float\n initial bias for output layer\n\n learning_rate: float\n learning rate for Adam optimizer\n\n n_layers: int\n number of hidden layers\n\n n_nodes: int\n number of nodes in the hidden layers\n\n dropout: float\n Dropout rate\n\n l2_regularizer: float\n L2 Regularization parameter.\n\n Returns\n -------\n keras model instance\n\n \"\"\"\n model = keras.Sequential(name=\"mlp_binary\")\n\n if output_bias is not None:\n output_bias = keras.initializers.Constant(output_bias)\n\n if l2_regularizer is not None:\n l2_regularizer = keras.regularizers.l2(l2_regularizer)\n\n # adding the input layer\n model.add(keras.layers.Input(shape=(n_features)))\n\n # hidden layers\n for i in range(n_layers):\n model.add(keras.layers.Dense(n_nodes,\n activation=activation,\n name='dense{0:n}'.format(i + 1),\n kernel_regularizer=l2_regularizer,\n bias_regularizer=l2_regularizer\n )\n )\n if dropout > 0.:\n model.add(keras.layers.Dropout(dropout))\n\n # output\n model.add(keras.layers.Dense(1, activation='sigmoid', name='output',\n bias_initializer=output_bias)) # output layer for binary classification\n\n adam = keras.optimizers.Adam(learning_rate=learning_rate)\n model.compile(\n loss=keras.losses.BinaryCrossentropy(from_logits=True),\n optimizer=adam,\n metrics=metrics\n )\n\n return model\n\n\ndef initial_output_bias(y_train):\n \"\"\"\n Compute the initial guess for the output bias\n for binary classification for imbalanced data\n\n Parameters\n ----------\n y_train: array-like\n Training class labels\n\n Returns\n -------\n tuple with array with initial guess for bias and resulting initial loss\n \"\"\"\n initial_bias = np.array([np.log(y_train.sum() / np.invert(y_train.astype(bool)).astype(int).sum())])\n p0 = 1. / (1. + np.exp(-initial_bias))\n initial_loss = -p0 * np.log(p0) - (1. - p0) * np.log(1. - p0)\n return initial_bias, initial_loss\n\n\ndef train_model(model, X_train, y_train, X_val=None, y_val=None, epochs=200, batch_size=2048, **kwargs):\n \"\"\"\n Train model\n\n Parameters\n ----------\n model: keras model\n the model to fit\n X_train: array-like\n training data\n y_train: array-like\n training labels\n X_val: None or array-like\n validation data\n y_val: None or array-like\n validation labels\n epochs: int\n training epocks\n batch_size: int\n batch size\n kwargs: dict\n addtional kwargs passed to fit funtion\n \"\"\"\n kwargs.setdefault(\"verbose\", 0)\n\n # early stopping if loss of validation set does not improve\n early_stopping = keras.callbacks.EarlyStopping(\n monitor='val_loss',\n verbose=1,\n patience=10,\n mode='min',\n restore_best_weights=True)\n\n if X_val is None or y_val is None:\n valdation_data = None\n else:\n validation_data = (X_val, y_val)\n\n t0 = time.time()\n history = model.fit(\n X_train,\n y_train,\n batch_size=batch_size,\n epochs=epochs,\n validation_data=validation_data,\n **kwargs\n )\n t1 = time.time()\n if kwargs['verbose']:\n print(\"training took {0:.2f}s\".format(t1 - t0))\n\n return history\n"
] |
[
[
"numpy.full",
"numpy.zeros",
"numpy.load",
"numpy.save",
"numpy.savez"
],
[
"numpy.exp",
"tensorflow.keras.metrics.FalsePositives",
"tensorflow.keras.Sequential",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.losses.BinaryCrossentropy",
"numpy.log",
"tensorflow.keras.metrics.FalseNegatives",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.metrics.BinaryAccuracy",
"tensorflow.keras.regularizers.l2",
"tensorflow.keras.metrics.Precision",
"tensorflow.keras.initializers.Constant",
"tensorflow.keras.metrics.AUC",
"tensorflow.keras.layers.Input",
"tensorflow.keras.metrics.TrueNegatives",
"tensorflow.keras.metrics.Recall",
"tensorflow.keras.metrics.TruePositives",
"tensorflow.keras.callbacks.EarlyStopping"
]
] |
spyroot/shapenet
|
[
"31b95f25beff5129e0db31e798719ba555661685"
] |
[
"shapegnet/model_config.py"
] |
[
"# Graph Generator Model Configurator\n#\n# All trainer parameters abstracted in separate entity.\n#\n# - Trainer , Evaluator and the rest this class to configurator and store data.\n# It read yaml config file that users passes either as file name or io.string.\n#\n# Mustafa B\nimport os\nimport sys\nfrom os import listdir\nfrom os.path import isfile, join\nimport shutil\nimport logging\nfrom pathlib import Path\nfrom time import strftime, gmtime\nimport networkx as nx\nimport torch\nimport yaml\nfrom torch.utils.tensorboard import SummaryWriter\n# this is main colab fix.\nfrom typing import List\nfrom typing import List\nfrom typing import List, Set, Dict, Tuple, Optional\nfrom typing import Callable, Iterator, Union, Optional, List\nfrom typing import Union, Any, List, Optional, cast\nfrom typing import AnyStr\n\nfrom .graph_tools import graph_from_file\nfrom .utils import fmt_print, fmtl_print\n\n_opt_example = \"\"\"\"\noptimizer:\n - name: node_optimizer\n eps: 1e-8\n weight_decay: 0\n amsgrad: False\n momentum=0:\n betas: [0.9, 0.999]\n type: Adam\n\"\"\"\n\n\ndef extract_value_from_file(f, key, file_type='.dat'):\n \"\"\"\n @param file_type:\n @param f:\n @param key:\n @return:\n \"\"\"\n proceed = f.split('_')\n for i, k in enumerate(proceed):\n if key in k:\n v = proceed[i + 1]\n if file_type in v:\n return v[:-len(file_type)]\n else:\n return v\n\n\nclass ModelSpecs:\n \"\"\"\n The class hold all trainer configuration settings.\n\n \"\"\"\n\n def __init__(self, template_file_name='config.yaml', verbose=False):\n \"\"\"\n\n :param template_file_name:\n :param verbose:\n \"\"\"\n if isinstance(template_file_name, str):\n fmtl_print(\"Loading\", template_file_name)\n\n # store point to current loaded config,\n # after spec read serialize yaml to it.\n self.config = None\n\n # device\n self.device = 'cuda'\n if verbose:\n fmtl_print(\"Device\", self.device)\n\n # a file name or io.string\n self.config_file_name = template_file_name\n\n # if clean tensorboard\n self.clean_tensorboard = False\n\n # Cuda device id , if device is cuda\n self.cuda = 1\n\n # indicate active template to use\n self.active = \"\"\n\n # model spec used\n self.graph_specs = None\n\n # dictionary of models\n self.models = None\n\n # active model\n self.active_model = None\n\n # pointer to active model\n self.model = None\n\n # list of of lr scheduler\n self.lr_schedulers = None\n\n # list of optimizer defined in config file\n self._optimizers = None\n\n # tensorboard writer\n self.writer = None\n\n # Which graph dataset is used to train the model\n self.graph_type = self.active\n\n # verbose mode will output data to console\n self._verbose = verbose\n\n # stores a setting type ( name ), it must be defined in config.yaml\n self._active_setting = None\n\n # stores current global settings,\n # list of setting defined in config.yaml\n self._setting = None\n\n # will be pre-computed\n self._batch_ratio = None\n\n # initialized\n self.inited = False\n\n # if argument is filename, read config.\n if isinstance(template_file_name, str):\n if len(template_file_name) == 0:\n raise Exception(\"path to config.yaml file is empty.\")\n self.read_from_file()\n else:\n self.read_from_stream(template_file_name)\n\n # hidden size for main RNN\n self.hidden_size_rnn = int(128 / self.parameter_shrink())\n\n # hidden size for output RNN\n self.hidden_size_rnn_output = 16\n\n # the size for LSTM input\n self.embedding_size_rnn = int(64 / self.parameter_shrink())\n\n # the embedding size for edge rnn\n self.embedding_size_rnn_output = 8\n\n # the embedding size for output\n self.embedding_size_output = int(64 / self.parameter_shrink())\n\n # training config\n self.rescale_factor = 10\n\n # output dirs\n self.dir_input = self.root_dir()\n self.dir_result = Path(self.dir_input) / Path(self.results_dir())\n self.dir_log = Path(self.dir_result) / Path(self.log_dir())\n self.model_save_path = self.dir_result / Path(self.model_save_dir())\n self.dir_graph_save = self.dir_result / Path(self.graph_dir())\n self.dir_figure = self.dir_result / Path(self.figures_dir())\n self.dir_timing = self.dir_result / Path(self.timing_dir())\n # default dir where we store serialized prediction graph as image\n self.dir_model_prediction = self.dir_result / Path(self.prediction_dir())\n # self.dir_model_prediction = self.dir_result / Path(self.figures_prediction_dir())\n\n # filenames to save results, statistics , traces , logs\n self.filename = None\n self.filename_prediction = None\n self.filename_train = None\n self.filename_test = None\n self.filename_metrics = None\n self.filename_time_traces = None\n\n # self.filename_baseline = self.dir_graph_save / Path(\n # self.graph_type + self.generator_baseline + '_' + self.metric_baseline)\n\n # generate all template file names\n self.generate_file_name_template()\n\n # fmt for filenames\n self._epoch_file_fmt = \"epoch\"\n\n def get_prediction_dir(self):\n \"\"\"\n Return directory where prediction stored.\n :return:\n \"\"\"\n return self.dir_model_prediction\n\n def generate_file_name_template(self):\n \"\"\"\n Generates file name templates.\n \"\"\"\n self.filename = \"{}_{}_{}_layers_{}_hidden_{}_\".format(self.active,\n self.active_model,\n self.graph_type,\n str(self.num_layers()),\n str(self.hidden_size_rnn))\n\n self.filename_prediction = self.filename + 'predictions_'\n self.filename_train = self.filename + 'train_'\n self.filename_test = self.filename + 'test_'\n self.filename_metrics = self.filename + 'metric_'\n self.filename_time_traces = self.filename + 'timetrace_'\n\n def template_file_name(self):\n \"\"\"\n Return main template file name, template file\n name contains model name and other details.\n :return:\n \"\"\"\n return self.filename\n\n def prediction_dir_from_type(self, file_type):\n \"\"\"\n Return prediction dir based on file type\n :param file_type: dat or png\n :return: return prediction dir based on file type\n \"\"\"\n if file_type == 'dat':\n return self.dir_model_prediction\n elif file_type == 'png':\n return self.dir_figure\n else:\n raise Exception(\"Unknown format for prediction.\")\n\n def prediction_filename(self, epoch=None, sample=None, gid=None, file_type='dat'):\n \"\"\"\n Return prediction file name\n @param epoch:\n @param sample:\n @param file_type:\n @param gid:\n @return:\n \"\"\"\n _dir = self.prediction_dir_from_type(file_type)\n\n if epoch is not None:\n if gid is None:\n return str(_dir / Path(self.filename_prediction\n + 'epoch' + '_' + str(epoch) + '_'\n + 'sample' + '_' + str(sample) + '.' + file_type))\n else:\n return str(_dir / Path(self.filename_prediction\n + 'epoch' + '_' + str(epoch) + '_'\n + 'sample' + '_' + str(sample) +\n '_gid_' + str(gid) + '.' + file_type))\n\n return self.filename_prediction\n\n def train_filename(self, epoch=None, sample=None, file_type='dat'):\n \"\"\"\n Return file name used for training\n :param epoch:\n :param sample:\n :param file_type:\n :return:\n \"\"\"\n if epoch is not None:\n return str(self.dir_graph_save / Path(self.filename_train\n + 'epoch' + '_' + str(epoch) + '_'\n + 'sample' + '_' + str(sample) + '.' + file_type))\n return self.filename_train\n\n def train_plot_filename(self, epoch=None, sample=None):\n \"\"\"\n\n \"\"\"\n return str(self.dir_figure / Path(self.filename_train))\n\n def test_filename(self, epoch=None, sample=None, file_type='dat'):\n \"\"\"\n\n \"\"\"\n if epoch is not None:\n return str(self.dir_graph_save / Path(self.filename_test\n + 'epoch' + '_' + str(epoch) + '_'\n + 'sample' + '_' + str(sample) + '.' + file_type))\n return self.filename_test\n\n def train_graph_file(self):\n \"\"\"\n Default generated graphs state file.\n \"\"\"\n return self.train_filename(epoch=0, sample=self.sample_time())\n\n def test_graph_file(self):\n \"\"\"\n Default generated test state file.\n \"\"\"\n return self.test_filename(epoch=0, sample=self.sample_time())\n\n def save_timed_trace(self, epoch=None, sample=None, file_type='dat') -> str:\n \"\"\"\n\n \"\"\"\n if epoch is not None:\n return str(self.dir_timing / Path(self.filename_time_traces\n + 'epoch' + '_' + str(epoch) + '_'\n + 'sample' + '_' + str(sample) + '.' + file_type))\n return self.filename_time_traces\n\n def model_node_file_name(self) -> str:\n \"\"\"\n Models checkpoint filename.\n @return:\n \"\"\"\n files_dict = self.model_filenames()\n if 'node_model' in files_dict:\n return files_dict['node_model']\n\n return str(self.dir_graph_save / Path('default_train_node_rnn_state.dat'))\n\n def model_edge_file_name(self) -> str:\n \"\"\"\n Models checkpoint filename.\n @return:\n \"\"\"\n files_dict = self.model_filenames()\n if 'edge_model' in files_dict:\n return files_dict['edge_model']\n\n return str(self.dir_graph_save / Path('default_train_edge_rnn_state.dat'))\n\n def models_list(self):\n \"\"\"\n List of network types and sub-network models used for a given model.\n For example GraphRNN has graph edge and graph node model.\n @return: list of models.\n \"\"\"\n models_types = []\n for k in self.model:\n if k.find('model') != -1:\n models_types.append(k)\n\n def model_filenames(self, file_type='.dat'):\n \"\"\"\n\n Returns dict that hold sub-model name and\n respected checkpoint filename.\n\n @param file_type:\n @return:\n \"\"\"\n models_filenames = {}\n for k in self.model:\n if k.find('model') != -1:\n models_filenames[k] = str(self.model_save_path /\n Path(self.filename + '_' + k + '_' + str(self.load_epoch()) + file_type))\n return models_filenames\n\n def is_dropout(self) -> bool:\n \"\"\"\n TODO\n \"\"\"\n return bool(self.get_config_key('is_dropout'))\n\n def get_optimizer(self, alias_name: str):\n \"\"\"\n Method return optimizer setting.\n :param alias_name: alias name in config. It bind optimizer to model\n :return: dict that hold optimizer settings\n \"\"\"\n return self._optimizers[alias_name]\n\n def read_config(self, debug=False):\n \"\"\"\n\n Parse config file and initialize trainer\n\n :param debug: will output debug into\n :return: nothing\n \"\"\"\n if debug:\n fmtl_print(\"Parsing... \", self.config)\n\n if 'active' not in self.config:\n raise Exception(\"config.yaml must contains valid active settings.\")\n self.active = self.config['active']\n\n if 'graph' not in self.config:\n raise Exception(\"config.yaml must contains corresponding graph settings for {}\".format(self.active))\n\n g_list = self.config['graph']\n if self.active not in g_list:\n raise Exception(\"config.yaml doesn't contain {} template, check config.\".format(self.active))\n\n self.graph_specs = self.config['graph'][self.active]\n\n if 'models' not in self.config:\n raise Exception(\"config.yaml must contain at least one models list and one model.\")\n\n if 'use_model' not in self.config:\n raise Exception(\"config.yaml must contain use_model and it must defined.\")\n\n self.active_model = self.config['use_model']\n self.models = self.config['models']\n\n if self.active_model not in self.models:\n raise Exception(\"config.yaml doesn't contain model {}.\".format(self.active_model))\n\n self.model = self.models[self.active_model]\n\n if 'lr_schedulers' in self.config:\n self.lr_schedulers = self.config['lr_schedulers']\n\n # checks if optimizers setting present\n if 'optimizers' in self.config:\n self._optimizers = self.config['optimizers']\n else:\n raise Exception(\"config.yaml doesn't contain optimizers section. Example {}\".format(_opt_example))\n\n if 'settings' not in self.config:\n raise Exception(\"config.yaml must contain at least one section with a global setting.\")\n\n if 'active_setting' not in self.config:\n raise Exception(\"config.yaml must contain name of the \"\n \"global setting that the trainer must use.\")\n\n # settings stored internally\n if debug:\n fmt_print(\"active setting\", self.config['active_setting'])\n self._active_setting = self.config['active_setting']\n\n _settings = self.config['settings']\n if debug:\n fmt_print(\"Settings list\", _settings)\n\n if self._active_setting not in _settings:\n raise Exception(\"config.yaml use undefined variable {} \".format(self._active_setting))\n\n self._setting = _settings[self._active_setting].copy()\n if debug:\n fmt_print(\"Active settings\", self._setting)\n\n self.inited = True\n\n def read_from_file(self, debug=False):\n \"\"\"\n Read config file and initialize trainer\n \"\"\"\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n with open(self.config_file_name, \"r\") as stream:\n try:\n fmtl_print(\"Reading... \", self.config_file_name)\n self.config = yaml.load(stream, Loader=yaml.FullLoader)\n except yaml.YAMLError as exc:\n print(exc)\n\n self.read_config()\n\n def read_from_stream(self, buffer, debug=False):\n \"\"\"\n Read config file from a stream\n \"\"\"\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n try:\n if self._verbose:\n print(\"Reading from io buffer\")\n self.config = yaml.load(buffer, Loader=yaml.FullLoader)\n except yaml.YAMLError as exc:\n print(exc)\n sys.exit(\"Failed parse yaml\")\n\n self.read_config()\n\n def get_config_key(self, key):\n \"\"\"\n Return generic config element by key\n \"\"\"\n if key in self.config:\n return self.config[key]\n\n def epochs(self) -> int:\n \"\"\"\n Return epochs,\n Note each graph has own total epochs. ( depend on graph size)\n :return: number of epochs to run for given dataset, default 100\n \"\"\"\n if 'epochs' in self.graph_specs:\n return int(self.graph_specs['epochs'])\n return 100\n\n def batch_size(self):\n \"\"\"\n Return batch size, each dataset has own batch size.\n Model batch size\n :return:\n \"\"\"\n if 'batch_size' in self.graph_specs:\n return int(self.graph_specs['batch_size'])\n return 32\n\n def num_layers(self):\n \"\"\"\n\n :return:\n \"\"\"\n if 'num_layers' in self.graph_specs:\n return int(self.graph_specs['num_layers'])\n return 4\n\n def parameter_shrink(self):\n \"\"\"\n\n \"\"\"\n return self.graph_specs['parameter_shrink']\n\n def test_batch_size(self):\n \"\"\"\n\n \"\"\"\n return self.graph_specs['test_batch_size']\n\n def test_total_size(self):\n \"\"\"\n\n \"\"\"\n return self.graph_specs['test_total_size']\n\n def lr(self) -> float:\n \"\"\"\n Models default learning rate, default 0.003\n \"\"\"\n if 'lr' in self.graph_specs:\n float(self.graph_specs['lr'])\n\n return 0.003\n\n def set_lr(self, rate: float):\n \"\"\"\n Adjust learning rate for model, during loading learning rate re-adjusted.\n \"\"\"\n self.graph_specs['ls'] = rate\n\n def lr_rate(self):\n \"\"\"\n\n \"\"\"\n return float(self.graph_specs['lr_rate'])\n\n def set_lr_rate(self, rate: float):\n \"\"\"\n\n :param rate:\n :return:\n \"\"\"\n self.graph_specs['lr_rate'] = rate\n\n def milestones(self):\n \"\"\"\n\n :return:\n \"\"\"\n return self.graph_specs['milestones']\n\n def set_milestones(self, m):\n \"\"\"\n\n :param m:\n :return:\n \"\"\"\n self.graph_specs['milestones'] = m\n\n def load(self) -> bool:\n \"\"\"\n Return true if model must be loaded.\n \"\"\"\n return bool(self.config['load_model'])\n\n def save(self) -> bool:\n \"\"\"\n Return true if model saved during training.\n \"\"\"\n return bool(self.config['save_model'])\n\n def load_epoch(self) -> int:\n \"\"\"\n Setting dictates whether load model or not.\n \"\"\"\n return int(self.config['load_epoch'])\n\n def do_bfs(self) -> bool:\n \"\"\"\n In Graph RNN uses BFS to predict edges for generated nodes.\n Default: True\n \"\"\"\n if 'do_bfs' in self.graph_specs:\n return self.graph_specs['do_bfs']\n return True\n\n def do_randomwalk(self) -> bool:\n \"\"\"\n Alternative approach is to sample random walks,\n Default: False\n \"\"\"\n if 'do_randomwalk' in self.graph_specs:\n return self.graph_specs['do_randomwalk']\n return False\n\n def max_nodes(self) -> int:\n \"\"\"\n Maximum nodes for a graph generation.\n @return:\n \"\"\"\n if 'max_num_node' in self.graph_specs:\n return int(self.graph_specs['max_num_node'])\n else:\n self.graph_specs['max_num_node'] = int(0)\n\n return 0\n\n def max_depth(self) -> int:\n \"\"\"\n Maximum nodes to track in BFS.\n @return: Maximum nodes to track in BFS or zero\n \"\"\"\n if 'max_prev_node' in self.graph_specs:\n return int(self.graph_specs['max_prev_node'])\n else:\n self.graph_specs['max_prev_node'] = int(0)\n\n return 0\n\n def set_max_num_node(self, m: int):\n \"\"\"\n Update max node for Graph\n @param m:\n @return:\n \"\"\"\n self.graph_specs['max_num_node'] = m\n\n def set_max_prev_node(self, m: int):\n \"\"\"\n Update max prev nodes for BFS order\n @param m:\n @return:\n \"\"\"\n self.graph_specs['max_prev_node'] = m\n\n def epochs_log(self) -> int:\n \"\"\"\n\n :return:\n \"\"\"\n \"\"\"\n Setting dictates when to log each epoch statistic.\n @return: Default 100\n \"\"\"\n if self.inited is False:\n raise Exception(\"Training must be initialized first\")\n\n if self._setting is None:\n raise Exception(\"Initialize settings first\")\n\n if 'epochs_log' in self._setting:\n return int(self._setting['epochs_log'])\n\n return 100\n\n def start_test(self) -> int:\n \"\"\"\n Setting dictates when to start sampling at training loop epoch.\n @return: Default 100\n \"\"\"\n if 'start_test' in self._setting:\n return int(self._setting['start_test'])\n return 100\n\n def epochs_test(self) -> int:\n \"\"\"\n Setting dictates when to start predicting at training loop.\n @return: Default 100\n @return:\n \"\"\"\n if 'epochs_test' in self._setting:\n return int(self._setting['epochs_test'])\n return 100\n\n def epochs_save(self) -> int:\n \"\"\"\n Save model at epochs , by default trainer will use early stopping\n TODO add early stopping optional\n \"\"\"\n if 'epochs_save' in self._setting:\n return int(self._setting['epochs_save'])\n return 100\n\n def single_shoot(self) -> bool:\n \"\"\"\n Draw single shoot\n \"\"\"\n if 'single_shoot' in self.config:\n return bool(self.config['single_shoot'])\n return False\n\n def trace_prediction_timer(self) -> bool:\n \"\"\"\n Trace execution timer for prediction\n \"\"\"\n if 'trace_prediction_timer' in self.config:\n return bool(self.config['trace_prediction_timer'])\n return False\n\n def trace_training_timer(self) -> bool:\n \"\"\"\n Trace training timer\n \"\"\"\n if 'trace_training_timer' in self.config:\n return bool(self.config['trace_training_timer'])\n return False\n\n def trace_epocs(self) -> int:\n \"\"\"\n Trace each epocs\n \"\"\"\n if 'trace_epocs' in self.config:\n return int(self.config['trace_epocs'])\n return 0\n\n def num_workers(self) -> int:\n \"\"\"\n Number of worker node used to fetch data from dataset\n \"\"\"\n if 'training' in self.config:\n t = self.config['training']\n if 'sample_time' in t:\n return int(t['num_workers'])\n return 0\n\n def batch_ratio(self) -> int:\n \"\"\"\n Number batches of samples per each epoch, 1 epoch = n batches\n \"\"\"\n if self._batch_ratio is not None:\n return self._batch_ratio\n\n if 'training' in self.config:\n t = self.config['training']\n if 'sample_time' in t:\n self._batch_ratio = int(t['batch_ratio'])\n return self._batch_ratio\n\n self._batch_ratio = 32\n\n return self._batch_ratio\n\n def setup_tensorflow(self):\n \"\"\"\n Setup tensorflow dir\n \"\"\"\n time = strftime(\"%Y-%m-%d-%H\", gmtime())\n fmtl_print(\"tensorboard log dir\", self.log_dir())\n logging.basicConfig(filename=str(self.dir_log / Path('train' + time + '.log')), level=logging.DEBUG)\n if bool(self.config['regenerate']):\n if os.path.isdir(\"tensorboard\"):\n shutil.rmtree(\"tensorboard\")\n self.writer = SummaryWriter()\n return self.writer\n\n def build_dir(self):\n \"\"\"\n Creates all directories required for trainer.\n \"\"\"\n if not os.path.isdir(self.model_save_path):\n os.makedirs(self.model_save_path)\n\n if not os.path.isdir(self.dir_log):\n os.makedirs(self.dir_log)\n\n if not os.path.isdir(self.dir_graph_save):\n os.makedirs(self.dir_graph_save)\n\n if not os.path.isdir(self.dir_figure):\n os.makedirs(self.dir_figure)\n\n if not os.path.isdir(self.dir_timing):\n os.makedirs(self.dir_timing)\n\n if not os.path.isdir(self.dir_model_prediction):\n os.makedirs(self.dir_model_prediction)\n\n # if not os.path.isdir(self.nll_save_path):\n # os.makedirs(self.nll_save_path)\n\n def log_tensorboard(self, loss, epoch, batch_idx):\n \"\"\"\n Write tensorboard logs\n\n @param loss:\n @param epoch:\n @param batch_idx:\n @return:\n \"\"\"\n self.writer.add_scalar('loss_' + self.active_model, loss.item(), epoch * self.batch_ratio() + batch_idx)\n self.writer.flush()\n\n def log_prediction(self, model, graps):\n \"\"\"\n\n \"\"\"\n # graph_list = utils.load_graph_prediction(graps)\n #\n # # grid = torchvision.utils.make_grid(images_buffer_generator(graph_list))\n # # self.writer.add_image(\"images\", grid)\n # for img in images_buffer_generator(graph_list):\n # self.writer.add_image(model, img)\n # # self.writer.add_graph(model, images_buffer_generator(graph_list))\n\n # self.writer.close()\n\n def root_dir(self):\n \"\"\"\n Return root dir where results, dataset stored.\n By default it same dir where we execute code.\n \"\"\"\n return self.config['root_dir']\n\n def results_dir(self) -> str:\n \"\"\"\n Return main directory where all results stored.\n \"\"\"\n if 'results_dir' in self.config:\n return self.config['results_dir']\n return 'results'\n\n def log_dir(self) -> str:\n \"\"\"\n Return directory that used to store logs.\n \"\"\"\n if 'log_dir' in self.config:\n return self.config['log_dir']\n return 'logs'\n\n def graph_dir(self) -> str:\n \"\"\"\n Return directory where store original graphs\n \"\"\"\n if 'graph_dir' in self.config:\n return self.config['graph_dir']\n return 'graphs'\n\n def timing_dir(self) -> str:\n \"\"\"\n Return directory we use to store time traces\n \"\"\"\n if 'timing_dir' in self.config:\n return self.config['timing_dir']\n return 'timing'\n\n def model_save_dir(self) -> str:\n \"\"\"\n Default dir where model checkpoint stored.\n \"\"\"\n if 'model_save_dir' in self.config:\n return self.config['model_save_dir']\n return 'model_save'\n\n def prediction_dir(self) -> str:\n \"\"\"\n Default dir where model prediction serialized.\n \"\"\"\n if 'figures_prediction_dir' in self.config:\n return self.config['figures_prediction_dir']\n\n return 'prediction'\n\n def prediction_figure_dir(self) -> str:\n \"\"\"\n Default dir where model prediction serialized.\n \"\"\"\n if 'figures_prediction_dir' in self.config:\n return self.config['prediction_figures']\n\n return 'prediction'\n\n def figures_dir(self) -> str:\n \"\"\"\n Default dir where test figures serialized.\n \"\"\"\n if 'figures_dir' in self.config:\n return self.config['figures_dir']\n return 'figures'\n\n def test_ratio(self) -> float:\n \"\"\"\n Test ratio for test/validation\n \"\"\"\n if 'training' in self.config:\n t = self.config['training']\n if 'test_ration' in t:\n return float(t['test_ration'])\n return 0.0\n\n def train_ratio(self) -> float:\n \"\"\"\n Train/Test ratio.\n \"\"\"\n if 'training' in self.config:\n t = self.config['training']\n if 'train_ratio' in t:\n return float(t['train_ratio'])\n return 0.0\n\n def validation_ratio(self) -> float:\n \"\"\"\n Validation ratio for test/validation\n \"\"\"\n if 'training' in self.config:\n t = self.config['training']\n if 'validation_ratio' in t:\n return float(t['validation_ratio'])\n return 0.0\n\n def is_train_network(self) -> bool:\n \"\"\"\n Train network or not.\n Default: True\n \"\"\"\n if 'train' in self.config:\n return bool(self.config['train'])\n return True\n\n def is_draw_samples(self) -> bool:\n \"\"\"\n Check if we need draw sample or not after model trained.\n @return:\n \"\"\"\n if 'draw_prediction' in self.config:\n return bool(self.config['draw_prediction'])\n else:\n self.config['draw_prediction'] = True\n\n return True\n\n def set_draw_samples(self, val):\n \"\"\"\n Sets value we need draw sample or not\n after model trained.\n \"\"\"\n if 'draw_prediction' in self.config:\n self.config['draw_prediction'] = val\n else:\n self.config['draw_prediction'] = val\n\n def betas(self, alias_name, default=False) -> [float, float]:\n \"\"\"\n Coefficients used for computing running averages of gradient\n and its square (default: (0.9, 0.999))\n\n :param alias_name:\n :param default:\n :return:\n \"\"\"\n if default is False:\n opt = self.get_optimizer(alias_name)\n if 'betas' in opt:\n return opt['betas']\n return [0.9, 0.999]\n\n def eps(self, alias_name, default=False):\n \"\"\"\n Term added to the denominator to improve numerical stability\n default: 1e-8\n :param alias_name:\n :param default:\n :return:\n \"\"\"\n if default is False:\n opt = self.get_optimizer(alias_name)\n if 'eps' in opt:\n return float(opt['eps'])\n return 1e-8\n\n def weight_decay(self, alias_name: str, default=False) -> float:\n \"\"\"\n\n :param alias_name:\n :param default:\n :return:\n \"\"\"\n if default is False:\n opt = self.get_optimizer(alias_name)\n if 'weight_decay' in opt:\n return float(opt['weight_decay'])\n return float(0)\n\n def optimizer_type(self, alias_name: str, default=False) -> str:\n \"\"\"\n Return optimizer type for a given alias , if default is passed , will return default.\n\n :param alias_name: alias_name/\n :param default: if default value needed\n :return: optimizer type, Default Adam\n \"\"\"\n if default is False:\n opt = self.get_optimizer(alias_name)\n if 'type' in opt:\n return str(opt['type'])\n\n return \"Adam\"\n\n def amsgrad(self, alias_name: str, default=False) -> bool:\n \"\"\"\n Setting dictates whether to use the AMSGrad variant.\n\n :param alias_name:\n :param default:\n :return: true if ams grad must be enabled, default False\n\n \"\"\"\n if default is False:\n opt = self.get_optimizer(alias_name)\n if 'amsgrad' in opt:\n return bool(opt['amsgrad'])\n\n return False\n\n def sample_time(self) -> int:\n \"\"\"\n :return: number of time take sample during prediction.\n \"\"\"\n if 'training' in self.config:\n t = self.config['training']\n if 'sample_time' in t:\n return int(t['sample_time'])\n return 0\n\n def momentum(self, alias_name) -> float:\n \"\"\"\n Moment factor, default 0\n @param alias_name:\n @return: moment factor, default 0\n \"\"\"\n opt = self.get_optimizer(alias_name)\n if 'momentum' in opt:\n return float(opt['momentum'])\n\n return float(0)\n\n def dampening(self, alias_name) -> float:\n \"\"\"\n :return: Dampening for momentum, default 0\n \"\"\"\n opt = self.get_optimizer(alias_name)\n if 'dampening' in opt:\n return float(opt['dampening'])\n return float(0)\n\n def nesterov(self, alias_name) -> bool:\n \"\"\"\n Nesterov momentum,\n Default False\n \"\"\"\n opt = self.get_optimizer(alias_name)\n if 'nesterov' in opt:\n return bool(opt['nesterov'])\n\n return False\n\n def get_model_lr_scheduler(self, model_name) -> str:\n \"\"\"\n\n :param model_name:\n :return:\n \"\"\"\n return self.model[model_name]['lr_scheduler']\n\n def get_model_optimizer(self, model_name) -> str:\n \"\"\"\n Return model optimizer alias name\n :param model_name:\n :return:\n \"\"\"\n return self.model[model_name]['optimizer']\n\n def lr_scheduler(self, alias_name):\n \"\"\"\n Returns lr scheduler by name, each value of lr_scheduler in dict\n :param alias_name: alias name defined in config.\n The purpose of alias bind different scheduler config to model\n :return:\n \"\"\"\n if self.lr_schedulers is not None:\n for elm in self.lr_schedulers:\n spec = elm\n if 'name' in spec and alias_name in spec['name']:\n return spec\n return None\n\n def lr_scheduler_type(self, alias_name):\n \"\"\"\n Returns lr scheduler type.\n :param alias_name: alias_name: alias name defined in config.\n The purpose of alias bind different scheduler config to model\n :return:\n \"\"\"\n scheduler_spec = self.lr_scheduler(alias_name)\n if scheduler_spec is not None:\n if 'type' in scheduler_spec:\n return scheduler_spec['type']\n\n return None\n\n def min_lr(self, alias_name) -> float:\n \"\"\"\n Learning rate of each parameter group using a cosine annealing schedule\n @param alias_name: configuration alias_name defined in config\n @return: Minimum learning rate. Default: 0\n \"\"\"\n opt = self._optimizers[alias_name]\n if 'eta_min' in opt:\n return float(opt['eta_min'])\n else:\n return float(0)\n\n def compute_num_samples(self):\n \"\"\"\n \"\"\"\n return self.batch_size() * self.batch_ratio()\n\n def lr_lambdas(self, alias_name):\n \"\"\"\n A function which computes a multiplicative factor given an integer parameter epoch,\n or a list of such functions, one for each group in optimizer.param_groups.\n @param alias_name: configuration alias_name defined in config\n @return: list\n \"\"\"\n opt = self._optimizers[alias_name]\n if 'lr_lambda' in opt:\n return opt['lr_lambda']\n raise Exception(\"Optimizer has no type defined\")\n\n def is_read_benchmark(self):\n \"\"\"\n TODO\n @return:\n \"\"\"\n if 'debug' in self.config:\n t = self.config['debug']\n if 'benchmark_read' in t:\n return bool(t['benchmark_read'])\n return False\n\n def is_graph_creator_verbose(self) -> bool:\n \"\"\"\n Flag dictates if need trace debug on train graph generation process.\n Default false\n @return:\n \"\"\"\n if 'debug' in self.config:\n t = self.config['debug']\n if 'graph_generator' in t:\n return bool(t['graph_generator'])\n return False\n\n def is_model_verbose(self):\n \"\"\"\n Enables model debug during creation\n @return:\n \"\"\"\n if 'debug' in self.config:\n t = self.config['debug']\n if 'model_creation' in t:\n return bool(t['model_creation'])\n return False\n\n def is_train_verbose(self):\n \"\"\"\n\n @return:\n \"\"\"\n if 'debug' in self.config:\n t = self.config['debug']\n if 'train_verbose' in t:\n return bool(t['train_verbose'])\n return False\n\n def get_active_train_graph(self):\n \"\"\"\n\n \"\"\"\n return self.active\n\n def get_active_train_graph_spec(self):\n \"\"\"\n\n \"\"\"\n return self.graph_specs\n\n def get_active_model_prediction_files(self, reverse=True) -> List[str]:\n \"\"\"\n Method return all prediction model generated.\n \"\"\"\n if not self.is_trained():\n raise Exception(\"Untrained model\")\n\n if not os.path.exists(self.get_prediction_dir()):\n return []\n\n only_files = [f for f in listdir(self.get_prediction_dir())\n if isfile(join(self.get_prediction_dir(), f)) and\n f.find(self.get_active_model()) != -1 and\n f.find(self.get_active_train_graph()) != -1]\n\n # compute position of 'epoch' at runtime\n if len(only_files) > 0:\n pos = only_files[0].find(self._epoch_file_fmt)\n if pos != -1:\n pos = pos + len(self._epoch_file_fmt) + 1\n\n def epoch_sort(x):\n \"\"\"\n Sort file by epoch.\n \"\"\"\n file_suffix = x[pos:]\n if len(file_suffix) > 0:\n tokens = file_suffix.split('_')\n if tokens[0].isnumeric():\n return int(tokens[0])\n\n return 0\n\n only_files.sort(key=epoch_sort, reverse=reverse)\n return only_files\n\n def get_active_model(self) -> str:\n \"\"\"\n Return model that indicate as current active model.\n It important to understand, we can switch between models.\n \"\"\"\n return self.active_model\n\n def get_active_model_spec(self):\n \"\"\"\n Return model specs. Each value is dict.\n \"\"\"\n return self.model\n\n def get_active_model_names(self):\n \"\"\"\n Return model specs. Each value is dict.\n \"\"\"\n return self.model.keys()\n\n def get_last_graph_predictions(self):\n self.get_active_model_prediction_files()\n\n # def compute_basic_stats(real_g_list, target_g_list):\n # dist_degree = eval.stats.degree_stats(real_g_list, target_g_list)\n # dist_clustering = eval.stats.clustering_stats(real_g_list, target_g_list)\n # return dist_degree, dist_clustering\n\n def get_last_graph_stat(self, num_samples=1) -> List[nx.classes.graph.Graph]:\n \"\"\"\n Method return last graph from generated graph list.\n \"\"\"\n files = self.get_active_model_prediction_files()\n last_file = files[0]\n last_file_path = self.get_prediction_dir() / Path(last_file)\n graphs = graph_from_file(last_file_path)\n return graphs\n\n def get_prediction_graph(self, num_samples=1, reverse=False, is_last=False) -> List[nx.classes.graph.Graph]:\n \"\"\"\n Method returns generator / iterator for all prediction files.\n A Caller can iterate each iter call will return one file name.\n Note file are sorted.\n\n :param num_samples:\n :param reverse:\n :param is_last:\n :return:\n \"\"\"\n if is_last is True:\n #TODO check this\n files = self.get_active_model_prediction_files(reverse=reverse)\n epoch = extract_value_from_file(files, \"epoch\")\n sample_time = extract_value_from_file(files, \"sample\")\n graph_file = self.get_prediction_dir() / Path(files)\n yield epoch, sample_time, graph_file, graph_from_file(graph_file)\n\n files = self.get_active_model_prediction_files(reverse=reverse)\n for f in files:\n epoch = extract_value_from_file(f, \"epoch\")\n sample_time = extract_value_from_file(f, \"sample\")\n graph_file = self.get_prediction_dir() / Path(f)\n print(graph_file)\n yield epoch, sample_time, graph_file, graph_from_file(graph_file)\n\n def is_trained(self) -> bool:\n \"\"\"\n Return true if model trainer, it mainly checks if dat file created or not.\n :return: True if trainer\n \"\"\"\n models_filenames = self.model_filenames()\n if self._verbose:\n print(\"Model filenames\", models_filenames)\n\n for k in models_filenames:\n if not os.path.isfile(models_filenames[k]):\n return False\n\n return True\n\n def get_last_saved_epoc(self):\n \"\"\"\n Return last checkpoint saved as dict where key sub-model: last checkpoint\n If model un trained will raise exception\n \"\"\"\n checkpoints = {}\n if self._verbose:\n fmtl_print('Trying load models last checkpoint...', self.active_model)\n\n if not self.is_trained():\n raise Exception(\"Untrained model\")\n\n models_filenames = self.model_filenames()\n if self._verbose:\n print(\"Model filenames\", models_filenames)\n\n for m in models_filenames:\n if self._verbose:\n print(\"Trying to load checkpoint file\", models_filenames[m])\n\n check = torch.load(models_filenames[m])\n if self._verbose:\n print(check.keys())\n\n if 'epoch' in check:\n checkpoints[m] = check['epoch']\n\n return checkpoints\n\n # def load_models(self, model):\n # \"\"\"\n # TODO\n # \"\"\"\n # checkpoints = {}\n # models_filenames = self.model_filenames()\n # print('Trying load models last checkpoint...')\n # models_filenames = self.model_filenames()\n # print(\"Model filenames\", models_filenames)\n # for m in models_filenames:\n # checkpoints[m] = torch.load(models_filenames[m])\n # model.state.rnn.load_state_dict(checkpoint['model_state_dict'])\n # model.optimizer_rnn.load_state_dict(checkpoints[m]['optimizer_state_dict'])\n # model.scheduler_rnn.load_state_dict(checkpoints[m]['optimizer_state_dict'])\n\n # return checkpoints\n def generate_prediction_figure_name(self, epoch, gid=None, sample_time=1, file_type='png'):\n \"\"\"\n\n \"\"\"\n return self.prediction_filename(epoch, sample=sample_time, gid=gid, file_type=file_type)\n\n def load_train_test(self):\n \"\"\"\n \"\"\"\n return graph_from_file(self.train_graph_file()), graph_from_file(self.train_graph_file())\n\n def is_evaluate(self) -> bool:\n \"\"\"\n Return true if we need evaluate a model after a training.\n \"\"\"\n if 'evaluate' in self.config:\n return bool(self.config['evaluate'])\n\n return False\n\n def done(self):\n self.writer.close()\n\n def get_model_submodels(self) -> List[str]:\n \"\"\"\n @return: Return list of all sub models.\n \"\"\"\n keys = self.model.keys()\n return [k for k in keys]\n\n def get_optimizer_type(self, optimizer_alias_name):\n \"\"\"\n Method return optimizer type\n :param optimizer_alias_name:\n :return:\n \"\"\"\n opt = self._optimizers[optimizer_alias_name]\n if 'type' in opt:\n return opt['type']\n raise Exception(\"Optimizer has no type defined\")\n\n def is_early_stopping(self) -> bool:\n \"\"\"\n Return true if early stopping enabled.\n :return: default value False\n \"\"\"\n if self._setting is None:\n raise Exception(\"Initialize settings first\")\n\n if 'early_stopping' in self._setting:\n return True\n\n return False\n\n def get_patience(self) -> int:\n \"\"\"\n Number of epochs with no improvement after which training will be stopped.\n :return: default value False\n \"\"\"\n if 'early_stopping' in self.config:\n stopping = self.config['early_stopping']\n if 'patience' in stopping:\n return int(stopping['patience'])\n\n return False\n\n def mmd_degree(self) -> bool:\n \"\"\"\n\n :return:\n \"\"\"\n if 'metrics' in self.config:\n metrics = self.config['metrics']\n if 'degree' in metrics:\n return metrics['degree']\n return False\n\n def is_log_lr_rate(self):\n \"\"\"\n TODO\n :return:\n \"\"\"\n True\n\n def mmd_clustering(self) -> bool:\n \"\"\"\n @return: Return true of clustering statistic need to be collected.\n \"\"\"\n if 'metrics' in self.config:\n metrics = self.config['metrics']\n if 'clustering' in metrics:\n return metrics['clustering']\n return False\n\n def mmd_orbits(self) -> bool:\n \"\"\"\n @return: Return true of orbits statistic need to be collected.\n \"\"\"\n if 'metrics' in self.config:\n metrics = self.config['metrics']\n if 'orbits' in metrics:\n return bool(metrics['orbits'])\n\n return False\n\n def tensorboard_sample_update(self):\n \"\"\"\n Return true if early stopping enabled.\n :return: default value False\n \"\"\"\n if self._setting is None:\n raise Exception(\"Initialize settings first\")\n\n if 'early_stopping' in self._setting:\n return True\n\n def set_depth(self, graph_depth):\n \"\"\"\n Sets a graph depth.\n @param graph_depth:\n @return:\n \"\"\"\n if 'max_prev_node' in self.graph_specs:\n self.graph_specs['max_prev_node'] = graph_depth\n else:\n self.graph_specs['max_prev_node'] = graph_depth\n\n\n def H_inp(self):\n \"\"\"\n Input size of the LSTM-Cells\n @return:\n \"\"\"\n pass\n\n def H_gen(self):\n \"\"\"\n The hidden_size of the generator.\n @return: int, default: 40\n\n \"\"\"\n return 40\n\n def rw_len(self):\n pass\n\n def z_dim(self):\n pass\n\n def temp_start(self):\n pass\n\n def H_disc(self):\n pass\n\n def N(self):\n pass\n"
] |
[
[
"torch.cuda.is_available",
"torch.utils.tensorboard.SummaryWriter",
"torch.load"
]
] |
kristofgiber/lingvo
|
[
"4c6405a3c8b29764918dbfb599212dd7620ccf9c",
"4c6405a3c8b29764918dbfb599212dd7620ccf9c"
] |
[
"lingvo/core/layers_test.py",
"lingvo/core/recurrent_test.py"
] |
[
"# Lint as: python2, python3\n# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for layers.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\n\nfrom absl.testing import parameterized\nimport lingvo.compat as tf\nfrom lingvo.core import gpipe\nfrom lingvo.core import layers\nfrom lingvo.core import py_utils\nfrom lingvo.core import quant_utils\nfrom lingvo.core import test_utils\nimport numpy as np\nfrom six.moves import range\nfrom six.moves import zip\n\nfrom tensorflow.python.framework import ops\n\n\nclass ActivationsTest(test_utils.TestCase):\n\n def testGeluActivation(self):\n with self.session(use_gpu=True):\n inputs = tf.constant(\n np.linspace(-10.0, 10.0, num=21, dtype='float32'), dtype=tf.float32)\n grads_gelu = tf.gradients(layers.Gelu(inputs), inputs)\n grads_relu = tf.gradients(tf.nn.relu(inputs), inputs)\n\n self.assertEqual(0.0,\n layers.Gelu(tf.constant(-10.0, dtype='float32')).eval())\n self.assertEqual(0.0,\n layers.Gelu(tf.constant(0.0, dtype='float32')).eval())\n self.assertEqual(10.0,\n layers.Gelu(tf.constant(10.0, dtype='float32')).eval())\n actual_grads_gelu = grads_gelu[0].eval()\n actual_grads_relu = grads_relu[0].eval()\n\n self.assertAllClose(actual_grads_gelu[-5:], actual_grads_relu[-5:])\n self.assertAllClose(actual_grads_gelu[:5], actual_grads_relu[:5])\n\n # pyformat: disable\n # pylint: disable=bad-whitespace\n expected_grads_gelu = [\n -7.69459925e-22, -9.25176121e-18, -4.04182472e-14, -6.39430453e-11,\n -3.64552299e-08, -7.13557529e-06, -5.03641320e-04, -1.19456425e-02,\n -8.52318183e-02, -8.33154917e-02, 5.00000000e-01, 1.08331549e+00,\n 1.08523178e+00, 1.01194561e+00, 1.00050366e+00, 1.00000715e+00,\n 1.00000000e+00, 1.00000000e+00, 1.00000000e+00, 1.00000000e+00,\n 1.00000000e+00]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n self.assertAllClose(expected_grads_gelu, actual_grads_gelu)\n\n\nclass BatchNormLayerTest(test_utils.TestCase):\n\n def testBatchNormLayerConstruction(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.BatchNormLayer.Params()\n params.name = 'bn'\n params.dim = 2\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n layers.BatchNormLayer(params)\n bn_vars = tf.get_collection('BatchNormLayer_vars')\n bn_var_names = [x.name for x in bn_vars]\n expected_var_names = [\n 'bn/beta/var:0', 'bn/gamma/var:0', 'bn/moving_mean/var:0',\n 'bn/moving_variance/var:0'\n ]\n self.assertEqual(expected_var_names, bn_var_names)\n\n def testBatchNormLayerMoments(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n\n in_padding1 = tf.zeros([2, 2, 8, 1], dtype=tf.float32)\n bn_in1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 2, 8, 2]), dtype=tf.float32)\n mean1, var1 = layers.BatchNormLayer._Moments(bn_in1, 1.0 - in_padding1)\n mean2, var2 = tf.nn.moments(bn_in1, [0, 1, 2])\n\n in_padding2 = tf.ones([2, 2, 8, 1], dtype=tf.float32)\n bn_in2 = tf.constant(\n np.random.normal(-0.3, 1.0, [2, 2, 8, 2]), dtype=tf.float32)\n in_padding3 = tf.concat([in_padding1, in_padding2], 1)\n bn_in3 = tf.concat([bn_in1, bn_in2], 1)\n mean3, var3 = layers.BatchNormLayer._Moments(bn_in3, 1.0 - in_padding3)\n mean4, var4 = tf.nn.moments(bn_in3, [0, 1, 2])\n\n mean_diff = tf.reduce_sum(tf.square(mean3 - mean4))\n var_diff = tf.reduce_sum(tf.square(var3 - var4))\n\n tf.global_variables_initializer().run()\n\n self.assertAllClose(mean2.eval(), mean1.eval())\n self.assertAllClose(var2.eval(), var1.eval())\n self.assertAllClose(mean3.eval(), mean1.eval())\n self.assertAllClose(var3.eval(), var1.eval())\n # Since tf.nn.moments() doesn't support padding, it is expected to produce\n # different results than our own implementation (of moments).\n self.assertAllClose(0.095987, mean_diff.eval())\n self.assertAllClose(0.364456, var_diff.eval())\n\n def testBatchNormLayerFProp(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.BatchNormLayer.Params()\n params.name = 'bn'\n params.dim = 3\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n\n bn_layer = layers.BatchNormLayer(params)\n in_padding1 = tf.zeros([2, 8, 1], dtype=tf.float32)\n bn_in1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 8, 3]), dtype=tf.float32)\n\n bn_out = bn_layer.FPropDefaultTheta(bn_in1, in_padding1)\n sig1 = tf.reduce_sum(bn_out)\n sig2 = tf.reduce_sum(bn_out * bn_out)\n tf.global_variables_initializer().run()\n self.assertAllClose(0.0, sig1.eval(), atol=1e-5)\n self.assertAllClose(47.8371887, sig2.eval())\n\n def testBatchNormLayerFPropUseGlobalStatsForTraining(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.BatchNormLayer.Params()\n params.name = 'bn'\n params.dim = 3\n params.use_moving_avg_in_training = True\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n\n bn_layer = layers.BatchNormLayer(params)\n in_padding1 = tf.zeros([2, 8, 1], dtype=tf.float32)\n bn_in1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 8, 3]), dtype=tf.float32)\n\n bn_out = bn_layer.FPropDefaultTheta(bn_in1, in_padding1)\n sig1 = tf.reduce_sum(bn_out)\n sig2 = tf.reduce_sum(bn_out * bn_out)\n tf.global_variables_initializer().run()\n self.assertAllClose(2.6593573, sig1.eval(), atol=1e-5)\n self.assertAllClose(15.464208, sig2.eval())\n\n def testBatchNormLayerMomentsForConv(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n\n in_padding1 = tf.zeros([2, 8, 1, 1], dtype=tf.float32)\n bn_in1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 8, 4, 3]), dtype=tf.float32)\n mean1, var1 = layers.BatchNormLayer._Moments(bn_in1, 1.0 - in_padding1)\n mean2, var2 = tf.nn.moments(bn_in1, [0, 1, 2])\n\n in_padding2 = tf.ones([2, 8, 1, 1], dtype=tf.float32)\n bn_in2 = tf.constant(\n np.random.normal(-0.3, 1.0, [2, 8, 4, 3]), dtype=tf.float32)\n in_padding3 = tf.concat([in_padding1, in_padding2], 1)\n bn_in3 = tf.concat([bn_in1, bn_in2], 1)\n mean3, var3 = layers.BatchNormLayer._Moments(bn_in3, 1.0 - in_padding3)\n mean4, var4 = tf.nn.moments(bn_in3, [0, 1, 2])\n\n mean_diff = tf.reduce_sum(tf.square(mean3 - mean4))\n var_diff = tf.reduce_sum(tf.square(var3 - var4))\n\n tf.global_variables_initializer().run()\n\n self.assertAllClose(mean2.eval(), mean1.eval())\n self.assertAllClose(var2.eval(), var1.eval())\n self.assertAllClose(mean3.eval(), mean1.eval())\n self.assertAllClose(var3.eval(), var1.eval())\n self.assertAllClose(0.1726295, mean_diff.eval())\n self.assertAllClose(0.5592572093009949, var_diff.eval())\n\n def testBatchNormLayerFPropForConv(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.BatchNormLayer.Params()\n params.name = 'bn_conv'\n params.dim = 32\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n\n bn_layer = layers.BatchNormLayer(params)\n in_padding1 = tf.zeros([2, 8, 1, 1], dtype=tf.float32)\n bn_in1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 8, 4, 32]), dtype=tf.float32)\n\n bn_out = bn_layer.FPropDefaultTheta(bn_in1, in_padding1)\n sig1 = tf.reduce_sum(bn_out)\n sig2 = tf.reduce_sum(bn_out * bn_out)\n tf.global_variables_initializer().run()\n self.assertAllClose(0.0, sig1.eval(), atol=1e-4)\n self.assertAllClose(2039.398681, sig2.eval())\n\n\nclass ConvLayerTest(test_utils.TestCase):\n \"\"\"Tests conv layers.\n\n Note that there are multiple subclasses of BaseConv2DLayer and most cases\n are tested via the concrete Conv2DLayer. Other tests are done against\n other subclasses to cover key differences.\n \"\"\"\n\n def testConv2DLayerConstruction(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.Conv2DLayer.Params()\n params.name = 'conv'\n params.filter_shape = [3, 3, 3, 32]\n params.filter_stride = [2, 2]\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n layers.Conv2DLayer(params)\n conv_vars = tf.get_collection('Conv2DLayer_vars')\n conv_var_names = [x.name for x in conv_vars]\n expected_var_names = ['conv/w/var:0']\n self.assertEqual(expected_var_names, conv_var_names)\n bn_vars = tf.get_collection('BatchNormLayer_vars')\n bn_var_names = [x.name for x in bn_vars]\n expected_var_names = [\n 'conv/beta/var:0', 'conv/gamma/var:0', 'conv/moving_mean/var:0',\n 'conv/moving_variance/var:0'\n ]\n self.assertEqual(expected_var_names, bn_var_names)\n\n def testDepthwiseConv2DLayerConstruction(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.DepthwiseConv2DLayer.Params()\n params.name = 'conv'\n params.filter_shape = [3, 3, 3, 32]\n params.filter_stride = [2, 2]\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n layers.DepthwiseConv2DLayer(params)\n conv_vars = tf.get_collection('DepthwiseConv2DLayer_vars')\n conv_var_names = [x.name for x in conv_vars]\n expected_var_names = ['conv/w/var:0']\n self.assertEqual(expected_var_names, conv_var_names)\n bn_vars = tf.get_collection('BatchNormLayer_vars')\n bn_var_names = [x.name for x in bn_vars]\n expected_var_names = [\n 'conv/beta/var:0', 'conv/gamma/var:0', 'conv/moving_mean/var:0',\n 'conv/moving_variance/var:0'\n ]\n self.assertEqual(expected_var_names, bn_var_names)\n\n def testSeparableConv2DLayerConstruction(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.SeparableConv2DLayer.Params()\n params.name = 'conv'\n params.filter_shape = [3, 3, 3, 32]\n params.filter_stride = [2, 2]\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n params.Instantiate()\n # Vars for the outer conv layer.\n conv_vars = tf.get_collection('SeparableConv2DLayer_vars')\n conv_var_names = [x.name for x in conv_vars]\n expected_var_names = ['conv/w/var:0']\n self.assertSetEqual(set(expected_var_names), set(conv_var_names))\n # Vars for the inner depthwise layer.\n conv_vars = tf.get_collection('DepthwiseConv2DLayer_vars')\n conv_var_names = [x.name for x in conv_vars]\n expected_var_names = ['conv/depthwise_conv/w/var:0']\n self.assertSetEqual(set(expected_var_names), set(conv_var_names))\n bn_vars = tf.get_collection('BatchNormLayer_vars')\n bn_var_names = [x.name for x in bn_vars]\n expected_var_names = [\n # Outer conv batchnorm.\n 'conv/beta/var:0',\n 'conv/gamma/var:0',\n 'conv/moving_mean/var:0',\n 'conv/moving_variance/var:0',\n # Inner depthwise batchnorm.\n 'conv/depthwise_conv/beta/var:0',\n 'conv/depthwise_conv/gamma/var:0',\n 'conv/depthwise_conv/moving_mean/var:0',\n 'conv/depthwise_conv/moving_variance/var:0',\n ]\n self.assertSetEqual(set(expected_var_names), set(bn_var_names))\n\n def testConv2DLayerWithBiasConstruction(self):\n \"\"\"Tests Conv2DLayer with only bias and without batch normalization.\"\"\"\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.Conv2DLayer.Params()\n params.name = 'conv'\n params.filter_shape = [3, 3, 3, 32]\n params.filter_stride = [2, 2]\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n params.bias = True\n params.batch_norm = False\n layers.Conv2DLayer(params)\n conv_vars = tf.get_collection('Conv2DLayer_vars')\n conv_var_names = [x.name for x in conv_vars]\n # Has both 'w' and 'b'.\n expected_var_names = ['conv/w/var:0', 'conv/b/var:0']\n self.assertEqual(expected_var_names, conv_var_names)\n # No BatchNorm variables.\n bn_vars = tf.get_collection('BatchNormLayer_vars')\n bn_var_names = [x.name for x in bn_vars]\n expected_var_names = []\n self.assertEqual(expected_var_names, bn_var_names)\n\n def testDepthwiseConv2DLayerWithBiasConstruction(self):\n \"\"\"Tests DepthwiseConv2D with only bias and without batch normalization.\"\"\"\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.DepthwiseConv2DLayer.Params()\n params.name = 'conv'\n params.filter_shape = [3, 3, 3, 32]\n params.filter_stride = [2, 2]\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n params.bias = True\n params.batch_norm = False\n layers.DepthwiseConv2DLayer(params)\n conv_vars = tf.get_collection('DepthwiseConv2DLayer_vars')\n conv_var_names = [x.name for x in conv_vars]\n # Has both 'w' and 'b'.\n expected_var_names = ['conv/w/var:0', 'conv/b/var:0']\n self.assertEqual(expected_var_names, conv_var_names)\n # No BatchNorm variables.\n bn_vars = tf.get_collection('BatchNormLayer_vars')\n bn_var_names = [x.name for x in bn_vars]\n expected_var_names = []\n self.assertEqual(expected_var_names, bn_var_names)\n\n def testConv2DLayerOutShape(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.Conv2DLayer.Params()\n params.name = 'conv'\n params.filter_shape = [3, 3, 3, 32]\n params.filter_stride = [2, 2]\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n conv_layer = layers.Conv2DLayer(params)\n in_shape = [None, None, 10, 3]\n out_shape = conv_layer.OutShape(in_shape)\n self.assertEqual(out_shape, [None, None, 5, 32])\n in_shape = [None, 20, 10, 3]\n out_shape = conv_layer.OutShape(in_shape)\n self.assertEqual(out_shape, [None, 10, 5, 32])\n\n def testDepthwiseConv2DLayerOutShape(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.DepthwiseConv2DLayer.Params()\n params.name = 'conv'\n params.filter_shape = [3, 3, 3, 32]\n params.filter_stride = [2, 2]\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n conv_layer = layers.DepthwiseConv2DLayer(params)\n in_shape = [None, None, 10, 3]\n out_shape = conv_layer.OutShape(in_shape)\n self.assertEqual(out_shape, [None, None, 5, 96])\n in_shape = [None, 20, 10, 3]\n out_shape = conv_layer.OutShape(in_shape)\n self.assertEqual(out_shape, [None, 10, 5, 96])\n\n def testSeparableConv2DLayerOutShape(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.SeparableConv2DLayer.Params()\n params.name = 'conv'\n params.filter_shape = [3, 3, 3, 32]\n params.filter_stride = [2, 2]\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n conv_layer = params.Instantiate()\n in_shape = [None, None, 10, 3]\n out_shape = conv_layer.OutShape(in_shape)\n self.assertEqual(out_shape, [None, None, 5, 32])\n in_shape = [None, 20, 10, 3]\n out_shape = conv_layer.OutShape(in_shape)\n self.assertEqual(out_shape, [None, 10, 5, 32])\n\n def testConv2DLayerWithDilationOutShape(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.Conv2DLayer.Params()\n params.name = 'conv'\n params.filter_shape = [3, 3, 3, 32]\n params.filter_stride = [1, 1]\n params.dilation_rate = [2, 2]\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n conv_layer = layers.Conv2DLayer(params)\n # dilation_rate does not change output shape.\n in_shape = [None, None, 10, 3]\n out_shape = conv_layer.OutShape(in_shape)\n self.assertEqual(out_shape, [None, None, 10, 32])\n in_shape = [None, 20, 10, 3]\n out_shape = conv_layer.OutShape(in_shape)\n self.assertEqual(out_shape, [None, 20, 10, 32])\n\n def testDepthwiseConv2DLayerWithDilationOutShape(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.DepthwiseConv2DLayer.Params()\n params.name = 'conv'\n params.filter_shape = [3, 3, 3, 32]\n params.filter_stride = [1, 1]\n params.dilation_rate = [2, 2]\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n conv_layer = layers.DepthwiseConv2DLayer(params)\n # dilation_rate does not change output shape.\n in_shape = [None, None, 10, 3]\n out_shape = conv_layer.OutShape(in_shape)\n self.assertEqual(out_shape, [None, None, 10, 96])\n in_shape = [None, 20, 10, 3]\n out_shape = conv_layer.OutShape(in_shape)\n self.assertEqual(out_shape, [None, 20, 10, 96])\n\n def testSeparableConv2DLayerWithDilationOutShape(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.SeparableConv2DLayer.Params()\n params.name = 'conv'\n params.filter_shape = [3, 3, 3, 32]\n params.filter_stride = [1, 1]\n params.dilation_rate = [2, 2]\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n conv_layer = params.Instantiate()\n # dilation_rate does not change output shape.\n in_shape = [None, None, 10, 3]\n out_shape = conv_layer.OutShape(in_shape)\n self.assertEqual(out_shape, [None, None, 10, 32])\n in_shape = [None, 20, 10, 3]\n out_shape = conv_layer.OutShape(in_shape)\n self.assertEqual(out_shape, [None, 20, 10, 32])\n\n def testConvPoolComputeOutPadding(self):\n with self.session(use_gpu=True):\n in_padding = tf.constant(\n [[0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0],\n [0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0]],\n dtype=tf.float32)\n out_padding = layers._ComputeConvOutputPadding(in_padding, 2, 2)\n expected_out_padding = [[1, 1, 0, 0, 0, 1, 1, 0],\n [1, 1, 0, 0, 0, 1, 1, 0]]\n\n tf.global_variables_initializer().run()\n self.assertAllClose(expected_out_padding, out_padding.eval().tolist())\n\n def testConvPoolComputeOutPaddingUnevenStride(self):\n with self.session(use_gpu=True):\n in_padding = tf.constant([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1],\n [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1]],\n dtype=tf.float32)\n out_padding = layers._ComputeConvOutputPadding(in_padding, 3, 3)\n expected_out_padding = [[0, 0, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 1, 1, 1]]\n\n tf.global_variables_initializer().run()\n self.assertAllClose(expected_out_padding, out_padding.eval().tolist())\n\n def _checkConvLayerShapes(self,\n input_shape,\n filter_shape,\n filter_stride,\n dilation_rate=None,\n depth_multiplier=None,\n params_builder=layers.Conv2DLayer.Params):\n g = tf.Graph()\n with g.as_default():\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = params_builder()\n params.name = 'conv'\n params.filter_shape = filter_shape\n params.filter_stride = filter_stride\n if dilation_rate:\n params.dilation_rate = dilation_rate\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n if depth_multiplier is not None:\n params.depth_multiplier = depth_multiplier\n conv_layer = params.Instantiate()\n\n inp = tf.random_uniform(input_shape)\n inp_pad = tf.floor(0.5 + tf.random_uniform(input_shape[:2]))\n out, out_pad = conv_layer.FPropDefaultTheta(inp, inp_pad)\n\n with self.session(use_gpu=True, graph=g) as sess:\n tf.global_variables_initializer().run()\n out, out_pad = sess.run([out, out_pad])\n print(out.shape, out_pad.shape)\n # We expect conv_layer.OutShape can compute the actual output shape.\n self.assertAllEqual(out.shape, conv_layer.OutShape(inp.shape.as_list()))\n # We expect out_pad.shape matches the 1st 2 dimensions of out.\n self.assertAllEqual(out.shape[:2], out_pad.shape)\n\n def testConv2DLayerOutputShapes(self):\n self._checkConvLayerShapes([2, 4, 4, 3], [3, 3, 3, 32], [1, 1])\n self._checkConvLayerShapes([2, 4, 4, 3], [3, 3, 3, 32], [2, 2])\n self._checkConvLayerShapes([2, 10, 4, 3], [3, 3, 3, 32], [3, 3])\n\n self._checkConvLayerShapes([2, 10, 4, 3], [3, 3, 3, 32], [1, 1],\n dilation_rate=[2, 2])\n self._checkConvLayerShapes([2, 10, 4, 3], [3, 3, 3, 32], [1, 1],\n dilation_rate=[3, 3])\n\n def testDepthwiseConv2DLayerOutputShapes(self):\n self._checkConvLayerShapes(\n [2, 4, 4, 3], [3, 3, 3, 32], [1, 1],\n params_builder=layers.DepthwiseConv2DLayer.Params)\n self._checkConvLayerShapes(\n [2, 4, 4, 3], [3, 3, 3, 32], [2, 2],\n params_builder=layers.DepthwiseConv2DLayer.Params)\n self._checkConvLayerShapes(\n [2, 10, 4, 3], [3, 3, 3, 32], [3, 3],\n params_builder=layers.DepthwiseConv2DLayer.Params)\n\n self._checkConvLayerShapes(\n [2, 10, 4, 3], [3, 3, 3, 32], [1, 1],\n dilation_rate=[2, 2],\n params_builder=layers.DepthwiseConv2DLayer.Params)\n self._checkConvLayerShapes(\n [2, 10, 4, 3], [3, 3, 3, 32], [1, 1],\n dilation_rate=[3, 3],\n params_builder=layers.DepthwiseConv2DLayer.Params)\n\n def testSeparableConv2DLayerOutputShapes(self):\n self._checkConvLayerShapes(\n [2, 4, 4, 3], [3, 3, 3, 32], [1, 1],\n params_builder=layers.SeparableConv2DLayer.Params)\n self._checkConvLayerShapes(\n [2, 4, 4, 3], [3, 3, 3, 32], [2, 2],\n params_builder=layers.SeparableConv2DLayer.Params)\n self._checkConvLayerShapes(\n [2, 10, 4, 3], [3, 3, 3, 32], [3, 3],\n params_builder=layers.SeparableConv2DLayer.Params)\n # Dilations.\n self._checkConvLayerShapes(\n [2, 10, 4, 3], [3, 3, 3, 32], [1, 1],\n dilation_rate=[2, 2],\n params_builder=layers.SeparableConv2DLayer.Params)\n self._checkConvLayerShapes(\n [2, 10, 4, 3], [3, 3, 3, 32], [1, 1],\n dilation_rate=[3, 3],\n params_builder=layers.SeparableConv2DLayer.Params)\n # Depth multiplier.\n self._checkConvLayerShapes(\n [2, 4, 4, 3], [3, 3, 3, 32], [1, 1],\n params_builder=layers.SeparableConv2DLayer.Params,\n depth_multiplier=2)\n self._checkConvLayerShapes(\n [2, 4, 4, 3], [3, 3, 3, 32], [2, 2],\n params_builder=layers.SeparableConv2DLayer.Params,\n depth_multiplier=6)\n self._checkConvLayerShapes(\n [2, 10, 4, 3], [3, 3, 3, 32], [3, 3],\n params_builder=layers.SeparableConv2DLayer.Params,\n depth_multiplier=12)\n\n def _evalConvLayerFProp(self,\n params_builder=layers.Conv2DLayer.Params,\n batch_norm=True,\n weight_norm=False,\n bias=False,\n activation='RELU',\n conv_last=False,\n strides=(2, 2),\n dilation_rate=(1, 1),\n bn_fold_weights=False,\n is_eval=False,\n quantized=False):\n self._ClearCachedSession()\n tf.reset_default_graph()\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = params_builder()\n params.name = 'conv'\n params.filter_shape = [3, 3, 3, 2]\n params.filter_stride = strides\n params.dilation_rate = dilation_rate\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.conv_last = conv_last\n params.batch_norm = batch_norm\n params.bn_fold_weights = bn_fold_weights\n params.weight_norm = weight_norm\n params.bias = bias\n params.activation = activation\n params.is_eval = is_eval\n\n if quantized:\n params.qdomain.default = quant_utils.PassiveAsymQDomain.Params()\n\n conv_layer = params.Instantiate()\n in_padding1 = tf.zeros([2, 4], dtype=tf.float32)\n inputs1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 4, 4, 3]), dtype=tf.float32)\n\n output1, _ = conv_layer.FPropDefaultTheta(inputs1, in_padding1)\n output2, _ = conv_layer.FPropDefaultTheta(inputs1)\n tf.global_variables_initializer().run()\n v1, v2 = sess.run([output1, output2])\n self.assertAllClose(v1, v2)\n return v1\n\n def testConv2DLayerFProp(self):\n # pyformat: disable\n # pylint: disable=bad-whitespace\n expected_output1 = [\n [[[ 0.36669245, 0.91488785],\n [ 0.07532132, 0. ]],\n [[ 0.34952009, 0. ],\n [ 1.91783941, 0. ]]],\n [[[ 0.28304493, 0. ],\n [ 0. , 0. ]],\n [[ 0. , 0.86575812],\n [ 0. , 1.60203481]]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n actual = self._evalConvLayerFProp()\n print('actual = ', np.array_repr(actual))\n self.assertAllClose(expected_output1, actual)\n\n def testDepthwiseConv2DLayerFProp(self):\n # pyformat: disable\n # pylint: disable=bad-whitespace\n expected_output1 = [\n [[[ 0.93514717, 0.35602099, 0. , 0.51261222, 0. ,\n 1.4310323 ],\n [ 0. , 0. , 0.49176404, 0. , 1.01494753,\n 0.51337928]],\n [[ 0.62087697, 0.34572476, 0. , 0.19352221, 0.47142431,\n 0. ],\n [ 0.81119895, 1.00890303, 0.90471351, 0. , 1.22736526,\n 0. ]]],\n [[[ 0. , 0. , 0.48927376, 0. , 0.74019426,\n 0. ],\n [ 0. , 0. , 1.49952257, 0. , 0. ,\n 0. ]],\n [[ 0.29156703, 0. , 0. , 1.14509106, 0. ,\n 0.74238932],\n [ 0.91312039, 1.39783907, 0. , 1.47650909, 0. ,\n 0.37969294]]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n actual = self._evalConvLayerFProp(\n params_builder=layers.DepthwiseConv2DLayer.Params)\n print('actual = ', np.array_repr(actual))\n self.assertAllClose(expected_output1, actual)\n\n def testSeparableConv2DLayerFProp(self):\n # pyformat: disable\n # pylint: disable=bad-whitespace\n expected_output1 =[\n [[[ 0.39866772, 0. ],\n [ 1.36471784, 0. ]],\n [[ 0. , 0. ],\n [ 0. , 0. ]]],\n [[[ 1.15356529, 0.1036691 ],\n [ 0.12865055, 0.61244327]],\n [[ 0.03609803, 1.81620765],\n [ 0. , 0.23052886]]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n actual = self._evalConvLayerFProp(\n params_builder=layers.SeparableConv2DLayer.Params)\n print('actual = ', np.array_repr(actual))\n self.assertAllClose(expected_output1, actual)\n\n def testConv2DLayerWithDilationFProp(self):\n # pyformat: disable\n # pylint: disable=bad-whitespace\n expected_output1 = [\n [[[ 0. , 0.48857123],\n [ 1.07320869, 0. ],\n [ 0. , 0.1550007 ],\n [ 0. , 1.59097648]],\n [[ 0. , 0. ],\n [ 0.20024362, 0. ],\n [ 0. , 0.64265913],\n [ 1.52903616, 0. ]],\n [[ 0.099805 , 0. ],\n [ 0. , 0.61720949],\n [ 1.31608474, 0. ],\n [ 0. , 0. ]],\n [[ 0.0175612 , 0. ],\n [ 0. , 0.17234094],\n [ 0.21719536, 0. ],\n [ 1.68514931, 0. ]]],\n [[[ 1.45240796, 0. ],\n [ 0. , 0. ],\n [ 0.72675145, 1.971596 ],\n [ 0. , 0.01062769]],\n [[ 0. , 1.70299017],\n [ 1.36936104, 1.29897082],\n [ 1.40132439, 1.74345171],\n [ 0.02585058, 0.29061913]],\n [[ 0. , 0. ],\n [ 0.32962656, 0.05025356],\n [ 0. , 0. ],\n [ 0. , 0. ]],\n [[ 0.97244394, 0. ],\n [ 0.23401484, 0.5722279 ],\n [ 0. , 0.40940297],\n [ 0. , 0.52711827]]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n actual = self._evalConvLayerFProp(strides=[1, 1], dilation_rate=[2, 2])\n print('testConvLayerWithDilationFProp actual = ', np.array_repr(actual))\n self.assertAllClose(expected_output1, actual)\n\n def testSeparableConv2DLayerWithDilationFProp(self):\n # pyformat: disable\n # pylint: disable=bad-whitespace\n expected_output1 = [\n [[[ 0.21535617, 0.86965537],\n [ 2.11499524, 1.2463783 ],\n [ 0. , 0.39275286],\n [ 0. , 0. ]],\n [[ 1.12706482, 1.37450278],\n [ 0. , 0. ],\n [ 0. , 0. ],\n [ 1.2390101 , 0.22932449]],\n [[ 0. , 0. ],\n [ 0.15051894, 1.32616639],\n [ 0. , 0. ],\n [ 0.72912866, 0.47753802]],\n [[ 0.91655868, 0. ],\n [ 0.88526261, 0.26690534],\n [ 0. , 0.26084688],\n [ 0.42923039, 0. ]]],\n [[[ 0.82440329, 0. ],\n [ 0.49015623, 0.52662987],\n [ 0. , 0. ],\n [ 0.35344127, 0. ]],\n [[ 0. , 0. ],\n [ 0. , 0. ],\n [ 0.43848675, 0. ],\n [ 0. , 1.21124518]],\n [[ 1.1026746 , 1.39578998],\n [ 0. , 0. ],\n [ 0.34652925, 0. ],\n [ 0. , 1.26868236]],\n [[ 0.91519427, 0.09030763],\n [ 0. , 0.59271163],\n [ 0. , 0.54207176],\n [ 0. , 0. ]]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n actual = self._evalConvLayerFProp(\n strides=[1, 1],\n dilation_rate=[2, 2],\n params_builder=layers.SeparableConv2DLayer.Params)\n print('testConvLayerWithDilationFProp actual = ', np.array_repr(actual))\n self.assertAllClose(expected_output1, actual)\n\n def testConv2DLayerConvFirstVsLastFProp(self):\n \"\"\"Compare results of conv first vs. last.\"\"\"\n # ... with batch_norm and activation disabled.\n self.assertAllClose(\n self._evalConvLayerFProp(\n batch_norm=False, activation='NONE', conv_last=False),\n self._evalConvLayerFProp(\n batch_norm=False, activation='NONE', conv_last=True))\n\n def testConv2DLayerFPropConvLast(self):\n # pyformat: disable\n # pylint: disable=bad-whitespace\n expected_output1 = [\n [[[ 0.22165056, 0.20731729],\n [ 0.09577402, -0.15359652]],\n [[ 0.07151584, 0.03027298],\n [ 0.05370769, 0.0143405 ]]],\n [[[-0.08854639, 0.06143938],\n [-0.37708873, 0.00889082]],\n [[-0.58154356, 0.30798748],\n [-0.37575331, 0.54729235]]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n actual = self._evalConvLayerFProp(conv_last=True)\n print(['ConvLast actual = ', np.array_repr(actual)])\n self.assertAllClose(expected_output1, actual)\n\n def testConv2DLayerConvWithBias(self):\n \"\"\"Compare results with bias vs. with neither batch_norm nor bias.\"\"\"\n # Results should match since bias is initialized to be 0.\n self.assertAllClose(\n self._evalConvLayerFProp(batch_norm=False, bias=False),\n self._evalConvLayerFProp(batch_norm=False, bias=True))\n\n def testConv2DLayerWeightNormFProp(self):\n # pyformat: disable\n # pylint: disable=bad-whitespace\n expected_output = [\n [[[ 0.37172362, 0.92405349],\n [ 0.07635488, 0.]],\n [[ 0.35431579, 0.],\n [ 1.94415355, 0.]]],\n [[[ 0.28692839, 0.],\n [ 0. , 0.]],\n [[ 0. , 0.87443149],\n [ 0. , 1.61808443]]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n actual = self._evalConvLayerFProp(weight_norm=True)\n print('actual1 = ', np.array_repr(actual))\n self.assertAllClose(expected_output, actual)\n\n def testDepthwiseConv2DLayerWeightNormFProp(self):\n # pyformat: disable\n # pylint: disable=bad-whitespace\n expected_output = [\n [[[ 0.97023201, 0.37429881, 0. , 0.53157473, 0. ,\n 1.60764372],\n [ 0. , 0. , 0.50401598, 0. , 1.07683432,\n 0.57673818]],\n [[ 0.644171 , 0.36347377, 0. , 0.20068097, 0.50016963,\n 0. ],\n [ 0.8416335 , 1.06069875, 0.92725372, 0. , 1.30220449,\n 0. ]]],\n [[[ 0. , 0. , 0.50146359, 0. , 0.78532791,\n 0. ],\n [ 0. , 0. , 1.53688192, 0. , 0. ,\n 0. ]],\n [[ 0.302506 , 0. , 0. , 1.18745029, 0. ,\n 0.83401161],\n [ 0.94737887, 1.46960247, 0. , 1.53112805, 0. ,\n 0.42655289]]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n actual = self._evalConvLayerFProp(\n weight_norm=True, params_builder=layers.DepthwiseConv2DLayer.Params)\n print('actual1 = ', np.array_repr(actual))\n self.assertAllClose(expected_output, actual)\n\n def testSeparableConv2DLayerWeightNormFProp(self):\n # pyformat: disable\n # pylint: disable=bad-whitespace\n expected_output = [\n [[[ 0.41837293, 0. ],\n [ 1.39592457, 0. ]],\n [[ 0. , 0. ],\n [ 0. , 0. ]]],\n [[[ 1.20513153, 0.11938372],\n [ 0.1284119 , 0.6927582 ]],\n [[ 0.0227453 , 2.05591369],\n [ 0. , 0.26530063]]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n actual = self._evalConvLayerFProp(\n weight_norm=True, params_builder=layers.SeparableConv2DLayer.Params)\n print('actual1 = ', np.array_repr(actual))\n self.assertAllClose(expected_output, actual)\n\n def testConv2DLayerFoldedBatchNormFProp(self):\n actual_unfolded = self._evalConvLayerFProp(\n batch_norm=True, bn_fold_weights=False)\n actual_folded = self._evalConvLayerFProp(\n batch_norm=True, bn_fold_weights=True)\n print('testConvLayerFoldedBatchNormFProp folded = ',\n np.array_repr(actual_folded))\n print('testConvLayerFoldedBatchNormFProp unfolded = ',\n np.array_repr(actual_unfolded))\n self.assertAllClose(actual_folded, actual_unfolded)\n\n def testDepthwiseConv2DLayerFoldedBatchNormFProp(self):\n actual_unfolded = self._evalConvLayerFProp(\n batch_norm=True,\n bn_fold_weights=False,\n params_builder=layers.DepthwiseConv2DLayer.Params)\n actual_folded = self._evalConvLayerFProp(\n batch_norm=True,\n bn_fold_weights=True,\n params_builder=layers.DepthwiseConv2DLayer.Params)\n print('testDepthwiseConvLayerFoldedBatchNormFProp folded = ',\n np.array_repr(actual_folded))\n print('testDepthwiseConvLayerFoldedBatchNormFProp unfolded = ',\n np.array_repr(actual_unfolded))\n self.assertAllClose(actual_folded, actual_unfolded)\n\n def testSeparableConv2DLayerFoldedBatchNormFProp(self):\n actual_unfolded = self._evalConvLayerFProp(\n batch_norm=True,\n bn_fold_weights=False,\n params_builder=layers.SeparableConv2DLayer.Params)\n actual_folded = self._evalConvLayerFProp(\n batch_norm=True,\n bn_fold_weights=True,\n params_builder=layers.SeparableConv2DLayer.Params)\n print('testSeparableConvLayerFoldedBatchNormFProp folded = ',\n np.array_repr(actual_folded))\n print('testSeparableConvLayerFoldedBatchNormFProp unfolded = ',\n np.array_repr(actual_unfolded))\n self.assertAllClose(actual_folded, actual_unfolded)\n\n def testConvLayerFoldedBatchNormFPropEval(self):\n actual_unfolded = self._evalConvLayerFProp(\n batch_norm=True, bn_fold_weights=False, is_eval=True)\n actual_folded = self._evalConvLayerFProp(\n batch_norm=True, bn_fold_weights=True, is_eval=True)\n print('testConvLayerFoldedBatchNormFPropEval folded = ',\n np.array_repr(actual_folded))\n print('testConvLayerFoldedBatchNormFPropEval unfolded = ',\n np.array_repr(actual_unfolded))\n self.assertAllClose(actual_folded, actual_unfolded)\n\n def testConv2DLayerNoPadding(self):\n g = tf.Graph()\n with g.as_default():\n tf.set_random_seed(24332)\n p = layers.Conv2DLayerNoPadding.Params().Set(\n name='test', filter_shape=(3, 3, 3, 5), filter_stride=(2, 2))\n l = p.Instantiate()\n x = tf.random_normal(shape=[17, 64, 64, 3])\n y = l.FPropDefaultTheta(x)\n\n with self.session(graph=g) as sess:\n sess.run(tf.global_variables_initializer())\n y_val = sess.run(y)\n\n self.assertEqual(y_val.shape, (17, 32, 32, 5))\n\n def testConvLayerFoldedBatchNormFPropQuantized(self):\n # pyformat: disable\n # pylint: disable=bad-whitespace\n expected_output = [\n [[[ 0.36997819, 0.91361964],\n [ 0.07550576, 0. ]],\n\n [[ 0.35487702, 0. ],\n [ 1.92539668, 0. ]]],\n [[[ 0.27937129, 0. ],\n [ 0. , 0. ]],\n\n [[ 0. , 0.86831617],\n [ 0. , 1.59317136]]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n\n actual_folded = self._evalConvLayerFProp(\n batch_norm=True, bn_fold_weights=True, quantized=True)\n print('testConvLayerFoldedBatchNormFPropQuantized folded = ',\n np.array_repr(actual_folded))\n self.assertAllClose(actual_folded, expected_output)\n\n def testCausalConvLayerFProp(self):\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.ConvLayer.Params()\n params.name = 'conv'\n params.filter_shape = [2, 1, 3, 2]\n params.filter_stride = [1, 1]\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n params.causal_convolution = True\n params.activation = 'NONE'\n params.batch_norm = False\n\n conv_layer = layers.ConvLayer(params)\n in_padding1 = tf.zeros([2, 4], dtype=tf.float32)\n inputs1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 4, 3, 3]), dtype=tf.float32)\n # Change the input for the last two steps.\n inputs2 = tf.concat([inputs1[:, :2, :, :], inputs1[:, 2:, :, :] + 0.5], 1)\n\n output1, _ = conv_layer.FPropDefaultTheta(inputs1, in_padding1)\n output2, _ = conv_layer.FPropDefaultTheta(inputs2, in_padding1)\n tf.global_variables_initializer().run()\n v1, v2 = sess.run([output1, output2])\n tf.logging.info('CausalConv output: %s', np.array_repr(v1))\n # pylint: disable=bad-whitespace,bad-continuation,line-too-long\n self.assertAllClose(v1, [\n [[[-0.01093466, 0.00369835],\n [ 0.03474921, 0.01418608],\n [ 0.01887876, -0.00763734]],\n [[-0.06922598, -0.04526342],\n [-0.02428233, 0.02042499],\n [-0.04504267, -0.01260209]],\n [[-0.14253227, -0.11353028],\n [-0.09067881, 0.03742362],\n [ 0.01281691, 0.00644186]],\n [[-0.06524619, -0.0555004 ],\n [-0.18850081, -0.05325979],\n [ 0.04960757, 0.05512709]]],\n [[[-0.01077277, 0.03013588],\n [ 0.00325067, -0.0223705 ],\n [-0.00895232, 0.03310337]],\n [[ 0.03113075, -0.02388876],\n [ 0.03238059, 0.00590346],\n [ 0.12839797, -0.02194144]],\n [[-0.09115655, -0.06798521],\n [-0.09801255, -0.01440183],\n [-0.04321899, 0.00340509]],\n [[-0.089603 , -0.07257183],\n [-0.04469771, -0.0389927 ],\n [-0.01747611, 0.00903451]]]\n ]) # pyformat: disable\n # pylint: enable=bad-whitespace,bad-continuation,line-too-long\n self.assertAllClose(v1[:, :2, :, :], v2[:, :2, :, :])\n with self.assertRaises(AssertionError):\n self.assertAllClose(v1[:, 2:, :, :], v2[:, 2:, :, :])\n\n def testCausalConv2DLayerFProp(self):\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.ConvLayer.Params()\n params.name = 'causal_conv'\n params.filter_shape = [2, 2, 3, 2]\n params.filter_stride = [1, 1]\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n params.causal_convolution = True\n params.activation = 'NONE'\n params.batch_norm = False\n\n conv_layer = layers.ConvLayer(params)\n in_padding1 = tf.zeros([2, 4], dtype=tf.float32)\n inputs1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 4, 3, 3]), dtype=tf.float32)\n\n output1, _ = conv_layer.FPropDefaultTheta(inputs1, in_padding1)\n tf.global_variables_initializer().run()\n v1 = sess.run(output1)\n tf.logging.info('CausalConv output: %s', np.array_repr(v1))\n # pylint: disable=bad-whitespace,bad-continuation,line-too-long\n self.assertAllClose(v1, [\n [[[-0.065196 , -0.0597635 ],\n [ 0.02871699, -0.02915794],\n [-0.00529849, -0.02677475]],\n [[-0.0227601 , 0.06118587],\n [ 0.25884673, -0.13917476],\n [ 0.03899311, -0.06894699]],\n [[-0.28780231, -0.12121122],\n [ 0.2447218 , 0.09553684],\n [-0.07054863, 0.12110104]],\n [[ 0.17036264, -0.00258163],\n [ 0.28644818, -0.02746056],\n [ 0.06173857, -0.11599959]]],\n [[[ 0.1468567 , 0.12725323],\n [-0.00131077, -0.03644447],\n [ 0.0266833 , 0.01140832]],\n [[-0.23816 , -0.07873908],\n [-0.07348203, 0.25653225],\n [-0.21931274, -0.0569509 ]],\n [[-0.06972647, -0.03123237],\n [ 0.07432974, -0.03340006],\n [ 0.10474236, 0.00807726]],\n [[ 0.07581483, 0.25381109],\n [ 0.07091375, -0.14229891],\n [ 0.05247882, -0.08783717]]]\n ]) # pyformat: disable\n # pylint: enable=bad-whitespace,bad-continuation,line-too-long\n\n def testCausalConv2DEqualsConv2DWithPadding(self):\n # Causal conv is equivalent to regular conv with zero pre-padding.\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.ConvLayer.Params()\n params.name = 'causal_conv'\n params.filter_shape = [2, 2, 3, 2]\n params.filter_stride = [1, 1]\n params.params_init = py_utils.WeightInit.Gaussian(0.1, seed=12345)\n params.is_eval = False\n params.causal_convolution = True\n params.activation = 'NONE'\n params.batch_norm = False\n causal_conv_layer = layers.ConvLayer(params)\n\n normal_conv_params = params.Copy()\n normal_conv_params.name = 'conv'\n normal_conv_params.causal_convolution = False\n normal_conv_layer = layers.ConvLayer(normal_conv_params)\n inputs1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 4, 3, 3]), dtype=tf.float32)\n # Causal conv with kernel height (time) = 2 requires prepadding size 1.\n inputs1_pad = tf.concat([tf.zeros([2, 1, 3, 3]), inputs1], axis=1)\n\n output_causal, _ = causal_conv_layer.FPropDefaultTheta(inputs1)\n output_normal, _ = normal_conv_layer.FPropDefaultTheta(inputs1_pad)\n tf.global_variables_initializer().run()\n v_causal, v_normal = sess.run([output_causal, output_normal])\n # Normal conv would produce an extra timestep due to SAME padding at the\n # end.\n self.assertAllClose(v_causal, v_normal[:, :-1])\n\n def testCausalConv2DEqualsConv2DWithKernelHeightOne(self):\n # When kernel height (time) = 1, causal convolution regresses to normal\n # convolution with SAME padding.\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.ConvLayer.Params()\n params.name = 'causal_conv'\n params.filter_shape = [1, 2, 3, 2]\n params.filter_stride = [1, 1]\n params.params_init = py_utils.WeightInit.Gaussian(0.1, seed=12345)\n params.is_eval = False\n params.causal_convolution = True\n params.activation = 'NONE'\n params.batch_norm = False\n causal_conv_layer = layers.ConvLayer(params)\n\n normal_conv_params = params.Copy()\n normal_conv_params.name = 'conv'\n normal_conv_params.causal_convolution = False\n normal_conv_layer = layers.ConvLayer(normal_conv_params)\n inputs1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 4, 3, 3]), dtype=tf.float32)\n\n output_causal, _ = causal_conv_layer.FPropDefaultTheta(inputs1)\n output_normal, _ = normal_conv_layer.FPropDefaultTheta(inputs1)\n tf.global_variables_initializer().run()\n v_causal, v_normal = sess.run([output_causal, output_normal])\n\n self.assertAllClose(v_causal, v_normal)\n\n def testConvLayerBackProp(self):\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.ConvLayer.Params()\n params.name = 'conv'\n params.filter_shape = [3, 3, 3, 2]\n params.filter_stride = [2, 2]\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n\n conv_layer = layers.ConvLayer(params)\n in_padding1 = tf.zeros([2, 4], dtype=tf.float32)\n inputs1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 4, 4, 3]), dtype=tf.float32)\n output1, _ = conv_layer.FPropDefaultTheta(inputs1, in_padding1)\n loss = tf.reduce_sum(output1)\n\n all_vars = tf.trainable_variables()\n self.assertEqual(3, len(all_vars))\n\n grads = tf.gradients(loss, all_vars)\n tf.global_variables_initializer().run()\n sym_grads = [sg.eval() for sg in grads]\n num_grads = [\n test_utils.ComputeNumericGradient(sess, loss, v) for v in all_vars\n ]\n\n for sg, ng in zip(sym_grads, num_grads):\n self.assertAllClose(sg, ng, rtol=1e-02, atol=1e-02)\n\n def testConvLayerFPropTanh(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.ConvLayer.Params()\n params.activation = 'TANH'\n params.name = 'conv'\n params.filter_shape = [3, 3, 3, 2]\n params.filter_stride = [2, 2]\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n\n conv_layer = layers.ConvLayer(params)\n in_padding1 = tf.zeros([2, 4], dtype=tf.float32)\n inputs1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 4, 4, 3]), dtype=tf.float32)\n\n output1, _ = conv_layer.FPropDefaultTheta(inputs1, in_padding1)\n tf.global_variables_initializer().run()\n\n # pyformat: disable\n # pylint: disable=bad-whitespace\n expected_output1 = [\n [[[ 0.35109526, 0.72346997],\n [ 0.0751792 , -0.84315312]],\n [[ 0.33594984, -0.18976833],\n [ 0.95773894, -0.28015777]]],\n [[[ 0.27572086, -0.26577294],\n [-0.38503852, -0.88501388]],\n [[-0.92332661, 0.69921255],\n [-0.75103623, 0.9219743 ]]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n actual = output1.eval()\n print(['actual = ', actual])\n self.assertAllClose(expected_output1, actual)\n\n def testConvSetLayerConstruction(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.ConvSetLayer.Params()\n params.name = 'conv_set'\n params.filter_shapes = [[3, 3, 3, 32], [8, 5, 3, 64]]\n params.cnn_tpl.filter_stride = [2, 2]\n params.cnn_tpl.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.cnn_tpl.is_eval = False\n layers.ConvSetLayer(params)\n\n def _evalConvSetLayerFProp(self,\n batch_norm=True,\n bn_fold_weights=False,\n weight_norm=False,\n bias=False,\n activation='RELU',\n conv_last=False,\n strides=(2, 2),\n dilation_rate=(1, 1),\n quantized=False,\n dump_graphdef=False):\n self._ClearCachedSession()\n ops.reset_default_graph()\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.ConvSetLayer.Params()\n params.name = 'conv_set'\n params.filter_shapes = [[2, 2, 6, 1], [3, 5, 6, 3]]\n params.cnn_tpl.filter_stride = strides\n params.cnn_tpl.dilation_rate = dilation_rate\n params.cnn_tpl.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.cnn_tpl.conv_last = conv_last\n params.cnn_tpl.batch_norm = batch_norm\n params.cnn_tpl.bn_fold_weights = bn_fold_weights\n params.cnn_tpl.weight_norm = weight_norm\n params.cnn_tpl.bias = bias\n params.cnn_tpl.activation = activation\n params.cnn_tpl.is_eval = False\n if quantized:\n params.qdomain.default = quant_utils.PassiveAsymQDomain.Params()\n\n conv_set_layer = layers.ConvSetLayer(params)\n in_padding1 = tf.zeros([2, 4], dtype=tf.float32)\n inputs1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 4, 4, 6]), dtype=tf.float32)\n\n output1, _ = conv_set_layer.FPropDefaultTheta(inputs1, in_padding1)\n tf.global_variables_initializer().run()\n\n if dump_graphdef:\n print('ConvSet GraphDef:', sess.graph.as_graph_def())\n assert False, 'Disable \"dump_graphdef\" before submit'\n\n return output1.eval()\n\n def testConvSetLayerFProp(self):\n # pyformat: disable\n # pylint: disable=bad-whitespace,bad-continuation\n expected_output1 = [\n [[[ 1.04307961, 0. , 1.27613628, 0. ],\n [ 0. , 0. , 0. , 1.21081829 ]],\n [[ 0. , 0.18475296, 0. , 0. ],\n [ 1.34087086 , 2.2726357 , 0. , 0. ]]],\n [[[ 0. , 0.25231963, 0. , 0. ],\n [ 1.13677704 , 0. , 0.996117 , 1.836285 ]],\n [[ 0. , 0. , 1.04101253, 0. ],\n [ 0.12628449 , 0.37599814, 0.3134549 , 0.51208746 ]]]\n ]\n # pyformat: enable\n # pylint: enable=bad-whitespace,bad-continuation\n actual = self._evalConvSetLayerFProp()\n print(['actual = ', np.array_repr(actual)])\n self.assertAllClose(expected_output1, actual)\n\n def testConvSetLayerFPropQuantized(self):\n # pyformat: disable\n # pylint: disable=bad-whitespace,bad-continuation\n expected_output1 = [\n [[[ 1.04016984, 0. , 1.28103447, 0. ],\n [ 0. , 0. , 0. , 1.20986581]],\n [[ 0. , 0.18681753, 0. , 0. ],\n [ 1.35328221, 2.26849842, 0. , 0. ]]],\n [[[ 0. , 0.24909003, 0. , 0. ],\n [ 1.14100266, 0. , 0.98746401, 1.83259094]],\n [[ 0. , 0. , 1.04084051, 0. ],\n [ 0.12736773, 0.38253111, 0.32025862, 0.5159722 ]]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace,bad-continuation\n actual = self._evalConvSetLayerFProp(bn_fold_weights=True, quantized=True)\n # Note that we don't have many ways to verify in a unit test that the\n # quant nodes were added properly; however, if their placement changes,\n # it will very likely perturb the golden values above. If digging deeper,\n # add 'dump_graphdef=True' to the above call and inspect the graphdef:\n # There should be one layer of fake_quant* nodes before the ConcatV2.\n print('actual = ', np.array_repr(actual))\n self.assertAllClose(expected_output1, actual)\n\n # TODO(yonghui): more test for convolution layer\n\n\nclass PoolingLayerTest(test_utils.TestCase):\n\n def testPoolLayerFProp(self):\n with self.session(use_gpu=True):\n params = layers.PoolingLayer.Params()\n params.name = 'pool'\n params.window_shape = [3, 3]\n params.window_stride = [1, 2]\n params.is_eval = False\n\n pool_layer = layers.PoolingLayer(params)\n in_padding1 = tf.zeros([2, 4], dtype=tf.float32)\n inputs1 = tf.constant(\n np.arange(96, dtype='float32').reshape([2, 4, 4, 3]),\n dtype=tf.float32)\n\n output1, _ = pool_layer.FPropDefaultTheta(inputs1, in_padding1)\n tf.global_variables_initializer().run()\n print([np.array_repr(output1.eval())])\n # pyformat: disable\n expected_output1 = [\n [[[18., 19., 20.],\n [21., 22., 23.]],\n [[30., 31., 32.],\n [33., 34., 35.]],\n [[42., 43., 44.],\n [45., 46., 47.]],\n [[42., 43., 44.],\n [45., 46., 47.]]],\n [[[66., 67., 68.],\n [69., 70., 71.]],\n [[78., 79., 80.],\n [81., 82., 83.]],\n [[90., 91., 92.],\n [93., 94., 95.]],\n [[90., 91., 92.],\n [93., 94., 95.]]]]\n # pyformat: enable\n self.assertAllClose(expected_output1, output1.eval())\n\n def testPoolLayerMoreShapes(self):\n with self.session(use_gpu=True):\n for window_shape, window_stride in [\n [[3, 3], [1, 2]],\n [[2, 2], [1, 2]],\n [[3, 4], [1, 3]],\n ]:\n params = layers.PoolingLayer.Params()\n params.name = 'pool'\n params.window_shape = window_shape\n params.window_stride = window_stride\n params.is_eval = False\n\n pool_layer = layers.PoolingLayer(params)\n in_padding1 = tf.zeros([2, 4], dtype=tf.float32)\n inputs1 = tf.constant(\n np.arange(96, dtype='float32').reshape([2, 4, 4, 3]),\n dtype=tf.float32)\n\n output1, _ = pool_layer.FPropDefaultTheta(inputs1, in_padding1)\n\n output2 = tf.nn.max_pool(inputs1, [1] + params.window_shape + [1],\n [1] + params.window_stride + [1], 'SAME')\n\n predicted_out_shape = pool_layer.OutShape(inputs1.shape.as_list())\n\n tf.global_variables_initializer().run()\n output1_v = output1.eval()\n self.assertAllClose(output2.eval(), output1_v)\n self.assertAllClose(predicted_out_shape, output1_v.shape)\n\n\nclass ProjectionLayerTest(test_utils.TestCase):\n\n def testProjectionLayerConstruction(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.ProjectionLayer.Params()\n params.name = 'proj'\n params.input_dim = 2\n params.output_dim = 3\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n layers.ProjectionLayer(params)\n proj_vars = tf.get_collection('ProjectionLayer_vars')\n proj_var_names = [x.name for x in proj_vars]\n self.assertEqual(['proj/w/var:0'], proj_var_names)\n bn_vars = tf.get_collection('BatchNormLayer_vars')\n bn_var_names = [x.name for x in bn_vars]\n expected_var_names = [\n 'proj/beta/var:0', 'proj/gamma/var:0', 'proj/moving_mean/var:0',\n 'proj/moving_variance/var:0'\n ]\n self.assertEqual(expected_var_names, bn_var_names)\n\n def _evalProjectionLayer(self,\n reshape_to_2d=False,\n batch_norm=True,\n weight_norm=False,\n activation='RELU',\n affine_last=False,\n input_dim=3,\n output_dim=2,\n quantized=False,\n has_bias=False,\n bn_fold_weights=None,\n expect_bn_fold_weights=None,\n is_eval=False,\n layer_callback=None):\n self._ClearCachedSession()\n tf.reset_default_graph()\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.ProjectionLayer.Params()\n params.name = 'proj'\n params.input_dim = input_dim\n params.output_dim = output_dim\n params.has_bias = has_bias\n if has_bias:\n params.bias_init = 5.0\n params.activation = activation\n params.batch_norm = batch_norm\n params.weight_norm = weight_norm\n params.affine_last = affine_last\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.bn_fold_weights = bn_fold_weights\n if quantized:\n cc_schedule = quant_utils.FakeQuantizationSchedule.Params().Set(\n clip_end_step=1, quant_start_step=1)\n qdomain_default = quant_utils.SymmetricScheduledClipQDomain.Params(\n ).Set(cc_schedule=cc_schedule.Copy())\n params.qdomain.default = qdomain_default.Copy()\n params.is_eval = is_eval\n\n in_padding = tf.zeros([2, 4, 1], dtype=tf.float32)\n inputs = tf.constant(\n np.random.normal(0.1, 0.5, [2, 4, 3]), dtype=tf.float32)\n if reshape_to_2d:\n in_padding = tf.reshape(in_padding, [-1, 1])\n inputs = tf.reshape(inputs, [-1, 3])\n\n proj_layer = layers.ProjectionLayer(params)\n if layer_callback:\n layer_callback(proj_layer)\n if expect_bn_fold_weights is not None:\n self.assertEqual(expect_bn_fold_weights, proj_layer._is_bn_folded)\n\n output = proj_layer.FPropDefaultTheta(inputs, in_padding)\n tf.global_variables_initializer().run()\n if quantized:\n # Put it in the fully quantized range.\n sess.run(tf.assign(py_utils.GetOrCreateGlobalStepVar(), 5))\n return output.eval()\n\n def testProjectionLayerFProp(self):\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_output = [\n [[ 0. , 0.33779466],\n [ 0.4527415 , 0.99911398],\n [ 0.44320837, 0. ],\n [ 0. , 0.04557215]],\n [[ 0.69273949, 0. ],\n [ 0.30908319, 0. ],\n [ 0. , 0. ],\n [ 0. , 1.54578114]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n for reshape_to_2d in (False, True):\n actual = self._evalProjectionLayer(\n reshape_to_2d=reshape_to_2d, expect_bn_fold_weights=False)\n if reshape_to_2d:\n expected_output = np.reshape(np.array(expected_output), (-1, 2))\n tf.logging.info('expected = %s', expected_output)\n tf.logging.info('actual = %s', np.array_repr(actual))\n self.assertAllClose(expected_output, actual)\n\n def testProjectionLayerFPropWithBias(self):\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_output = [\n [[ 4.98987579, 5.03493643],\n [ 5.01192808, 5.0917592 ],\n [ 5.01156807, 4.99741936],\n [ 4.96849394, 5.00982761]],\n [[ 5.02098131, 4.98014927],\n [ 5.00650883, 4.87676954],\n [ 4.98995209, 4.91770315],\n [ 4.95948696, 5.138731 ]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n # Tested without batch_norm because batch_norm will mostly cancel out the\n # affect of bias.\n actual = self._evalProjectionLayer(\n has_bias=True,\n batch_norm=False,\n expect_bn_fold_weights=False,\n activation='RELU6')\n tf.logging.info('expected = %s', expected_output)\n tf.logging.info('actual = %s', np.array_repr(actual))\n self.assertAllClose(expected_output, actual)\n\n def testProjectionLayerExplicitFolding(self):\n unfolded = self._evalProjectionLayer(\n bn_fold_weights=False, expect_bn_fold_weights=False)\n folded = self._evalProjectionLayer(\n bn_fold_weights=True, expect_bn_fold_weights=True)\n tf.logging.info('unfolded = %s', np.array_repr(unfolded))\n tf.logging.info('folded = %s', np.array_repr(folded))\n self.assertAllClose(folded, unfolded)\n\n def testProjectionLayerExplicitFoldingEval(self):\n unfolded = self._evalProjectionLayer(\n bn_fold_weights=False, expect_bn_fold_weights=False, is_eval=True)\n folded = self._evalProjectionLayer(\n bn_fold_weights=True, expect_bn_fold_weights=True, is_eval=True)\n tf.logging.info('unfolded = %s', np.array_repr(unfolded))\n tf.logging.info('folded = %s', np.array_repr(folded))\n self.assertAllClose(folded, unfolded)\n\n def testProjectionLayerExplicitFoldingNoBatchNorm(self):\n unfolded = self._evalProjectionLayer(\n batch_norm=False, bn_fold_weights=False, expect_bn_fold_weights=False)\n # Note that weight folding will report as disabled because batch norm is\n # disabled.\n folded = self._evalProjectionLayer(\n batch_norm=False, bn_fold_weights=True, expect_bn_fold_weights=False)\n tf.logging.info('unfolded = %s', np.array_repr(unfolded))\n tf.logging.info('folded = %s', np.array_repr(folded))\n self.assertAllClose(folded, unfolded)\n\n def testProjectionLayerExplicitFoldingWithWeightNorm(self):\n unfolded = self._evalProjectionLayer(\n weight_norm=True, bn_fold_weights=False, expect_bn_fold_weights=False)\n folded = self._evalProjectionLayer(\n weight_norm=True, bn_fold_weights=True, expect_bn_fold_weights=True)\n tf.logging.info('unfolded = %s', np.array_repr(unfolded))\n tf.logging.info('folded = %s', np.array_repr(folded))\n self.assertAllClose(folded, unfolded)\n\n def testProjectionLayerWeightNorm(self):\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_output = [\n [[ 0. , 0.36285588],\n [ 0.82909501, 1.07323885],\n [ 0.81163716, 0. ],\n [ 0. , 0.04895319]],\n [[ 1.26859784, 0. ],\n [ 0.56601691, 0. ],\n [ 0. , 0. ],\n [ 0. , 1.66046333]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n for reshape_to_2d in (False, True):\n actual = self._evalProjectionLayer(\n reshape_to_2d=reshape_to_2d, weight_norm=True)\n if reshape_to_2d:\n expected_output = np.reshape(np.array(expected_output), (-1, 2))\n tf.logging.info('expected = %s', expected_output)\n tf.logging.info('actual = %s', np.array_repr(actual))\n self.assertAllClose(expected_output, actual)\n\n def testProjectionLayerAffineFirstVsLastFProp(self):\n \"\"\"Compare results of affine first vs. last.\"\"\"\n # ... with batch_norm and activation disabled.\n self.assertAllClose(\n self._evalProjectionLayer(\n batch_norm=False, activation='NONE', affine_last=False),\n self._evalProjectionLayer(\n batch_norm=False, activation='NONE', affine_last=True))\n\n def testProjectionLayerAffineLastFProp(self):\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_output1 = [\n [[ 0. , 0. ],\n [ 0.03410175, 0.04741348],\n [ 0.02665393, -0.02072855],\n [-0.01116518, -0.06280501]],\n [[ 0.04615254, -0.03589247],\n [-0.00376316, -0.0464084 ],\n [-0.01111402, -0.13706152],\n [-0.02596203, 0.16340451]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n actual = self._evalProjectionLayer(affine_last=True)\n print(['actual = ', np.array_repr(actual)])\n self.assertAllClose(expected_output1, actual)\n\n def testProjectionLayerBackProp(self):\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.ProjectionLayer.Params()\n params.name = 'proj'\n params.dtype = tf.float64\n params.input_dim = 3\n params.output_dim = 2\n params.params_init = py_utils.WeightInit.Gaussian(0.01)\n params.is_eval = False\n\n proj_layer = layers.ProjectionLayer(params)\n in_padding1 = tf.zeros([2, 4, 1], dtype=tf.float64)\n inputs1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 4, 3]), dtype=tf.float64)\n output1 = proj_layer.FPropDefaultTheta(inputs1, in_padding1)\n loss = tf.reduce_sum(output1)\n\n all_vars = tf.trainable_variables()\n self.assertEqual(3, len(all_vars))\n\n grads = tf.gradients(loss, all_vars)\n tf.global_variables_initializer().run()\n sym_grads = [sg.eval() for sg in grads]\n num_grads = [\n test_utils.ComputeNumericGradient(sess, loss, v, 1e-6)\n for v in all_vars\n ]\n\n for sg, ng in zip(sym_grads, num_grads):\n self.assertAllClose(sg, ng, rtol=1e-06, atol=1e-06)\n\n def testProjectionLayerFPropQuantizedWithUnfusedActivation(self):\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_output = [\n [[-0.1328125, 0.3125 ],\n [ 0.421875 , 0.734375 ],\n [ 0.421875 , -0.109375 ],\n [-0.6015625, 0.0078125]],\n [[ 0.6015625, -0.3046875],\n [ 0.3046875, -0.7578125],\n [-0.125 , -0.7578125],\n [-0.734375 , 0.7578125]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n def CheckLayer(proj_layer):\n # Should not error because this qtensor is defined.\n proj_layer.QTensor('activation', tf.convert_to_tensor(0.))\n # The intermediate tensor should be defined.\n proj_layer.QTensor('affine_matmul', tf.convert_to_tensor(0.))\n\n # When quantization enabled, batchnorm folding should auto enable.\n # TANH is unfused.\n actual = self._evalProjectionLayer(\n activation='TANH',\n quantized=True,\n expect_bn_fold_weights=True,\n layer_callback=CheckLayer)\n tf.logging.info('expected = %s', expected_output)\n tf.logging.info('actual = %s', np.array_repr(actual))\n self.assertAllClose(expected_output, actual)\n\n def testProjectionLayerFPropQuantizedWithFusedActivation(self):\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_output = [\n [[ 0. , 0.3203125],\n [ 0.453125 , 0.9375 ],\n [ 0.4453125, 0. ],\n [ 0. , 0.0078125]],\n [[ 0.6953125, 0. ],\n [ 0.3125 , 0. ],\n [ 0. , 0. ],\n [ 0. , 0.9921875]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n def CheckLayer(proj_layer):\n # Should not error because this qtensor is defined.\n proj_layer.QTensor('activation', tf.convert_to_tensor(0.))\n with self.assertRaises(AssertionError):\n # The intermediate tensor should *not* be quantized.\n proj_layer.QTensor('affine_matmul', tf.convert_to_tensor(0.))\n\n # When quantization enabled, batchnorm folding should auto enable.\n # RELU6 is fused.\n actual = self._evalProjectionLayer(\n activation='RELU6',\n quantized=True,\n expect_bn_fold_weights=True,\n layer_callback=CheckLayer)\n tf.logging.info('expected = %s', expected_output)\n tf.logging.info('actual = %s', np.array_repr(actual))\n self.assertAllClose(expected_output, actual)\n\n def testProjectionLayerFPropQuantizedOnlyMatmul(self):\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_output = [\n [[-0.0078125, 0.0390625],\n [ 0.0078125, 0.09375 ],\n [ 0.0078125, 0. ],\n [-0.03125 , 0.015625 ]],\n [[ 0.015625 , -0.015625 ],\n [ 0.0078125, -0.125 ],\n [-0.0078125, -0.078125 ],\n [-0.0390625, 0.1484375]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n def CheckLayer(proj_layer):\n # Should not error because this qtensor is defined.\n proj_layer.QTensor('affine_matmul', tf.convert_to_tensor(0.))\n\n actual = self._evalProjectionLayer(\n activation='NONE',\n quantized=True,\n batch_norm=False,\n expect_bn_fold_weights=False,\n layer_callback=CheckLayer)\n tf.logging.info('expected = %s', expected_output)\n tf.logging.info('actual = %s', np.array_repr(actual))\n self.assertAllClose(expected_output, actual)\n\n def testProjectionLayerFPropQuantizedOnlyMatmulBias(self):\n # pylint: disable=bad-whitespace\n # pyformat: disable\n # Saturated because of the out of range bias.\n expected_output = [[[0.9921875, 0.9921875], [0.9921875, 0.9921875],\n [0.9921875, 0.9921875], [0.9921875, 0.9921875]],\n [[0.9921875, 0.9921875], [0.9921875, 0.9921875],\n [0.9921875, 0.9921875], [0.9921875, 0.9921875]]]\n\n # pyformat: enable\n # pylint: enable=bad-whitespace\n def CheckLayer(proj_layer):\n # Should not error because this qtensor is defined.\n proj_layer.QTensor('affine_matmul', tf.convert_to_tensor(0.))\n\n actual = self._evalProjectionLayer(\n activation='NONE',\n quantized=True,\n has_bias=True,\n batch_norm=False,\n expect_bn_fold_weights=False,\n layer_callback=CheckLayer)\n tf.logging.info('expected = %s', expected_output)\n tf.logging.info('actual = %s', np.array_repr(actual))\n self.assertAllClose(expected_output, actual)\n\n def testFCLayerConstruction(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.FCLayer.Params()\n params.name = 'fc'\n params.input_dim = 2\n params.output_dim = 3\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n layers.FCLayer(params)\n proj_vars = tf.get_collection('FCLayer_vars')\n proj_var_names = [x.name for x in proj_vars]\n expected_var_names = ['fc/w/var:0', 'fc/b/var:0']\n self.assertEqual(expected_var_names, proj_var_names)\n\n def testFCLayerFProp(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.FCLayer.Params()\n params.name = 'fc'\n params.input_dim = 3\n params.output_dim = 2\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n\n proj_layer = layers.FCLayer(params)\n inputs = tf.constant(\n np.random.normal(0.1, 0.5, [2, 4, 3]), dtype=tf.float32)\n\n output = proj_layer.FPropDefaultTheta(inputs)\n tf.global_variables_initializer().run()\n\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_output = [\n [[ 0. , 0.04883499],\n [ 0.17094055, 0. ],\n [ 0.09287541, 0. ],\n [ 0. , 0.19471419]],\n [[ 0.15290432, 0. ],\n [ 0. , 0. ],\n [ 0. , 0.10548697],\n [ 0. , 0.22610095]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n actual = output.eval()\n print(['actual = ', np.array_repr(actual)])\n self.assertAllClose(expected_output, actual)\n\n def testFCLayerBackProp(self):\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.FCLayer.Params()\n params.name = 'fc'\n params.dtype = tf.float64\n params.input_dim = 3\n params.output_dim = 2\n params.params_init = py_utils.WeightInit.Gaussian(0.01)\n\n proj_layer = layers.FCLayer(params)\n inputs = tf.constant(\n np.random.normal(0.1, 0.5, [2, 4, 3]), dtype=tf.float64)\n output = proj_layer.FPropDefaultTheta(inputs)\n loss = tf.reduce_sum(output)\n\n all_vars = tf.trainable_variables()\n self.assertEqual(2, len(all_vars))\n\n grads = tf.gradients(loss, all_vars)\n tf.global_variables_initializer().run()\n sym_grads = [sg.eval() for sg in grads]\n num_grads = [\n test_utils.ComputeNumericGradient(sess, loss, v, 1e-6)\n for v in all_vars\n ]\n\n for sg, ng in zip(sym_grads, num_grads):\n self.assertAllClose(sg, ng, rtol=1e-06, atol=1e-06)\n\n def testStackingOverTimeFProp(self):\n with self.session(use_gpu=True):\n params = layers.StackingOverTime.Params()\n params.name = 'stackingOverTime'\n params.left_context = 2\n params.right_context = 0\n params.stride = 2\n\n stacker = layers.StackingOverTime(params)\n self.assertEqual(stacker.window_size, 3)\n\n inputs = tf.constant(\n [\n [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6]], # batch 0\n [[7, 7], [8, 8], [0, 0], [0, 0], [0, 0], [0, 0]]\n ], # batch 1\n dtype=tf.float32)\n paddings = tf.constant(\n [\n [[0], [0], [0], [0], [0], [0]], # batch 0\n [[0], [0], [1], [1], [1], [1]]\n ], # batch 1\n dtype=tf.float32)\n\n outputs, output_paddings = stacker.FProp(inputs, paddings)\n tf.global_variables_initializer().run()\n print([np.array_repr(outputs.eval())])\n\n expected_outputs = [\n [[0, 0, 0, 0, 1, 1], [1, 1, 2, 2, 3, 3], [3, 3, 4, 4, 5,\n 5]], # batch 0\n [[0, 0, 0, 0, 7, 7], [7, 7, 8, 8, 0, 0], [0, 0, 0, 0, 0,\n 0]] # batch 1\n ]\n self.assertAllClose(expected_outputs, outputs.eval())\n\n expected_output_paddings = [\n [[0], [0], [0]], # batch 0\n [[0], [0], [1]] # batch 1\n ]\n self.assertAllClose(expected_output_paddings, output_paddings.eval())\n\n def testStackingOverTimeFProp2(self):\n with self.session(use_gpu=True) as sess:\n params = layers.StackingOverTime.Params()\n params.name = 'stackingOverTime'\n params.left_context = 0\n params.right_context = 1\n params.stride = 2\n\n stacker = layers.StackingOverTime(params)\n self.assertEqual(stacker.window_size, 2)\n\n inputs = tf.random_normal([2, 21, 16], seed=78123)\n paddings = 1.0 - tf.sequence_mask([9, 14], 21, tf.float32)\n paddings = tf.expand_dims(paddings, -1)\n\n outputs, output_paddings = stacker.FProp(inputs, paddings)\n tf.global_variables_initializer().run()\n\n inputs_v, outputs_v, paddings_v = sess.run(\n [inputs, outputs, output_paddings])\n\n # length\n self.assertAllEqual([5, 7], np.sum(1.0 - paddings_v, (1, 2)))\n # input and output sums are equal\n self.assertAllClose(np.sum(inputs_v, (1, 2)), np.sum(outputs_v, (1, 2)))\n\n def testStackingOverTimeIdentityFProp(self):\n with self.session(use_gpu=True):\n params = layers.StackingOverTime.Params()\n params.name = 'stackingOverTime'\n params.left_context = 0\n params.right_context = 0\n params.stride = 1\n\n stacker = layers.StackingOverTime(params)\n self.assertEqual(stacker.window_size, 1)\n inputs = tf.constant([[[1], [2], [3], [4], [5]]], dtype=tf.float32)\n paddings = tf.zeros([1, 5, 1], dtype=tf.float32)\n\n outputs, output_paddings = stacker.FProp(inputs, paddings)\n tf.global_variables_initializer().run()\n print([np.array_repr(outputs.eval())])\n expected_outputs = [[[1], [2], [3], [4], [5]]]\n self.assertAllClose(expected_outputs, outputs.eval())\n expected_output_paddings = [[[0], [0], [0], [0], [0]]]\n self.assertAllClose(expected_output_paddings, output_paddings.eval())\n\n def _testUnstack(self, params, inputs):\n with self.session(use_gpu=True) as sess:\n stacker = params.Instantiate()\n stacked, _ = stacker.FProp(inputs)\n unstacked = stacker.Unstack(stacked)\n inputs, stacked, unstacked = sess.run([inputs, stacked, unstacked])\n expected_length = (\n inputs.shape[1] - (inputs.shape[1] - 1) % stacker.params.stride)\n self.assertAllClose(inputs[:, :expected_length, :], unstacked)\n\n def testStackingOverTimeUnstack(self):\n params = layers.StackingOverTime.Params()\n params.name = 'stackingOverTime'\n\n batch_size = 2\n length = 7\n depth = 3\n inputs = tf.reshape(\n tf.range(batch_size * length * depth), [batch_size, length, depth])\n self._testUnstack(params.Set(left_context=2, stride=1), inputs)\n self._testUnstack(params.Set(stride=2), inputs)\n self._testUnstack(params.Set(stride=2, right_context=3), inputs)\n self._testUnstack(params.Set(stride=3), inputs)\n self._testUnstack(params.Set(stride=4, right_context=3), inputs)\n\n\nclass EmbeddingLayerTest(test_utils.TestCase):\n\n def testEmbeddingLayer(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n params = layers.EmbeddingLayer.Params()\n params.name = 'emb'\n params.dtype = tf.float32\n params.vocab_size = 80000\n params.embedding_dim = 128\n params.max_num_shards = 4\n params.params_init = py_utils.WeightInit.Gaussian(0.01)\n params.vn.global_vn = False\n params.vn.per_step_vn = False\n emb_layer = layers.EmbeddingLayer(params)\n ids = tf.constant([[89], [100]])\n embs = emb_layer.EmbLookupDefaultTheta(ids)\n embs_sum = tf.reduce_sum(embs)\n tf.global_variables_initializer().run()\n test_utils.CompareToGoldenSingleFloat(self, 0.234941, embs_sum.eval())\n\n def testCheckedIds(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n params = layers.EmbeddingLayer.Params()\n params.name = 'emb'\n params.dtype = tf.float32\n params.vocab_size = 16\n params.embedding_dim = 128\n params.max_num_shards = 4\n params.params_init = py_utils.WeightInit.Gaussian(0.01)\n params.vn.global_vn = False\n params.vn.per_step_vn = False\n emb_layer = layers.EmbeddingLayer(params)\n\n neg_ids = tf.constant([[-1]])\n neg_embs = emb_layer.EmbLookupDefaultTheta(neg_ids)\n oov_ids = tf.constant([[params.vocab_size]])\n oov_embs = emb_layer.EmbLookupDefaultTheta(oov_ids)\n tf.global_variables_initializer().run()\n\n with self.assertRaises(tf.errors.InvalidArgumentError):\n neg_embs.eval()\n with self.assertRaises(tf.errors.InvalidArgumentError):\n oov_embs.eval()\n\n def testEmbeddingLayerScaling(self):\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(398847392)\n params = layers.EmbeddingLayer.Params()\n params.name = 'emb'\n params.dtype = tf.float32\n params.vocab_size = 80000\n params.embedding_dim = 128\n params.max_num_shards = 4\n params.params_init = py_utils.WeightInit.Gaussian(0.01)\n params.vn.global_vn = False\n params.vn.per_step_vn = False\n params.scale_sqrt_depth = True\n emb_layer = layers.EmbeddingLayer(params)\n ids = tf.constant([[89], [100]])\n embs = emb_layer.EmbLookupDefaultTheta(ids)\n embs_sum = tf.reduce_sum(embs)\n tf.global_variables_initializer().run()\n self.assertAllClose(0.23494134843349457 * params.embedding_dim**0.5,\n sess.run(embs_sum))\n\n def testEmbeddingLayerWithVN(self):\n with self.session(use_gpu=True):\n tf.set_random_seed(398847392)\n params = layers.EmbeddingLayer.Params()\n params.name = 'emb'\n params.dtype = tf.float32\n params.vocab_size = 80000\n params.embedding_dim = 128\n params.max_num_shards = 4\n params.params_init = py_utils.WeightInit.Gaussian(0.01, seed=398847392)\n params.vn.global_vn = True\n params.vn.per_step_vn = False\n params.vn.scale = 0.5\n params.vn.seed = 398847392\n emb_layer = layers.EmbeddingLayer(params)\n self.assertEqual(len(emb_layer.vars.Flatten()), 4)\n ids = tf.constant([[89], [100]])\n embs = emb_layer.EmbLookupDefaultTheta(ids)\n embs_sum = tf.reduce_sum(embs)\n tf.global_variables_initializer().run()\n test_utils.CompareToGoldenSingleFloat(self, -6.807296, embs_sum.eval())\n\n def _testSimpleEmbeddingLayer(self, use_matmul, use_3d_weight_tensor,\n fprop_mode):\n g = tf.Graph()\n with g.as_default():\n tf.set_random_seed(398847392)\n params = layers.SimpleEmbeddingLayer.Params()\n params.name = 'emb'\n params.dtype = tf.float32\n params.vocab_size = 8000\n params.embedding_dim = 128\n params.use_matmul = use_matmul\n params.fprop_mode = fprop_mode\n params.use_3d_weight_tensor = use_3d_weight_tensor\n params.params_init = py_utils.WeightInit.Gaussian(0.01)\n params.vn.global_vn = False\n params.vn.per_step_vn = False\n\n emb_layer = layers.SimpleEmbeddingLayer(params)\n expected_fprop_mode = fprop_mode\n if expected_fprop_mode is None:\n expected_fprop_mode = 'matmul' if use_matmul else 'gather'\n self.assertEqual(emb_layer._fprop_mode, expected_fprop_mode)\n\n emb_matrix = emb_layer.vars.wm\n ids = tf.constant([[89], [100]])\n outputs = emb_layer.EmbLookupDefaultTheta(ids)\n fast_outputs = emb_layer.EmbLookupDefaultThetaOnCpu(ids)\n\n with self.session(use_gpu=True, graph=g) as sess:\n tf.global_variables_initializer().run()\n emb_matrix_val, ids_val, outputs_val, fast_outputs_val = sess.run(\n [emb_matrix, ids, outputs, fast_outputs])\n self.assertEqual(emb_matrix_val.shape, (8000, 128))\n self.assertEqual(ids_val.shape, (2, 1))\n self.assertEqual(outputs_val.shape, (2, 1, 128))\n self.assertAllClose(emb_matrix_val[89, :], outputs_val[0, 0, :])\n self.assertAllClose(emb_matrix_val[100, :], outputs_val[1, 0, :])\n\n self.assertEqual(fast_outputs_val.shape, (2, 1, 128))\n self.assertAllClose(emb_matrix_val[89, :], fast_outputs_val[0, 0, :])\n self.assertAllClose(emb_matrix_val[100, :], fast_outputs_val[1, 0, :])\n\n def testSimpleEmbeddingLayerForLoop(self):\n self._testSimpleEmbeddingLayer(False, True, None)\n\n def testSimpleEmbeddingLayerForLoop2D(self):\n self._testSimpleEmbeddingLayer(False, False, None)\n\n def testSimpleEmbeddingLayerMatmul(self):\n self._testSimpleEmbeddingLayer(True, False, None)\n\n def testSimpleEmbeddingLayerGather(self):\n self._testSimpleEmbeddingLayer(False, False, 'gather')\n\n def testSimpleEmbeddingLayerMasked(self):\n g = tf.Graph()\n with g.as_default():\n tf.set_random_seed(398847392)\n params = layers.SimpleEmbeddingLayer.Params()\n params.name = 'emd'\n params.dtype = tf.float32\n params.vocab_size = 10\n params.embedding_dim = 5\n params.fprop_mode = 'gather'\n params.use_3d_weight_tensor = False\n params.params_init = py_utils.WeightInit.Gaussian(0.01)\n params.vn.global_vn = False\n params.vn.per_step_vn = False\n params.apply_pruning = True\n\n emb_layer = layers.SimpleEmbeddingLayer(params)\n emb_matrix = emb_layer.vars.wm\n ids = tf.constant([[1], [2]])\n outputs = emb_layer.EmbLookupDefaultTheta(ids)\n\n self.assertTrue('wm' in emb_layer.vars.wm.name)\n self.assertTrue('mask' in emb_layer.vars.mask.name)\n self.assertTrue('threshold' in emb_layer.vars.threshold.name)\n\n self.assertEqual(emb_layer.theta.wm.get_shape(), tf.TensorShape([10, 5]))\n self.assertEqual(emb_layer.theta.mask.get_shape(), tf.TensorShape([10,\n 5]))\n self.assertEqual(emb_layer.theta.threshold.get_shape(),\n tf.TensorShape([]))\n\n embedding_var_count = 1\n wts = tf.get_collection('SimpleEmbeddingLayer_vars')\n self.assertEqual(embedding_var_count, len(wts))\n\n embedding_mask_count = 1\n masks = tf.get_collection('masks')\n self.assertEqual(embedding_mask_count, len(masks))\n\n emebdding_threshold_count = 1\n threshold = tf.get_collection('thresholds')\n self.assertEqual(emebdding_threshold_count, len(threshold))\n\n with self.session(use_gpu=False, graph=g) as sess:\n tf.global_variables_initializer().run()\n emb_matrix_val, _, outputs_val = sess.run([emb_matrix, ids, outputs])\n\n self.assertAllClose(emb_matrix_val[1:3], outputs_val[:, 0, :])\n\n def _testSimpleEmbeddingLayerGrad(self, use_matmul, use_3d_weight_tensor):\n g = tf.Graph()\n with g.as_default():\n tf.set_random_seed(398847392)\n params = layers.SimpleEmbeddingLayer.Params()\n params.name = 'emb'\n params.dtype = tf.float32\n params.vocab_size = 8000\n params.embedding_dim = 128\n params.use_matmul = use_matmul\n params.use_3d_weight_tensor = use_3d_weight_tensor\n params.params_init = py_utils.WeightInit.Gaussian(0.01)\n params.vn.global_vn = False\n params.vn.per_step_vn = False\n emb_layer = layers.SimpleEmbeddingLayer(params)\n ids = tf.constant([89, 100, 89, 89])\n embs = emb_layer.EmbLookupDefaultTheta(ids) * tf.constant([[0.1], [0.2],\n [0.3], [0.4]])\n embs_sum = tf.reduce_sum(embs)\n emb_weight = emb_layer.vars.wm\n emb_grad, = tf.gradients(ys=[embs_sum], xs=[emb_weight])\n with self.session(use_gpu=True, graph=g) as sess:\n tf.global_variables_initializer().run()\n emb_grad_val = sess.run(emb_grad)\n\n if not use_matmul:\n # tf.embedding_lookup's gradient is a sparse representation.\n # For testing, we convert it to a dense representation.\n o_grad_matrix = np.zeros((8000, 128))\n for i in range(emb_grad_val.indices.shape[0]):\n o_grad_matrix[emb_grad_val.indices[i], :] += emb_grad_val.values[i, :]\n emb_grad_val = o_grad_matrix\n\n expected_emb_grad = np.zeros(shape=(8000, 128))\n expected_emb_grad[89, :] = 0.8\n expected_emb_grad[100, :] = 0.2\n self.assertAllClose(expected_emb_grad, emb_grad_val)\n\n def testSimpleEmbeddingLayerGradForLoop(self):\n self._testSimpleEmbeddingLayerGrad(False, True)\n\n def testSimpleEmbeddingLayerGradForLoop2D(self):\n self._testSimpleEmbeddingLayerGrad(False, False)\n\n def testSimpleEmbeddingLayerGradMatmul(self):\n self._testSimpleEmbeddingLayerGrad(True, False)\n\n def testCompareEmbeddingLayers(self):\n classes = 8000\n dims = 128\n g = tf.Graph()\n with g.as_default():\n ids = tf.placeholder(tf.int32)\n\n def CreateSimple():\n tf.set_random_seed(398847392)\n p = layers.SimpleEmbeddingLayer.Params()\n p.name = 'emb'\n p.dtype = tf.float32\n p.vocab_size = classes\n p.embedding_dim = dims\n p.params_init = py_utils.WeightInit.Gaussian(0.01)\n p.vn.global_vn = False\n p.vn.per_step_vn = False\n return layers.SimpleEmbeddingLayer(p)\n\n simple = CreateSimple()\n simple_outs = simple.EmbLookupDefaultTheta(ids)\n simple_grad = tf.gradients(simple_outs, simple.vars.wm)[0]\n\n def CreateOriginal():\n tf.set_random_seed(398847392)\n p = layers.EmbeddingLayer.Params()\n p.name = 'emb'\n p.dtype = tf.float32\n p.vocab_size = classes\n p.embedding_dim = dims\n p.max_num_shards = 1\n p.params_init = py_utils.WeightInit.Gaussian(0.01)\n p.vn.global_vn = False\n p.vn.per_step_vn = False\n return layers.EmbeddingLayer(p)\n\n original = CreateOriginal()\n weight = tf.identity(simple.vars.wm)\n theta = py_utils.NestedMap()\n theta.wm = [weight]\n original_outs = original.EmbLookup(theta, ids)\n original_grad = tf.gradients(original_outs, weight)[0]\n\n ids_val = np.random.randint(0, high=classes, size=(4000,))\n with self.session(graph=g) as sess:\n sess.run(tf.global_variables_initializer())\n s_outs, s_grad, o_outs, o_grad = sess.run(\n [simple_outs, simple_grad, original_outs, original_grad],\n feed_dict={ids: ids_val})\n self.assertAllClose(s_outs, o_outs)\n self.assertAllClose(s_grad, o_grad)\n\n def testPositionalEmbeddingLayer(self):\n with self.session(use_gpu=False) as sess:\n p = layers.PositionalEmbeddingLayer.Params()\n p.name = 'position_emb'\n p.min_timescale = 1\n p.max_timescale = 7\n p.embedding_dim = 4\n seq_length = 11\n\n pos_emb_layer = layers.PositionalEmbeddingLayer(p)\n position_embs = pos_emb_layer.FPropDefaultTheta(seq_length)\n actual_position_embs, = sess.run([position_embs])\n\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_output = [\n [ 0. , 0. , 1. , 1. ],\n [ 0.84147096, 0.14237173, 0.54030228, 0.98981327],\n [ 0.90929741, 0.28184283, -0.41614676, 0.95946062],\n [ 0.14112 , 0.4155719 , -0.9899925 , 0.90956032],\n [-0.7568025 , 0.54083425, -0.65364361, 0.84112918],\n [-0.95892417, 0.65507787, 0.28366217, 0.75556135],\n [-0.27941549, 0.75597537, 0.96017027, 0.65460002],\n [ 0.65698659, 0.84147096, 0.7539022 , 0.54030228],\n [ 0.98935831, 0.90982294, -0.14550003, 0.41499668],\n [ 0.41211855, 0.9596386 , -0.91113025, 0.28123617],\n [-0.54402113, 0.98990309, -0.83907151, 0.14174587]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n print('expected_position_embs:', expected_output)\n print('actual_position_embs:', actual_position_embs)\n self.assertAllClose(actual_position_embs, expected_output)\n\n def testPositionalEmbeddingLayerWithPosition(self):\n with self.session(use_gpu=False) as sess:\n p = layers.PositionalEmbeddingLayer.Params()\n p.name = 'position_emb'\n p.min_timescale = 1\n p.max_timescale = 7\n p.embedding_dim = 4\n pos_tensor = tf.constant(\n np.asarray([[0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3],\n [0, 1, 2, 0, 1, 2, 3, 4, 0, 1, 0]]),\n dtype=tf.int32)\n\n pos_emb_layer = layers.PositionalEmbeddingLayer(p)\n position_embs = pos_emb_layer.FPropWithPosition(pos_emb_layer.theta,\n pos_tensor)\n actual_position_embs, = sess.run([position_embs])\n\n # pylint: disable=bad-whitespace,bad-continuation\n # pyformat: disable\n expected_output = [\n [[ 0. , 0. , 1. , 1. ],\n [ 0.84147096, 0.14237173, 0.54030228, 0.98981327],\n [ 0.90929741, 0.28184283, -0.41614676, 0.95946062],\n [ 0.14112 , 0.4155719 , -0.9899925 , 0.90956032],\n [-0.7568025 , 0.54083425, -0.65364361, 0.84112918],\n [-0.95892417, 0.65507787, 0.28366217, 0.75556135],\n [-0.27941549, 0.75597537, 0.96017027, 0.65460002],\n [ 0. , 0. , 1. , 1. ],\n [ 0.84147096, 0.14237173, 0.54030228, 0.98981327],\n [ 0.90929741, 0.28184283, -0.41614676, 0.95946062],\n [ 0.14112 , 0.4155719 , -0.9899925 , 0.90956032]],\n [[ 0. , 0. , 1. , 1. ],\n [ 0.84147096, 0.14237173, 0.54030228, 0.98981327],\n [ 0.90929741, 0.28184283, -0.41614676, 0.95946062],\n [ 0. , 0. , 1. , 1. ],\n [ 0.84147096, 0.14237173, 0.54030228, 0.98981327],\n [ 0.90929741, 0.28184283, -0.41614676, 0.95946062],\n [ 0.14112 , 0.4155719 , -0.9899925 , 0.90956032],\n [-0.7568025 , 0.54083425, -0.65364361, 0.84112918],\n [ 0. , 0. , 1. , 1. ],\n [ 0.84147096, 0.14237173, 0.54030228, 0.98981327],\n [ 0. , 0. , 1. , 1. ]]\n ]\n # pyformat: enable\n # pylint: enable=bad-whitespace,bad-continuation\n print('expected_position_embs:', expected_output)\n print('actual_position_embs:', actual_position_embs)\n self.assertAllClose(actual_position_embs, expected_output)\n\n def testPositionalEmbeddingLayerWithScaling(self):\n with self.session(use_gpu=False) as sess:\n p = layers.PositionalEmbeddingLayer.Params()\n p.name = 'position_emb'\n p.min_timescale = 1\n p.max_timescale = 7\n p.embedding_dim = 4\n p.trainable_scaling = True\n p.trainable_scaling_init = 1.0 / np.sqrt(p.embedding_dim)\n seq_length = 11\n\n pos_emb_layer = layers.PositionalEmbeddingLayer(p)\n position_embs = pos_emb_layer.FPropDefaultTheta(seq_length)\n tf.global_variables_initializer().run()\n actual_position_embs, = sess.run([position_embs])\n\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_output = [\n [ 0. , 0. , 1. , 1. ],\n [ 0.84147096, 0.14237173, 0.54030228, 0.98981327],\n [ 0.90929741, 0.28184283, -0.41614676, 0.95946062],\n [ 0.14112 , 0.4155719 , -0.9899925 , 0.90956032],\n [-0.7568025 , 0.54083425, -0.65364361, 0.84112918],\n [-0.95892417, 0.65507787, 0.28366217, 0.75556135],\n [-0.27941549, 0.75597537, 0.96017027, 0.65460002],\n [ 0.65698659, 0.84147096, 0.7539022 , 0.54030228],\n [ 0.98935831, 0.90982294, -0.14550003, 0.41499668],\n [ 0.41211855, 0.9596386 , -0.91113025, 0.28123617],\n [-0.54402113, 0.98990309, -0.83907151, 0.14174587]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n self.assertAllClose(expected_output / np.sqrt(p.embedding_dim),\n actual_position_embs)\n\n\nclass SoftmaxLayerTest(test_utils.TestCase):\n\n def _RunSimpleFullSoftmax(self,\n num_shards=1,\n chunk_size=0,\n inputs=None,\n class_ids=None,\n class_weights=None,\n class_probabilities=None,\n num_samples=0,\n default_qdomain=None,\n training_step=-1,\n seed=None,\n dtype=tf.float32,\n fprop_dtype=None,\n apply_pruning=False):\n if fprop_dtype is None:\n fprop_dtype = dtype\n with self.session(use_gpu=True, graph=tf.Graph()) as sess:\n if seed is not None:\n tf.set_random_seed(seed)\n if class_ids is None:\n class_ids = tf.constant([[1], [5], [10]], dtype=tf.int32)\n else:\n class_ids = tf.constant(class_ids)\n if class_weights is None:\n class_weights = tf.constant([1.0, 0.4, 0.8], dtype=fprop_dtype)\n else:\n class_weights = tf.constant(class_weights)\n np.random.seed(12345)\n if inputs is None:\n inputs = [tf.constant(np.random.rand(3, 10), dtype=fprop_dtype)]\n else:\n inputs = [tf.constant(inputs, dtype=fprop_dtype)]\n\n params = layers.SimpleFullSoftmax.Params()\n params.dtype = dtype\n params.fprop_dtype = fprop_dtype\n params.name = 'softmax'\n params.input_dim = 10\n params.num_classes = 32\n params.num_shards = num_shards\n params.chunk_size = chunk_size\n params.apply_pruning = apply_pruning\n params.params_init = py_utils.WeightInit.Gaussian(0.5, 123456)\n params.random_seed = 12345678\n\n if default_qdomain is not None:\n params.qdomain.default = default_qdomain\n\n if num_samples > 0:\n # Turn on sampled soft-max; the asserts need to hold for it to be used.\n params.num_sampled = num_samples\n assert class_probabilities is None\n assert chunk_size == 0\n assert params.is_eval is not True\n\n params.vn.global_vn = False\n softmax = layers.SimpleFullSoftmax(params)\n xent_loss = softmax.FProp(\n softmax.theta,\n inputs,\n class_weights=class_weights,\n class_ids=class_ids,\n class_probabilities=class_probabilities)\n\n all_vars = tf.get_collection('SimpleFullSoftmax_vars')\n expected_var_names = []\n for i in range(num_shards):\n expected_var_names.append(u'softmax/weight_%d/var:0' % i)\n expected_var_names.append(u'softmax/bias_%d/var:0' % i)\n\n all_var_names = [v.name for v in all_vars]\n self.assertEqual(sorted(expected_var_names), sorted(all_var_names))\n\n tf.global_variables_initializer().run()\n if training_step >= 0:\n sess.run(tf.assign(py_utils.GetOrCreateGlobalStepVar(), training_step))\n return sess.run(xent_loss)\n\n def testSimpleFullSoftmaxMasked(self):\n num_shards = 2\n apply_pruning = True\n params = layers.SimpleFullSoftmax.Params()\n params.name = 'softmax'\n params.dtype = tf.float32\n params.input_dim = 10\n params.num_classes = 32\n params.fprop_dtype = tf.float32\n params.num_shards = num_shards\n params.apply_pruning = apply_pruning\n params.random_seed = 12345678\n softmax_layer = layers.SimpleFullSoftmax(params)\n\n self.assertTrue('weight_0' in softmax_layer.vars.weight_0.name)\n self.assertTrue('weight_1' in softmax_layer.vars.weight_1.name)\n self.assertTrue('mask_0' in softmax_layer.vars.mask_0.name)\n self.assertTrue('mask_1' in softmax_layer.vars.mask_1.name)\n self.assertTrue('threshold_0' in softmax_layer.vars.threshold_0.name)\n self.assertTrue('threshold_1' in softmax_layer.vars.threshold_1.name)\n\n self.assertEqual(softmax_layer.theta.weight_0.get_shape(),\n tf.TensorShape([10, 16]))\n self.assertEqual(softmax_layer.theta.weight_1.get_shape(),\n tf.TensorShape([10, 16]))\n self.assertEqual(softmax_layer.theta.mask_0.get_shape(),\n tf.TensorShape([10, 16]))\n self.assertEqual(softmax_layer.theta.mask_1.get_shape(),\n tf.TensorShape([10, 16]))\n self.assertEqual(softmax_layer.theta.threshold_0.get_shape(),\n tf.TensorShape([]))\n self.assertEqual(softmax_layer.theta.threshold_0.get_shape(),\n tf.TensorShape([]))\n\n softmax_var_count = 4 # 2 each for weights and biases (we have 2 shards)\n wts = tf.get_collection('SimpleFullSoftmax_vars')\n self.assertEqual(softmax_var_count, len(wts))\n\n softmax_mask_count = 2\n masks = tf.get_collection('masks')\n self.assertEqual(softmax_mask_count, len(masks))\n\n softmax_threshold_count = 2\n threshold = tf.get_collection('thresholds')\n self.assertEqual(softmax_threshold_count, len(threshold))\n\n # Sampled and Masked\n xent_loss = self._RunSimpleFullSoftmax(\n num_samples=32, seed=12345, apply_pruning=True)\n loss = xent_loss.total_xent\n log_perplexity = xent_loss.avg_xent\n self.assertNear(loss, 8.681571, 1e-5)\n self.assertNear(log_perplexity, 3.946169, 1e-5)\n\n # Sharded and Masked\n xent_loss = self._RunSimpleFullSoftmax(num_shards=2, apply_pruning=True)\n loss = xent_loss.total_xent\n log_perplexity = xent_loss.avg_xent\n self.assertNear(loss, 6.14888, 1e-5)\n self.assertNear(log_perplexity, 2.79495, 1e-5)\n\n # Non_2D and Masked\n xent_loss = self._RunSimpleFullSoftmax(\n inputs=np.random.rand(4, 3, 10),\n class_weights=np.ones((4, 3)),\n class_ids=np.random.randint(32, size=(4, 3)),\n apply_pruning=True)\n self.assertEqual(xent_loss.logits.shape, (4, 3, 32))\n self.assertEqual(xent_loss.per_example_xent.shape, (4, 3))\n self.assertEqual(xent_loss.per_example_weight.shape, (4, 3))\n\n xent_loss = self._RunSimpleFullSoftmax(\n inputs=np.random.rand(4, 3, 10),\n class_weights=np.ones((4, 3)),\n class_probabilities=np.random.uniform(size=(4, 3, 32)),\n apply_pruning=True)\n self.assertEqual(xent_loss.logits.shape, (4, 3, 32))\n self.assertEqual(xent_loss.per_example_xent.shape, (4, 3))\n self.assertEqual(xent_loss.per_example_weight.shape, (4, 3))\n\n # Chunked and Masked\n for chunk_size in (0, 1, 2, 3, 4, 5):\n print('chunk_size = ', chunk_size)\n xent_output = self._RunSimpleFullSoftmax(\n chunk_size=chunk_size, apply_pruning=True)\n loss = xent_output.total_xent\n log_perplexity = xent_output.avg_xent\n print('xent_output ', xent_output)\n print('xent_output.per_example_argmax.dtype ',\n xent_output.per_example_argmax.dtype)\n self.assertAllClose(loss, 6.22425)\n self.assertAllClose(log_perplexity, 2.82920)\n self.assertAllEqual(xent_output.per_example_argmax,\n np.argmax(xent_output.logits, axis=1))\n\n def testSimpleFullSoftmax_Sampled(self):\n xent_loss = self._RunSimpleFullSoftmax(num_samples=32, seed=12345)\n loss = xent_loss.total_xent\n log_perplexity = xent_loss.avg_xent\n self.assertNear(loss, 8.681571, 1e-5)\n self.assertNear(log_perplexity, 3.946169, 1e-5)\n\n def testSimpleFullSoftmax_SampledAndSharded(self):\n xent_loss = self._RunSimpleFullSoftmax(\n num_shards=4, num_samples=32, seed=12345)\n loss = xent_loss.total_xent\n log_perplexity = xent_loss.avg_xent\n self.assertNear(loss, 8.510439, 1e-5)\n self.assertNear(log_perplexity, 3.868381, 1e-5)\n\n def testSimpleFullSoftmax_Non2D(self):\n xent_loss = self._RunSimpleFullSoftmax(\n inputs=np.random.rand(4, 3, 10),\n class_weights=np.ones((4, 3)),\n class_ids=np.random.randint(32, size=(4, 3)))\n self.assertEqual(xent_loss.logits.shape, (4, 3, 32))\n self.assertEqual(xent_loss.per_example_xent.shape, (4, 3))\n self.assertEqual(xent_loss.per_example_weight.shape, (4, 3))\n\n xent_loss = self._RunSimpleFullSoftmax(\n inputs=np.random.rand(4, 3, 10),\n class_weights=np.ones((4, 3)),\n class_probabilities=np.random.uniform(size=(4, 3, 32)))\n self.assertEqual(xent_loss.logits.shape, (4, 3, 32))\n self.assertEqual(xent_loss.per_example_xent.shape, (4, 3))\n self.assertEqual(xent_loss.per_example_weight.shape, (4, 3))\n\n def _testSimpleFullSoftmax_Basic_Helper(self, dtype, fprop_dtype):\n xent_loss = self._RunSimpleFullSoftmax(dtype=dtype, fprop_dtype=fprop_dtype)\n loss = xent_loss.total_xent\n log_perplexity = xent_loss.avg_xent\n print(['loss', loss])\n print(['log_perplexity', log_perplexity])\n err = 1e-5\n if fprop_dtype == tf.float16 or fprop_dtype == tf.bfloat16:\n err = 1e-2\n self.assertNear(loss, 6.22425, err=err)\n self.assertNear(log_perplexity, 2.8292, err=err)\n self.assertAllEqual(xent_loss.per_example_argmax,\n np.argmax(xent_loss.logits, axis=1))\n\n def testSimpleFullSoftmax_Basic_Float32(self):\n self._testSimpleFullSoftmax_Basic_Helper(\n dtype=tf.float32, fprop_dtype=tf.float32)\n\n def testSimpleFullSoftmax_Basic_Float32Float16(self):\n self._testSimpleFullSoftmax_Basic_Helper(\n dtype=tf.float32, fprop_dtype=tf.float16)\n\n def testSimpleFullSoftmax_Sharded(self):\n xent_loss = self._RunSimpleFullSoftmax(2)\n loss = xent_loss.total_xent\n log_perplexity = xent_loss.avg_xent\n print(['loss', loss])\n print(['log_perplexity', log_perplexity])\n self.assertNear(loss, 6.14888, 1e-5)\n self.assertNear(log_perplexity, 2.79495, 1e-5)\n\n def testSimpleFullSoftmax_Chunked(self):\n for chunk_size in (0, 1, 2, 3, 4, 5):\n print('chunk_size = ', chunk_size)\n xent_output = self._RunSimpleFullSoftmax(chunk_size=chunk_size)\n loss = xent_output.total_xent\n log_perplexity = xent_output.avg_xent\n print('xent_output ', xent_output)\n print('xent_output.per_example_argmax.dtype ',\n xent_output.per_example_argmax.dtype)\n self.assertAllClose(loss, 6.22425)\n self.assertAllClose(log_perplexity, 2.82920)\n self.assertAllEqual(xent_output.per_example_argmax,\n np.argmax(xent_output.logits, axis=1))\n\n def testSimpleFullSoftmax_Basic_Distributions(self):\n with self.session(use_gpu=False) as sess:\n class_ids = tf.constant([1, 5, 10], dtype=tf.int32)\n class_weights = tf.constant([1.0, 0.4, 0.8], dtype=tf.float32)\n np.random.seed(12345)\n inputs = [tf.constant(np.random.rand(3, 10), dtype=tf.float32)]\n\n params = layers.SimpleFullSoftmax.Params()\n params.name = 'softmax'\n params.input_dim = 10\n params.num_classes = 32\n params.params_init = py_utils.WeightInit.Gaussian(0.5, 123456)\n params.vn.global_vn = False\n softmax = layers.SimpleFullSoftmax(params)\n xent_loss = softmax.XentLoss(\n inputs,\n class_weights=class_weights,\n class_probabilities=tf.one_hot(class_ids, params.num_classes))\n tf.global_variables_initializer().run()\n loss = sess.run(xent_loss.total_xent)\n log_perplexity = sess.run(xent_loss.avg_xent)\n print(['loss', loss])\n print(['log_perplexity', log_perplexity])\n self.assertNear(loss, 6.22425, 1e-5)\n self.assertNear(log_perplexity, 2.8292, 1e-5)\n\n def testSimpleFullSoftmax_GlobalVN(self):\n with self.session(use_gpu=False) as sess:\n class_ids = tf.constant([1, 5, 10], dtype=tf.int32)\n class_weights = tf.constant([1.0, 0.4, 0.8], dtype=tf.float32)\n np.random.seed(12345)\n inputs = [tf.constant(np.random.rand(3, 10), dtype=tf.float32)]\n\n params = layers.SimpleFullSoftmax.Params()\n params.name = 'softmax'\n params.input_dim = 10\n params.num_classes = 32\n params.params_init = py_utils.WeightInit.Gaussian(0.5, 123456)\n params.vn.global_vn = True\n params.vn.seed = 23456\n params.vn.scale = 1.0\n softmax = layers.SimpleFullSoftmax(params)\n xent_loss = softmax.XentLoss(\n inputs, class_weights=class_weights, class_ids=class_ids)\n tf.global_variables_initializer().run()\n loss = sess.run(xent_loss.total_xent)\n log_perplexity = sess.run(xent_loss.avg_xent)\n print(['testSimpleFullSoftmax_GlobalVN loss', loss])\n print(['testSimpleFullSoftmax_GlobalVN log_perplexity', log_perplexity])\n self.assertNear(loss, 19.9612, 1e-4)\n self.assertNear(log_perplexity, 3.46426, 1e-4)\n\n def testSimpleFullSoftmax_PerStepVN(self):\n with self.session(use_gpu=False) as sess:\n class_ids = tf.constant([1, 5, 10], dtype=tf.int32)\n class_weights = tf.constant([1.0, 0.4, 0.8], dtype=tf.float32)\n np.random.seed(12345)\n inputs = [tf.constant(np.random.rand(3, 10), dtype=tf.float32)]\n\n params = layers.SimpleFullSoftmax.Params()\n params.name = 'softmax'\n params.input_dim = 10\n params.num_classes = 32\n params.params_init = py_utils.WeightInit.Gaussian(0.5, 123456)\n params.vn.global_vn = False\n params.vn.per_step_vn = True\n params.vn.seed = 23456\n params.vn.scale = 1.0\n softmax = layers.SimpleFullSoftmax(params)\n xent_loss = softmax.XentLoss(\n inputs, class_weights=class_weights, class_ids=class_ids)\n tf.global_variables_initializer().run()\n loss = sess.run(xent_loss.total_xent)\n log_perplexity = sess.run(xent_loss.avg_xent)\n print(['testShardedFullSoftmax_PerStepVN loss', loss])\n print(['testShardedFullSoftmax_PerStepVN log_perplexity', log_perplexity])\n self.assertNear(loss, 19.9612, 1e-4)\n self.assertNear(log_perplexity, 3.46426, 1e-4)\n\n def testSimpleFullSoftmax_FakeQuantized(self):\n default_qdomain = quant_utils.SymmetricScheduledClipQDomain.Params()\n default_qdomain.cc_schedule = quant_utils.FakeQuantizationSchedule.Params(\n ).Set(\n clip_start_step=0, clip_end_step=2, quant_start_step=2)\n xent_loss = self._RunSimpleFullSoftmax(\n default_qdomain=default_qdomain, training_step=5)\n loss = xent_loss.total_xent\n log_perplexity = xent_loss.avg_xent\n print(['loss', loss])\n print(['log_perplexity', log_perplexity])\n self.assertNear(loss, 6.285590, 1e-5)\n self.assertNear(log_perplexity, 2.857086, 1e-5)\n\n def _RunSimpleFullSoftmaxGradientChecker(self, batch_size, num_classes,\n chunk_size, num_shards):\n for (dtype, use_gpu, tolerance) in [(tf.float32, True, 1e-2),\n (tf.float64, False, 1e-6)]:\n tf.logging.info('dtype %s tolerance %g', dtype, tolerance)\n with self.session(use_gpu=use_gpu, graph=tf.Graph()) as sess:\n input_dim = 10\n np.random.seed(12345)\n class_ids = tf.constant(\n np.random.randint(num_classes, size=(batch_size, 1)),\n dtype=tf.int32)\n class_weights = tf.constant(np.random.rand(batch_size), dtype=dtype)\n inputs = [\n tf.constant(np.random.rand(batch_size, input_dim), dtype=dtype)\n ]\n\n params = layers.SimpleFullSoftmax.Params()\n params.name = 'softmax'\n params.dtype = dtype\n params.input_dim = input_dim\n params.num_classes = num_classes\n params.num_shards = num_shards\n params.chunk_size = chunk_size\n params.params_init = py_utils.WeightInit.Gaussian(0.5, 123456)\n params.vn.global_vn = False\n softmax = layers.SimpleFullSoftmax(params)\n xent_loss = softmax.XentLoss(\n inputs, class_weights=class_weights, class_ids=class_ids)\n softmax_vars = softmax.vars.Flatten()\n # Now add the backward graph.\n grads = tf.gradients(xent_loss.total_xent, softmax_vars)\n\n tf.global_variables_initializer().run()\n assert len(softmax_vars) == len(grads)\n for x, grad_x in zip(softmax_vars, grads):\n grad_symbolic = sess.run(grad_x)\n grad_numeric = test_utils.ComputeNumericGradient(\n sess, xent_loss.total_xent, x)\n self.assertAllClose(\n grad_symbolic, grad_numeric, atol=tolerance, rtol=tolerance)\n\n def testSimpleFullSoftmaxGradientChecker(self):\n self._RunSimpleFullSoftmaxGradientChecker(3, 4, 0, 1)\n self._RunSimpleFullSoftmaxGradientChecker(3, 4, 0, 2)\n self._RunSimpleFullSoftmaxGradientChecker(3, 4, 2, 2)\n self._RunSimpleFullSoftmaxGradientChecker(3, 4, 5, 2)\n\n\nclass SoftmaxLayerLogitsTest(test_utils.TestCase):\n \"\"\"Testing SoftmaxLayer.Logits().\"\"\"\n\n def _Logits(self, params, batch_size=2, seq_length=None):\n with self.session(use_gpu=True, graph=tf.Graph()):\n np.random.seed(12345)\n tf.set_random_seed(1234)\n\n params.name = 'softmax'\n if not params.input_dim:\n params.input_dim = 3\n if not params.num_classes:\n params.num_classes = 4\n params.params_init = py_utils.WeightInit.Gaussian(0.5, 123456)\n softmax = params.Instantiate()\n\n input_dim = params.input_dim\n if seq_length:\n inputs = np.random.rand(batch_size, seq_length, input_dim)\n else:\n inputs = np.random.rand(batch_size, input_dim)\n inputs = tf.constant(inputs, dtype=py_utils.FPropDtype(params))\n logits = softmax.Logits(softmax.theta, inputs)\n\n if seq_length:\n logits = py_utils.HasShape(logits,\n [batch_size, seq_length, params.num_classes])\n else:\n logits = py_utils.HasShape(logits, [batch_size, params.num_classes])\n tf.global_variables_initializer().run()\n return logits.eval()\n\n def testConvSoftmaxLogits(self):\n params = layers.ConvSoftmax.Params()\n self.assertAllClose([[0.52536774, -0.17598523, 0.38314393, -0.36068222],\n [0.75792629, -0.18001975, 0.42298675, -0.35423514]],\n self._Logits(params))\n\n def testSimpleFullSoftmax(self):\n params = layers.SimpleFullSoftmax.Params()\n self.assertAllClose([[0.52536774, -0.17598523, 0.38314393, -0.36068222],\n [0.75792629, -0.18001975, 0.42298675, -0.35423514]],\n self._Logits(params))\n\n def testConvSoftmaxLogitsWith3DInputs(self):\n params = layers.ConvSoftmax.Params()\n logits = self._Logits(params, seq_length=5)\n self.assertAllClose(6.9934864, np.sum(logits))\n\n\nclass FeedForwardNetTest(test_utils.TestCase):\n\n def testFeedForwardNetConstruction(self):\n with self.session(use_gpu=False):\n p = layers.FeedForwardNet.Params().Set(\n name='ffn',\n input_dim=10,\n hidden_layer_dims=[20, 30],\n batch_norm=True,\n activation='TANH',\n params_init=py_utils.WeightInit.Uniform(1.0))\n p.dropout.keep_prob = 0.5\n proj_l = p.Instantiate()\n a = tf.constant(1.0, shape=[20, 10])\n proj_l.FPropDefaultTheta(a)\n\n p = layers.FeedForwardNet.Params().Set(\n name='ffn2',\n input_dim=10,\n hidden_layer_dims=[20, 30],\n batch_norm=True,\n activation='TANH',\n params_init=py_utils.WeightInit.Uniform(1.0))\n p.dropout = [\n layers.DropoutLayer.Params().Set(keep_prob=0.5),\n layers.DropoutLayer.Params().Set(keep_prob=0.9)\n ]\n proj_l = p.Instantiate()\n a = tf.constant(1.0, shape=[20, 10])\n proj_l.FPropDefaultTheta(a)\n\n p = layers.FeedForwardNet.Params().Set(\n name='ffn3',\n input_dim=10,\n hidden_layer_dims=[20, 30],\n batch_norm=[True, False],\n activation=['TANH', 'RELU'],\n params_init=py_utils.WeightInit.Uniform(1.0))\n p.dropout = [\n layers.DropoutLayer.Params().Set(keep_prob=0.5),\n layers.DropoutLayer.Params().Set(keep_prob=0.9)\n ]\n proj_l = p.Instantiate()\n a = tf.constant(1.0, shape=[20, 10])\n proj_l.FPropDefaultTheta(a)\n\n def testFeedForwardNet(self):\n with self.session(use_gpu=False) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n p = layers.FeedForwardNet.Params().Set(\n name='ffn',\n input_dim=10,\n hidden_layer_dims=[20, 30],\n batch_norm=False,\n activation=['RELU', 'NONE'])\n params_init = py_utils.WeightInit.Xavier(scale=1.0, seed=837465638)\n p.params_init = params_init\n feedforward_net = p.Instantiate()\n\n p1 = layers.ProjectionLayer.Params().Set(\n name='p1',\n input_dim=10,\n output_dim=20,\n activation='RELU',\n batch_norm=False)\n p1.params_init = params_init\n p1_l = p1.Instantiate()\n\n p2 = layers.ProjectionLayer.Params().Set(\n name='p2',\n input_dim=20,\n output_dim=30,\n activation='NONE',\n batch_norm=False)\n p2.params_init = params_init\n p2_l = p2.Instantiate()\n\n a = tf.constant(np.random.rand(5, 10), dtype=tf.float32)\n out1 = feedforward_net.FPropDefaultTheta(a)\n\n out2 = p2_l.FPropDefaultTheta(p1_l.FPropDefaultTheta(a))\n\n tf.global_variables_initializer().run()\n out1_v, out2_v = sess.run([out1, out2])\n self.assertAllClose(out1_v, out2_v)\n\n def testFeedForwardNetQuantized(self):\n with self.session(use_gpu=False) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n\n cc_schedule = quant_utils.FakeQuantizationSchedule.Params().Set(\n clip_start_step=1,\n clip_end_step=2,\n quant_start_step=2,\n start_cap=8.0,\n end_cap=2.0)\n proj_qdomain = quant_utils.SymmetricScheduledClipQDomain.Params().Set(\n cc_schedule=cc_schedule)\n\n p = layers.FeedForwardNet.Params().Set(\n name='ffn',\n input_dim=10,\n hidden_layer_dims=[20, 30],\n batch_norm=False,\n activation=['RELU', 'NONE'])\n p.qdomain.default = proj_qdomain.Copy()\n params_init = py_utils.WeightInit.Xavier(scale=1.0, seed=837465638)\n p.params_init = params_init\n feedforward_net = p.Instantiate()\n\n p1 = layers.ProjectionLayer.Params().Set(\n name='p1',\n input_dim=10,\n output_dim=20,\n activation='RELU',\n batch_norm=False)\n p1.qdomain.default = proj_qdomain.Copy()\n p1.params_init = params_init\n p1_l = p1.Instantiate()\n\n p2 = layers.ProjectionLayer.Params().Set(\n name='p2',\n input_dim=20,\n output_dim=30,\n activation='NONE',\n batch_norm=False)\n p2.params_init = params_init\n p2.qdomain.default = proj_qdomain.Copy()\n p2_l = p2.Instantiate()\n\n a = tf.constant(np.random.rand(5, 10), dtype=tf.float32)\n out1 = feedforward_net.FPropDefaultTheta(a)\n out2 = p2_l.FPropDefaultTheta(p1_l.FPropDefaultTheta(a))\n\n tf.global_variables_initializer().run()\n\n sess.run(tf.assign(py_utils.GetOrCreateGlobalStepVar(), 5))\n out1_v, out2_v = sess.run([out1, out2])\n self.assertAllClose(out1_v, out2_v)\n\n def testFeedForwardNetBnFolded(self):\n with self.session(use_gpu=False) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n p = layers.FeedForwardNet.Params().Set(\n name='ffn',\n input_dim=10,\n hidden_layer_dims=[20, 30],\n batch_norm=True,\n bn_fold_weights=True,\n activation=['RELU', 'NONE'])\n params_init = py_utils.WeightInit.Xavier(scale=1.0, seed=837465638)\n p.params_init = params_init\n feedforward_net = p.Instantiate()\n\n p1 = layers.ProjectionLayer.Params().Set(\n name='p1',\n input_dim=10,\n output_dim=20,\n activation='RELU',\n batch_norm=True,\n bn_fold_weights=True)\n p1.params_init = params_init\n p1_l = p1.Instantiate()\n\n p2 = layers.ProjectionLayer.Params().Set(\n name='p2',\n input_dim=20,\n output_dim=30,\n activation='NONE',\n batch_norm=True,\n bn_fold_weights=True)\n p2.params_init = params_init\n p2_l = p2.Instantiate()\n\n a = tf.constant(np.random.rand(5, 10), dtype=tf.float32)\n out1 = feedforward_net.FPropDefaultTheta(a)\n\n out2 = p2_l.FPropDefaultTheta(p1_l.FPropDefaultTheta(a))\n\n tf.global_variables_initializer().run()\n out1_v, out2_v = sess.run([out1, out2])\n self.assertAllClose(out1_v, out2_v)\n\n def testFeedForwardNetSmokeTest(self):\n with self.session(use_gpu=False):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n p = layers.FeedForwardNet.Params().Set(\n name='ffn',\n input_dim=10,\n hidden_layer_dims=[20, 30],\n activation=['RELU', 'NONE'])\n params_init = py_utils.WeightInit.Xavier(scale=1.0, seed=837465638)\n p.params_init = params_init\n feedforward_net = p.Instantiate()\n a = tf.constant(np.random.rand(5, 10), dtype=tf.float32)\n out = tf.reduce_sum(feedforward_net.FPropDefaultTheta(a))\n out_abs = tf.reduce_sum(tf.abs(feedforward_net.FPropDefaultTheta(a)))\n\n tf.global_variables_initializer().run()\n # pyformat: disable\n test_utils.CompareToGoldenSingleFloat(self, 8.190775, out.eval(), atol=1e-5) # pylint: disable=line-too-long\n # pyformat: enable\n test_utils.CompareToGoldenSingleFloat(self, 36.773586, out_abs.eval())\n\n def testDropoutLayerTrain(self):\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(3980847392)\n p = layers.DropoutLayer.Params()\n p.keep_prob = 0.5\n p.random_seed = 1234\n p.name = 'dropout'\n\n dl = p.Instantiate()\n\n x = tf.random_normal([10, 10, 10, 3])\n xd = dl.FPropDefaultTheta(x)\n x, xd = sess.run([x, xd])\n self.assertGreater((xd == 0).mean(), 0.3)\n self.assertLess((xd == 0).mean(), 0.7)\n self.assertAllClose(xd[xd != 0], x[xd != 0] / p.keep_prob)\n\n def testDropoutLayerEval(self):\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(3980847392)\n p = layers.DropoutLayer.Params()\n p.keep_prob = 0.5\n p.random_seed = 1234\n p.name = 'dropout'\n p.is_eval = True\n\n dl = p.Instantiate()\n\n x = tf.random_normal([10, 10, 10, 3])\n xd = dl.FPropDefaultTheta(x)\n\n x, xd = sess.run([x, xd])\n\n self.assertAllEqual(xd, x)\n\n\nclass AddingAccumulatorTest(test_utils.TestCase):\n \"\"\"Test for AddingAccumulator.\"\"\"\n\n def testAddingAccumulator(self):\n with self.session():\n layer_p = layers.IdentityLayer.Params()\n layer_p.name = 'test'\n layer = layer_p.Instantiate()\n\n layer.RegisterAccumulator('acc1', layers.AddingAccumulator([],\n tf.float32))\n\n # Initial value.\n self.assertEqual(0.0, layer.accumulators.acc1.GetValue().eval())\n\n # Update/merge.\n layer.accumulators.acc1.Update(1.0)\n layer.accumulators.acc1.Update(1.0)\n self.assertEqual(2.0, layer.accumulators.acc1.GetValue().eval())\n\n # Reset.\n layer.accumulators.Transform(lambda acc: acc.Reset())\n self.assertEqual(0.0, layer.accumulators.acc1.GetValue().eval())\n\n\nclass BatchNormLayerNoPaddingTest(test_utils.TestCase, parameterized.TestCase):\n\n def testBatchNormLayerNoPaddingConstruction(self):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.BatchNormLayerNoPadding.Params()\n params.name = 'bn'\n params.dim = 2\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n layers.BatchNormLayerNoPadding(params)\n bn_vars = tf.get_collection('BatchNormLayerNoPadding_vars')\n bn_var_names = [x.name for x in bn_vars]\n expected_var_names = [\n 'bn/beta/var:0', 'bn/gamma/var:0', 'bn/moving_mean/var:0',\n 'bn/moving_variance/var:0'\n ]\n self.assertEqual(expected_var_names, bn_var_names)\n\n @parameterized.named_parameters({\n 'testcase_name': '_eval',\n 'is_eval': True,\n }, {\n 'testcase_name': '_train',\n 'is_eval': False,\n })\n def testBatchNormLayerNoPaddingFProp(self, is_eval):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.BatchNormLayerNoPadding.Params()\n params.name = 'bn'\n params.dim = 3\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = is_eval\n\n bn_layer = layers.BatchNormLayerNoPadding(params)\n bn_in1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 8, 3]), dtype=tf.float32)\n\n bn_out = bn_layer.FPropDefaultTheta(bn_in1)\n sig1 = tf.reduce_sum(bn_out)\n sig2 = tf.reduce_sum(bn_out * bn_out)\n expected_sig1 = 2.6593573 if is_eval else 0\n expected_sig2 = 15.4642076 if is_eval else 47.850193\n with self.session(use_gpu=True):\n tf.global_variables_initializer().run()\n self.assertAllClose(expected_sig1, sig1.eval(), atol=1e-5)\n self.assertAllClose(expected_sig2, sig2.eval(), atol=1e-5)\n\n def testBatchNormLayerNoPaddingFPropUseGlobalStatsForTraining(self):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.BatchNormLayerNoPadding.Params()\n params.name = 'bn'\n params.dim = 3\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n\n bn_layer = layers.BatchNormLayerNoPadding(params)\n bn_in1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 8, 3]), dtype=tf.float32)\n\n bn_out = bn_layer.FPropDefaultTheta(bn_in1)\n sig1 = tf.reduce_sum(bn_out)\n sig2 = tf.reduce_sum(bn_out * bn_out)\n with self.session(use_gpu=True):\n tf.global_variables_initializer().run()\n self.assertAllClose(1.19209289551e-06, sig1.eval(), atol=1e-5)\n self.assertAllClose(47.8501930237, sig2.eval(), atol=1e-5)\n\n def testBatchNormLayerNoPaddingPostTrainingStepUpdate(self):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.BatchNormLayerNoPadding.Params()\n params.name = 'bn'\n params.dim = 2\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n\n bn_layer = layers.BatchNormLayerNoPadding(params)\n bn_layer.accumulators.counts.Update(0.0)\n bn_layer.accumulators.mean_ss.Update([1.0, 1.0])\n bn_layer.accumulators.variance_ss.Update([5.0, 5.0])\n bn_updates = bn_layer.PostTrainingStepUpdate(tf.constant(100))\n\n with self.session(use_gpu=True) as sess:\n tf.global_variables_initializer().run()\n sess.run(bn_updates)\n moving_mean = sess.run(bn_layer.vars.moving_mean)\n moving_std = sess.run(bn_layer.vars.moving_variance)\n self.assertAllClose([0.0, 0.0], moving_mean)\n self.assertAllClose([1.0, 1.0], moving_std)\n\n def testBatchNormLayerNoPaddingFPropForConv(self):\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n params = layers.BatchNormLayerNoPadding.Params()\n params.name = 'bn_conv'\n params.dim = 32\n params.params_init = py_utils.WeightInit.Gaussian(0.1)\n params.is_eval = False\n\n bn_layer = layers.BatchNormLayerNoPadding(params)\n bn_in1 = tf.constant(\n np.random.normal(0.1, 0.5, [2, 8, 4, 32]), dtype=tf.float32)\n\n bn_out = bn_layer.FPropDefaultTheta(bn_in1)\n sig1 = tf.reduce_sum(bn_out)\n sig2 = tf.reduce_sum(bn_out * bn_out)\n with self.session(use_gpu=True):\n tf.global_variables_initializer().run()\n self.assertAllClose(0.0, sig1.eval(), atol=1e-4)\n self.assertAllClose(2039.398681, sig2.eval())\n\n def _BuildDummyStackedBNLayer(self, splits):\n num_micro_batches = 8\n if splits == 0:\n endpoint = layers.BatchNormLayerNoPadding.Params().Set(\n decay=0.997, name='bn', dim=1)\n else:\n cell_tpl = []\n for split in range(splits):\n nets_to_split = [\n layers.BatchNormLayerNoPadding.Params().Set(\n decay=0.997, name='bn_{}'.format(split), dim=1),\n ]\n split_layer = gpipe.FeatureExtractionLayer.Params().Set(\n name='split_{}'.format(split), sub=nets_to_split)\n cell_tpl.append(split_layer)\n endpoint = gpipe.PipeliningLayer.Params().Set(\n name='pipeline',\n num_micro_batches=num_micro_batches,\n cell_tpl=cell_tpl,\n before_tpl=[])\n layer = endpoint.Instantiate()\n return layer\n\n @parameterized.named_parameters({\n 'testcase_name': '_baseline',\n 'splits': 0,\n }, {\n 'testcase_name': '_two_splits',\n 'splits': 2,\n }, {\n 'testcase_name': '_four_splits',\n 'splits': 4,\n })\n def testBatchNormLayerNoPaddingAccumulators(self, splits):\n batch_size = 1024\n with self.session(graph=tf.Graph()) as sess:\n # Construct a network where loss = w * x + b\n inputs = tf.concat([\n tf.ones([batch_size // 2, 1, 1, 1]),\n tf.zeros([batch_size // 2, 1, 1, 1])\n ],\n axis=0)\n net = self._BuildDummyStackedBNLayer(splits)\n logits = net.FPropDefaultTheta(inputs)\n loss = tf.reduce_mean(logits)\n grads = tf.gradients(loss, tf.trainable_variables())\n # Check the accumulator values\n counts = []\n means = []\n variances = []\n for i in range(splits):\n l = net.children['split_{}'.format(i)].children['bn_{}'.format(i)]\n counts.append(l.accumulators.counts.GetValue())\n means.append(l.accumulators.mean_ss.GetValue())\n variances.append(l.accumulators.variance_ss.GetValue())\n if splits == 0:\n counts.append(net.accumulators.counts.GetValue())\n means.append(net.accumulators.mean_ss.GetValue())\n variances.append(net.accumulators.variance_ss.GetValue())\n post_training_step_updates = net.PostTrainingStepUpdate(\n net.theta.global_step)\n\n sess.run(tf.global_variables_initializer())\n _, count_vals, mean_vals, var_vals = sess.run(\n [grads, counts, means, variances])\n\n self.assertSameElements(count_vals, {batch_size})\n\n self.assertEqual(batch_size // 2, mean_vals[0])\n if len(mean_vals) > 1:\n self.assertSameElements(mean_vals[1:], {0})\n\n self.assertEqual(batch_size // 2, var_vals[0])\n if len(var_vals) > 1:\n self.assertSameElements(var_vals[1:], {0})\n sess.run(post_training_step_updates)\n moving_vars = sess.run(tf.get_collection('moving_vars'))\n self.assertEqual(0.0015, moving_vars[0])\n self.assertNear(0.997750, moving_vars[1], err=1.0e-6)\n\n\nclass LayerNormTest(test_utils.TestCase):\n\n def testLayerNormFProp(self):\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n p = layers.LayerNorm.Params()\n p.name = 'ln'\n p.input_dim = 3\n layer_norm = layers.LayerNorm(p)\n npy_input = np.random.normal(1.0, 0.5,\n [2, 4, 4, p.input_dim]).astype('float32')\n inputs = tf.constant(npy_input, dtype=tf.float32)\n output = layer_norm.FPropDefaultTheta(inputs)\n\n tf.global_variables_initializer().run()\n sym_output = sess.run(output)\n\n # Mean should be zero and variance should be close to one.\n self.assertNear(0.0, sym_output.sum(), 1e-5)\n self.assertNear(1.0, np.var(sym_output), 1e-4)\n\n # Compare with numpy.\n mean = npy_input.mean(-1, keepdims=True)\n variance = np.mean(np.square(npy_input - mean), -1, keepdims=True)\n npy_output = (npy_input - mean) / np.sqrt(variance + p.epsilon)\n self.assertAllClose(sym_output, npy_output)\n\n def testLayerNormBProp(self):\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n p = layers.LayerNorm.Params()\n p.name = 'ln'\n p.input_dim = 3\n layer_norm = layers.LayerNorm(p)\n\n inputs = tf.constant(\n np.random.normal(0.1, 0.5, [2, 4, 4, p.input_dim]), dtype=tf.float32)\n output = layer_norm.FPropDefaultTheta(inputs)\n loss = tf.reduce_sum(output)\n\n all_vars = tf.trainable_variables()\n self.assertEqual(2, len(all_vars))\n\n grads = tf.gradients(loss, all_vars)\n tf.global_variables_initializer().run()\n sym_grads = [sg.eval() for sg in grads]\n num_grads = [\n test_utils.ComputeNumericGradient(sess, loss, v) for v in all_vars\n ]\n\n for sg, ng in zip(sym_grads, num_grads):\n self.assertAllClose(sg, ng, rtol=1e-02, atol=1e-02)\n\n\nclass DeterministicDropoutTest(test_utils.TestCase, parameterized.TestCase):\n\n def testDeterministicDropoutLayer(self):\n params = layers.DeterministicDropoutLayer.Params().Set(keep_prob=0.7)\n params.name = 'drop'\n dropout = layers.DeterministicDropoutLayer(params)\n\n x = tf.ones([4, 6], dtype=tf.float32)\n x_expected = np.array([\n [1, 0, 0, 0, 1, 1],\n [1, 1, 1, 1, 1, 1],\n [1, 0, 0, 1, 1, 0],\n [1, 0, 0, 1, 1, 1],\n ]) / 0.7\n\n with self.session():\n tf.assign(py_utils.GetOrCreateGlobalStepVar(), 1234).eval()\n py_utils.ResetStepSeed(seed=5678)\n x_val = dropout.FPropDefaultTheta(x).eval()\n self.assertAllClose(x_expected, x_val)\n self.assertEqual(5679, py_utils.GetStepSeed().eval())\n\n # Different step seed gives different result.\n x_val = dropout.FPropDefaultTheta(x).eval()\n self.assertNotAllClose(x_expected, x_val)\n\n # Different global step gives different result\n tf.assign(py_utils.GetOrCreateGlobalStepVar(), 1235).eval()\n py_utils.ResetStepSeed(seed=5678)\n x_val = dropout.FPropDefaultTheta(x).eval()\n self.assertNotAllClose(x_expected, x_val)\n\n # The same seeds in the same session is consistent.\n tf.assign(py_utils.GetOrCreateGlobalStepVar(), 1234).eval()\n py_utils.ResetStepSeed(seed=5678)\n x_val = dropout.FPropDefaultTheta(x).eval()\n self.assertAllClose(x_expected, x_val)\n\n # The same seeds in a different session is consistent.\n with self.session():\n tf.assign(py_utils.GetOrCreateGlobalStepVar(), 1234).eval()\n py_utils.ResetStepSeed(seed=5678)\n x_val = dropout.FPropDefaultTheta(x).eval()\n self.assertAllClose(x_expected, x_val)\n\n def testNoiseShapeBroadcastDims(self):\n params = layers.DeterministicDropoutLayer.Params().Set(\n keep_prob=0.7, noise_shape_broadcast_dims=[-1])\n params.name = 'drop'\n dropout = layers.DeterministicDropoutLayer(params)\n\n x = tf.ones([4, 6])\n x_expected = np.array([\n [1, 1, 1, 1, 1, 1],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n ]) / 0.7\n\n with self.session():\n tf.assign(py_utils.GetOrCreateGlobalStepVar(), 1234).eval()\n self.assertEqual(1234, dropout.theta.global_step.eval())\n py_utils.ResetStepSeed(seed=5678)\n x_val = dropout.FPropDefaultTheta(x).eval()\n self.assertEqual(5679, py_utils.GetStepSeed().eval())\n self.assertAllClose(x_expected, x_val)\n\n @parameterized.named_parameters(\n {\n 'testcase_name': 'baseline',\n 'splits': 1,\n 'num_micro_batches': 1\n },\n {\n 'testcase_name': 'OneSplitTwoMicroBatches',\n 'splits': 1,\n 'num_micro_batches': 2\n },\n {\n 'testcase_name': 'TwoSplitsOneMicroBatch',\n 'splits': 2,\n 'num_micro_batches': 1\n },\n {\n 'testcase_name': 'TwoSplitsTwoMicroBatches',\n 'splits': 2,\n 'num_micro_batches': 2\n },\n )\n def testDropoutInRecurrent(self, splits=1, num_micro_batches=1):\n \"\"\"Test to verify the drop mask used in fprop and bprop is identical.\"\"\"\n assert splits in [1, 2, 4]\n with self.session() as sess:\n tf.set_random_seed(12345)\n num_layers = 4\n # Build a model with 4 dropout layers.\n blocks = []\n for l in range(num_layers):\n blocks.append(layers.DeterministicDropoutLayer.Params().Set(\n name='dropout_{}'.format(l), keep_prob=0.7))\n # Divide the model into splits partitions.\n cell_tpl = []\n blocks_per_split = num_layers // splits\n for i in range(splits):\n sub = blocks[i * blocks_per_split:(i + 1) * blocks_per_split]\n cell_tpl.append(gpipe.FeatureExtractionLayer.Params().Set(\n name='cell_{}'.format(i), sub=sub))\n # Parallelize partitions using pipeline.\n p = gpipe.PipeliningLayer.Params().Set(\n name='pipeline',\n num_micro_batches=num_micro_batches,\n cell_tpl=cell_tpl)\n # Fake input\n x = tf.ones([2, 3])\n # Construct weights.\n w = tf.get_variable(\n 'w', shape=[2, 3], initializer=tf.constant_initializer([[1] * 3] * 2))\n mdl = p.Instantiate()\n y = mdl.FPropDefaultTheta(x * w)\n # Construct loss function such that gradients = final activation.\n loss = tf.reduce_sum(y)\n grads = py_utils.ComputeGradients(loss, py_utils.NestedMap(w=w))\n tf.global_variables_initializer().run()\n y_val = sess.run(y)\n grads_val = sess.run(grads)['w'][1]\n self.assertAllClose(y_val, grads_val)\n\n\nclass GradNormTrackerTest(test_utils.TestCase):\n\n def testGradNormTracker(self):\n with self.session(use_gpu=False) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n p = layers.GradNormTracker.Params().Set(\n name='grad_norm_tracker', clip_threshold=3.0)\n grad_norm_tracker = p.Instantiate()\n grad_norm = tf.placeholder(tf.float32)\n grad_norm_clip = grad_norm_tracker.FPropDefaultTheta(grad_norm)\n\n tf.global_variables_initializer().run()\n\n random_normal = np.exp(np.random.normal(5.0, 1.0, size=10000))\n # We are expected to reject 16% of the outliers.\n outliers = np.exp(np.random.normal(7.0, 1.0, size=100))\n total_rejections = 0\n for i in range(100):\n for j in range(100):\n sess.run([grad_norm_clip], {grad_norm: random_normal[i * 100 + j]})\n clip = sess.run([grad_norm_clip], {grad_norm: outliers[i]})[0]\n if clip == 0.0:\n total_rejections += 1\n # Q(yonghui): Why is total_rejections not deterministic?\n print('total_rejections', total_rejections)\n self.assertGreater(total_rejections, 5)\n\n def testGradNormTrackerClipCapMin(self):\n with self.session(use_gpu=False) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n p = layers.GradNormTracker.Params().Set(\n name='grad_norm_tracker',\n clip_threshold=3.0,\n grad_norm_clip_cap_min=math.exp(10.0))\n grad_norm_tracker = p.Instantiate()\n grad_norm = tf.placeholder(tf.float32)\n grad_norm_clip = grad_norm_tracker.FPropDefaultTheta(grad_norm)\n\n tf.global_variables_initializer().run()\n\n random_normal = np.exp(np.random.normal(5.0, 1.0, size=10000))\n # We expect no outliers being rejected due to the grad_norm_clip_cap_min.\n outliers = np.exp(np.random.normal(7.0, 1.0, size=100))\n total_rejections = 0\n for i in range(100):\n for j in range(100):\n sess.run([grad_norm_clip], {grad_norm: random_normal[i * 100 + j]})\n clip = sess.run([grad_norm_clip], {grad_norm: outliers[i]})[0]\n if clip == 0.0:\n total_rejections += 1\n print('total_rejections', total_rejections)\n self.assertEqual(total_rejections, 0)\n\n def testGradNormTrackerHasNan(self):\n with self.session(use_gpu=False) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n p = layers.GradNormTracker.Params().Set(\n name='grad_norm_tracker', clip_threshold=3.0)\n grad_norm_tracker = p.Instantiate()\n grad_norm = tf.placeholder(tf.float32)\n has_nan = tf.cast(tf.ones([]), dtype=tf.bool)\n grad_norm_clip = grad_norm_tracker.FPropDefaultTheta(grad_norm, has_nan)\n\n tf.global_variables_initializer().run()\n\n random_normal = np.exp(np.random.normal(5.0, 1.0, size=10000))\n outliers = np.exp(np.random.normal(7.0, 1.0, size=100))\n total_rejections = 0\n for i in range(100):\n for j in range(100):\n sess.run([grad_norm_clip], {grad_norm: random_normal[i * 100 + j]})\n clip = sess.run([grad_norm_clip], {grad_norm: outliers[i]})[0]\n if clip == 0.0:\n total_rejections += 1\n self.assertEqual(total_rejections, 100)\n\n\nclass HighwaySkipLayerTest(test_utils.TestCase):\n\n def testHighwaySkipLayerConstruction(self):\n with self.session(use_gpu=False):\n p = layers.HighwaySkipLayer.Params().Set(\n name='gffn',\n input_dim=10,\n carry_bias_init=1.0,\n couple_carry_transform_gates=True,\n batch_norm=False,\n params_init=py_utils.WeightInit.Uniform(1.0))\n proj_l = p.Instantiate()\n a = tf.constant(1.0, shape=[20, 10])\n b = tf.constant(-2.0, shape=[20, 10])\n proj_l.FPropDefaultTheta(a, b)\n\n def testHighwaySkipLayerCarryGate(self):\n with self.session(use_gpu=False) as sess:\n tf.set_random_seed(398847392)\n np.random.seed(12345)\n p = layers.HighwaySkipLayer.Params().Set(\n name='gffn',\n input_dim=10,\n carry_bias_init=1000.0,\n couple_carry_transform_gates=True,\n batch_norm=False,\n params_init=py_utils.WeightInit.Uniform(1.0))\n proj_l = p.Instantiate()\n a = tf.constant(1.0, shape=[20, 10])\n b = tf.constant(-2.0, shape=[20, 10])\n out = proj_l.FPropDefaultTheta(a, b)\n tf.global_variables_initializer().run()\n a, out = sess.run([a, out])\n self.assertAllClose(a, out)\n\n\nclass UniformLabelSmootherTest(test_utils.TestCase):\n\n def testUniformLabelSmoother(self):\n with self.session(use_gpu=False):\n params = layers.UniformLabelSmoother.Params()\n params.name = 'uls'\n params.num_classes = 5\n params.uncertainty = 0.1\n\n smooth_layer = layers.UniformLabelSmoother(params)\n target_labels = tf.constant([[0, 1, 2, 3, 3, 3, 4]], dtype=tf.int32)\n target_ids = tf.constant([[0, 0, 1, 2, 3, 3, 3]], dtype=tf.int32)\n target_paddings = tf.zeros(tf.shape(target_ids))\n output = smooth_layer.FPropDefaultTheta(target_paddings, target_labels,\n target_ids)\n tf.global_variables_initializer().run()\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_output = [[\n [0.89999998, 0.025 , 0.025 , 0.025 , 0.025 ],\n [0.025 , 0.89999998, 0.025 , 0.025 , 0.025 ],\n [0.025 , 0.025 , 0.89999998, 0.025 , 0.025 ],\n [0.025 , 0.025 , 0.025 , 0.89999998, 0.025 ],\n [0.025 , 0.025 , 0.025 , 0.89999998, 0.025 ],\n [0.025 , 0.025 , 0.025 , 0.89999998, 0.025 ],\n [0.025 , 0.025 , 0.025 , 0.025 , 0.89999998]\n ]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n output_v = output.eval()\n self.assertAllClose(expected_output, output_v, atol=1e-2, rtol=1e-2)\n self.assertAllClose(np.ones(output_v.shape[:-1]), output_v.sum(-1))\n\n def testUniformLabelSmootherLargerToken(self):\n with self.session(use_gpu=False):\n params = layers.UniformLabelSmoother.Params()\n params.name = 'uls'\n params.num_classes = 5\n params.uncertainty = 0.1\n params.uncertainty_larger = 0.2\n params.token_id_uncertainty_larger = 4\n\n smooth_layer = layers.UniformLabelSmoother(params)\n target_labels = tf.constant([[0, 1, 2, 3, 3, 3, 3]], dtype=tf.int32)\n target_ids = tf.constant([[0, 0, 1, 2, 4, 4, 4]], dtype=tf.int32)\n target_paddings = tf.zeros(tf.shape(target_ids))\n output = smooth_layer.FPropDefaultTheta(target_paddings, target_labels,\n target_ids)\n tf.global_variables_initializer().run()\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_output = [[\n [0.89999998, 0.025 , 0.025 , 0.025 , 0.025 ],\n [0.025 , 0.89999998, 0.025 , 0.025 , 0.025 ],\n [0.025 , 0.025 , 0.89999998, 0.025 , 0.025 ],\n [0.025 , 0.025 , 0.025 , 0.89999998, 0.025 ],\n [0.05 , 0.05 , 0.05 , 0.80000001, 0.05 ],\n [0.05 , 0.05 , 0.05 , 0.80000001, 0.05 ],\n [0.05 , 0.05 , 0.05 , 0.80000001, 0.05 ]\n ]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n output_v = output.eval()\n self.assertAllClose(expected_output, output_v, atol=1e-2, rtol=1e-2)\n self.assertAllClose(np.ones(output_v.shape[:-1]), output_v.sum(-1))\n\n\nclass WeightedSumLayerTest(test_utils.TestCase):\n\n def testWeightedSumLayer(self):\n with self.session(use_gpu=True) as sess:\n np.random.seed(505837249)\n depth = 4\n batch = 2\n n_sources = 3\n ctxs = [[[1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 4.0, 5.0]],\n [[3.0, 4.0, 5.0, 6.0], [6.0, 7.0, 8.0, 9.0]],\n [[4.0, 5.0, 6.0, 7.0], [7.0, 8.0, 1.0, 2.0]]]\n p = layers.WeightedSumLayer.Params()\n p.name = 'transparent_layer'\n p.num_sources = n_sources\n p.random_seed = 505837249\n merger = p.Instantiate()\n\n ctxs = [tf.expand_dims(i, 2) for i in ctxs]\n ctx = tf.squeeze(merger.FProp(merger.theta, ctxs), 2)\n tf.global_variables_initializer().run()\n actual_ctx = sess.run(ctx)\n\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_ctx = [[ 2.66666675, 3.66666675, 4.66666698, 5.66666698],\n [ 5.0, 6.0, 4.33333349, 5.33333349]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n self.assertEqual(actual_ctx.shape, (batch, depth))\n self.assertAllClose(expected_ctx, actual_ctx, rtol=1e-05, atol=1e-05)\n\n def testWeightedSumLayerGlobalWeightAndMinimalProb(self):\n with self.session(use_gpu=True) as sess:\n np.random.seed(505837249)\n depth = 4\n batch = 2\n n_sources = 3\n ctxs = [[[1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 4.0, 5.0]],\n [[3.0, 4.0, 5.0, 6.0], [6.0, 7.0, 8.0, 9.0]],\n [[4.0, 5.0, 6.0, 7.0], [7.0, 8.0, 1.0, 2.0]]]\n p = layers.WeightedSumLayer.Params()\n p.name = 'transparent_layer'\n p.num_sources = n_sources\n p.random_seed = 505837249\n p.minimal_prob = 0.01\n p.global_weight_scale = 10.0\n merger = p.Instantiate()\n\n ctxs = [tf.expand_dims(i, 2) for i in ctxs]\n ctx = tf.squeeze(merger.FProp(merger.theta, ctxs), 2)\n tf.global_variables_initializer().run()\n actual_ctx = sess.run(ctx)\n\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_ctx = [[ 2.66666675, 3.66666675, 4.66666698, 5.66666698],\n [ 5.0, 6.0, 4.33333349, 5.33333349]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n self.assertEqual(actual_ctx.shape, (batch, depth))\n self.assertAllClose(expected_ctx, actual_ctx, rtol=1e-05, atol=1e-05)\n\n\nclass GatedAverageLayerTest(test_utils.TestCase):\n\n def testGatedAverageLayer(self):\n with self.session(use_gpu=True) as sess:\n np.random.seed(505837249)\n depth = 4\n batch = 2\n num_inputs = 3\n\n inp_1 = np.asarray([[0.0, 0.0, 0.0, 0.0], [-1.0, -1.0, 1.0, 1.0]],\n dtype=np.float32)\n inp_2 = np.asarray([[1.0, 1.0, 1.0, 1.0], [-1.0, -1.0, 1.0, 1.0]],\n dtype=np.float32)\n inp_3 = np.asarray([[-1.0, -1.0, -1.0, -1.0], [-1.0, -1.0, 1.0, 1.0]],\n dtype=np.float32)\n p = layers.GatedAverageLayer.Params()\n p.name = 'gated_avg_layer'\n p.num_inputs = num_inputs\n p.num_nodes = depth\n p.random_seed = 505837249\n g_avg = p.Instantiate()\n\n avg = g_avg.FProp(g_avg.theta, [inp_1, inp_2, inp_3])\n tf.global_variables_initializer().run()\n actual_avg = sess.run(avg)\n\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_avg = [\n [ 0.13070658, 0.13070658, 0.13070658, 0.13070658],\n [ -1.0, -1.0, 1.0 , 1.0]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n self.assertEqual(actual_avg.shape, (batch, depth))\n self.assertAllClose(expected_avg, actual_avg, rtol=1e-05, atol=1e-05)\n\n\nclass LHUCLayerTest(test_utils.TestCase):\n\n def testLHUCLayer(self):\n with self.session(use_gpu=True) as sess:\n np.random.seed(505837249)\n depth = 4\n batch = 2\n\n inp = np.asarray([[1.0, 1.0, 1.0, 1.0], [-1.0, -1.0, -1.0, -1.0]],\n dtype=np.float32)\n p = layers.LHUCLayer.Params()\n p.name = 'lhuc_layer'\n p.input_dim = depth\n p.random_seed = 505837249\n lhuc = p.Instantiate()\n\n lhuc = lhuc.FProp(lhuc.theta, inp)\n tf.global_variables_initializer().run()\n actual_avg = sess.run(lhuc)\n\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_avg = [[1.0, 1.0, 1.0, 1.0], [-1.0, -1.0, -1.0, -1.0]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n self.assertEqual(actual_avg.shape, (batch, depth))\n self.assertAllClose(expected_avg, actual_avg, rtol=1e-05, atol=1e-05)\n\n\nclass ResidualAdapterLayerTest(test_utils.TestCase):\n\n def testResidualAdapterLayer(self):\n with self.session(use_gpu=True) as sess:\n np.random.seed(505837249)\n depth = 4\n batch = 2\n\n inp = np.asarray([[1.0, 1.0, 1.0, 1.0], [-1.0, -1.0, -1.0, -1.0]],\n dtype=np.float32)\n p = layers.ResidualAdapterLayer.Params()\n p.name = 'resadap_layer'\n p.input_dim = depth\n p.bottleneck_dim = 2\n p.random_seed = 505837249\n resadap = p.Instantiate()\n\n resadap = resadap.FProp(resadap.theta, inp)\n tf.global_variables_initializer().run()\n actual_avg = sess.run(resadap)\n\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_avg = [[1.0, 1.0, 1.0, 1.0], [-1.0, -1.0, -1.0, -1.0]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n self.assertEqual(actual_avg.shape, (batch, depth))\n self.assertAllClose(expected_avg, actual_avg, rtol=1e-05, atol=1e-05)\n\n\nclass GluLayerTest(test_utils.TestCase):\n\n def testGlu(self):\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(3980847392)\n inputs = tf.random_normal([5, 2, 3], seed=948387483)\n paddings = tf.zeros([5, 2])\n p = layers.GluLayer.Params()\n p.name = 'glu_layers'\n p.input_dim = 3\n glu_layer = layers.GluLayer(p)\n\n h = glu_layer.FPropDefaultTheta(inputs, paddings)\n tf.global_variables_initializer().run()\n actual_layer_output = sess.run(h)\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_output = [\n [[ -1.84272185e-01, -3.82728219e-01, 8.69752645e-01],\n [ 4.42533880e-01, 1.51665461e+00, 3.26201534e+00]],\n [[ -7.06624031e-01, -6.52632236e-01, 1.22156203e+00],\n [ 1.66484845e+00, 5.98078966e-01, 1.14039946e+00]],\n [[ 3.26439053e-01, 2.47359693e-01, -1.14889514e+00],\n [ 7.71084905e-01, 1.07083774e+00, 1.74589559e-01]],\n [[ 5.70576251e-01, 7.95466423e-01, -4.07778949e-01],\n [ -8.71581078e-01, -5.38501918e-01, -2.50373930e-01]],\n [[ -3.88817638e-01, 5.84501982e-01, -6.60797715e-01],\n [ -1.34579837e+00, -2.18637614e-03, 1.55258143e+00]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n print(np.array_repr(actual_layer_output))\n self.assertAllClose(actual_layer_output, expected_output)\n\n def testGluWithoutResidual(self):\n with self.session(use_gpu=True) as sess:\n tf.set_random_seed(3980847392)\n inputs = tf.random_normal([5, 2, 3], seed=948387483)\n paddings = tf.zeros([5, 2])\n p = layers.GluLayer.Params()\n p.name = 'glu_layers'\n p.input_dim = 3\n p.output_dim = 4\n p.apply_residual = False\n glu_layer = layers.GluLayer(p)\n\n h = glu_layer.FPropDefaultTheta(inputs, paddings)\n tf.global_variables_initializer().run()\n actual_layer_output = sess.run(h)\n # pylint: disable=bad-whitespace\n # pyformat: disable\n expected_output = [\n [[ 0.2498899 , 0. , 0.62683833, 0. ],\n [ 0.34115699, 0. , 0.38020864, 0. ]],\n [[ 0.3014423 , 0. , 0.59274423, 0. ],\n [ 0. , 0.35897657, 0.2908403 , 0.03678071]],\n [[ 0. , 0.78786391, 0. , 0.38839644],\n [ 0. , 0.44012907, 0. , 0.41553062]],\n [[ 0. , 0.61838603, 0. , 0.41521466],\n [ 0.34117079, 0. , 0.0372162 , 0. ]],\n [[ 0. , 0. , 0. , 0.28136203],\n [ 0.34413674, 0. , 0.30943182, 0. ]]]\n # pyformat: enable\n # pylint: enable=bad-whitespace\n print(np.array_repr(actual_layer_output))\n self.assertAllClose(actual_layer_output, expected_output)\n\n\nclass MultitaskAdapterLayerTest(test_utils.TestCase):\n\n def _MultitaskAdapterParams(self):\n return layers.MultitaskAdapterLayer.Params().Set(\n name='multi_adapter',\n input_dim=4,\n bottleneck_dim=2,\n num_tasks=3,\n random_seed=505837249)\n\n def testSingleStepFProp(self):\n with self.session(use_gpu=True) as sess:\n np.random.seed(1234567)\n # Inputs are of shape [1, batch, input_dim] (single time step)\n # Batch elements 0, 2, and 3 are identical, but 0 and 2 have the same\n # task ID where as 3 has a different task ID.\n inputs = tf.constant([[[0.5, 0.3, -0.2, 0.0], [0.0, 0.7, -1.0, 2.0],\n [0.5, 0.3, -0.2, 0.0], [0.5, 0.3, -0.2, 0.0]]],\n dtype=tf.float32)\n tasks = tf.constant([1, 0, 1, 0], dtype=tf.int32)\n p = self._MultitaskAdapterParams()\n adapter = p.Instantiate()\n output = adapter.FProp(adapter.theta, inputs, tasks)\n tf.global_variables_initializer().run()\n actual = sess.run(output)\n expected = [[[-0.674434, -0.331616, 0.066886, 0.388049],\n [0.262231, 0.667873, -0.92701, 2.246897],\n [-0.674434, -0.331616, 0.066886, 0.388049],\n [0.737031, 0.330693, -0.227962, 0.138892]]]\n self.assertEqual(actual.shape, (1, 4, 4))\n # Batch elements 0 and 2 are equal because they had the same input\n # and the same task ID.\n self.assertAllClose(actual[0][0], actual[0][2], rtol=1e-05, atol=1e-05)\n self.assertAllClose(expected, actual, rtol=1e-05, atol=1e-05)\n\n def testMultiStepFProp(self):\n with self.session(use_gpu=True) as sess:\n np.random.seed(1234567)\n # Inputs are same as above but of shape [time, batch, input_dim]\n inputs = tf.constant([[[0.5, 0.3, -0.2, 0.0], [0.0, 0.7, -1.0, 2.0]],\n [[0.5, 0.3, -0.2, 0.0], [0.5, 0.3, -0.2, 0.0]]],\n dtype=tf.float32)\n # tasks is of shape [batch] indicating one task for each sequence.\n tasks = tf.constant([1, 0], dtype=tf.int32)\n p = self._MultitaskAdapterParams()\n adapter = p.Instantiate()\n output = adapter.FProp(adapter.theta, inputs, tasks)\n tf.global_variables_initializer().run()\n actual = sess.run(output)\n # Output is same as above but with shape same as input.\n expected = [[[-0.674434, -0.331616, 0.066886, 0.388049],\n [0.262231, 0.667873, -0.92701, 2.246897]],\n [[-0.674434, -0.331616, 0.066886, 0.388049],\n [0.737031, 0.330693, -0.227962, 0.138892]]]\n self.assertEqual(actual.shape, (2, 2, 4))\n self.assertAllClose(expected, actual, rtol=1e-05, atol=1e-05)\n\n def testSpecifyTaskPerTimestepFProp(self):\n with self.session(use_gpu=True) as sess:\n np.random.seed(1234567)\n inputs = tf.constant([[[0.5, 0.3, -0.2, 0.0], [0.0, 0.7, -1.0, 2.0]],\n [[0.5, 0.3, -0.2, 0.0], [0.5, 0.3, -0.2, 0.0]]],\n dtype=tf.float32)\n # tasks are same as above but of shape [time, batch] indicating that\n # we should look up adapter params per timestep. In this example we\n # still have the task ID consistent across timesteps in order to\n # replicate the previous test's output.\n tasks = tf.constant([[1, 0], [1, 0]], dtype=tf.int32)\n p = self._MultitaskAdapterParams()\n adapter = p.Instantiate()\n output = adapter.FProp(adapter.theta, inputs, tasks)\n tf.global_variables_initializer().run()\n actual = sess.run(output)\n # Output is same as above.\n expected = [[[-0.674434, -0.331616, 0.066886, 0.388049],\n [0.262231, 0.667873, -0.92701, 2.246897]],\n [[-0.674434, -0.331616, 0.066886, 0.388049],\n [0.737031, 0.330693, -0.227962, 0.138892]]]\n self.assertEqual(actual.shape, (2, 2, 4))\n self.assertAllClose(expected, actual, rtol=1e-05, atol=1e-05)\n\n def testDifferentTaskPerTimestepFProp(self):\n with self.session(use_gpu=True) as sess:\n np.random.seed(1234567)\n inputs = tf.constant([[[0.5, 0.3, -0.2, 0.0], [0.0, 0.7, -1.0, 2.0]],\n [[0.5, 0.3, -0.2, 0.0], [0.5, 0.3, -0.2, 0.0]]],\n dtype=tf.float32)\n # tasks are again of shape [time, batch] but with different tasks\n # for each timestep.\n tasks = tf.constant([[1, 0], [2, 1]], dtype=tf.int32)\n p = self._MultitaskAdapterParams()\n adapter = p.Instantiate()\n output = adapter.FProp(adapter.theta, inputs, tasks)\n tf.global_variables_initializer().run()\n actual = sess.run(output)\n expected = [[[-0.674434, -0.331616, 0.066886, 0.388049],\n [0.262231, 0.667873, -0.92701, 2.246897]],\n [[0.181782, 0.928383, -0.307064, 0.560411],\n [-0.674434, -0.331616, 0.066886, 0.388049]]]\n self.assertEqual(actual.shape, (2, 2, 4))\n self.assertAllClose(expected, actual, rtol=1e-05, atol=1e-05)\n\n def testGradientChecker(self):\n with self.session(use_gpu=True) as sess:\n np.random.seed(1234567)\n inputs = tf.constant([[[0.5, 0.3, -0.2, 0.0], [0.0, 0.7, -1.0, 2.0]],\n [[0.5, 0.3, -0.2, 0.0], [0.5, 0.3, -0.2, 0.0]]],\n dtype=tf.float32)\n tasks = tf.constant([1, 0], dtype=tf.int32)\n p = self._MultitaskAdapterParams()\n adapter = p.Instantiate()\n output = adapter.FProp(adapter.theta, inputs, tasks)\n loss = tf.reduce_sum(output)\n tf.global_variables_initializer().run()\n all_vars = tf.trainable_variables()\n grads = tf.gradients(loss, all_vars)\n\n def DenseGrad(var, grad):\n if isinstance(grad, tf.Tensor):\n return grad\n elif isinstance(grad, tf.IndexedSlices):\n return tf.unsorted_segment_sum(grad.values, grad.indices,\n tf.shape(var)[0])\n\n dense_grads = [DenseGrad(x, y) for (x, y) in zip(all_vars, grads)]\n dense_grad_sums = [tf.reduce_sum(g) for g in dense_grads]\n grad_vs = sess.run(dense_grad_sums)\n self.assertAllClose([0., -0.239046, 12.765231, 16.0, 0.342786, -1.191779],\n grad_vs,\n rtol=1e-05,\n atol=1e-05)\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Lint as: python2, python3\n# -*- coding: utf-8 -*-\n# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for recurrent.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport lingvo.compat as tf\nfrom lingvo.core import base_layer\nfrom lingvo.core import py_utils\nfrom lingvo.core import recurrent\nfrom lingvo.core import test_utils\nimport numpy as np\nfrom six.moves import range\nfrom six.moves import zip\n\nfrom tensorflow.python.framework import function\n\n\ndef _ApplyPadding(padding, v_no_pad, v_pad):\n if padding is not None:\n padding = tf.cast(padding, v_no_pad.dtype)\n return (1 - padding) * v_no_pad + padding * v_pad\n return v_no_pad\n\n\ndef _ReferenceStaticUnroll(theta, state0, inputs, cell_fn):\n \"\"\"Statically unrolls a `cell_fn` wrt inputs as `recurrent.Recurrent()` does.\n\n This is not a complete implementation but should work reasonably for\n calls that do not have a custom cell_grad, extras or accumulators and\n can help check expectations.\n\n Args:\n theta: weights. A `.NestedMap`.\n state0: initial state. A `.NestedMap`.\n inputs: inputs. A `.NestedMap`. Tensors must have static shape.\n cell_fn: A python function, which computes::\n state1, extras = cell_fn(theta, state0, inputs[t, :])\n\n Returns:\n accumulate and final state.\n \"\"\"\n flat_inputs = inputs.Flatten()\n flat_state = state0.Flatten()\n step_count = flat_inputs[0].shape[0]\n acc_state = [[None] * step_count for t in flat_state]\n for i in range(step_count):\n flat_step_inputs = [t[i] for t in flat_inputs]\n step_inputs = inputs.Pack(flat_step_inputs)\n state1, unused_extras = cell_fn(theta, state0, step_inputs)\n for j, state_step in zip(range(len(acc_state[0])), state1.Flatten()):\n acc_state[j][i] = state_step\n state0 = state1\n return state0.Pack(acc_state), state1\n\n\ndef _Poly(theta, state, inputs):\n next_state = py_utils.NestedMap()\n next_state.value = state.value + inputs.coeff * state.x_power\n next_state.x_power = state.x_power * theta.x\n return next_state, py_utils.NestedMap()\n\n\nclass _IncrementAccumulator(base_layer.Accumulator):\n\n def DefaultValue(self):\n return tf.convert_to_tensor(0.0)\n\n def Update(self, increment_by):\n initial = self.GetValue()\n self.SetValue(initial + tf.convert_to_tensor(increment_by))\n\n\nclass _SampleAccumulatorLayer(base_layer.BaseLayer):\n\n def __init__(self, params):\n super(_SampleAccumulatorLayer, self).__init__(params)\n self.accumulator_name = 'sample_accumulator'\n self.RegisterAccumulator(self.accumulator_name, _IncrementAccumulator())\n\n\nclass RecurrentTest(test_utils.TestCase):\n\n def testBasic(self):\n\n with self.session() as sess:\n\n theta = py_utils.NestedMap()\n theta.x = tf.constant(2.0)\n state = py_utils.NestedMap()\n state.value = tf.constant(0.0)\n state.x_power = tf.constant(1.0)\n inputs = py_utils.NestedMap()\n inputs.coeff = tf.constant([1., 2., 3.])\n\n # x = 2\n # 1 + 2*x + 3*x^2\n ret = recurrent.Recurrent(theta, state, inputs, _Poly)\n\n acc, state = sess.run(ret)\n self.assertAllClose(acc.value, [1., 5., 17.])\n self.assertAllClose(acc.x_power, [2., 4., 8.])\n self.assertAllClose(state.value, 17.)\n self.assertAllClose(state.x_power, 8.)\n\n y = ret[1].value\n dx, d_coeff = tf.gradients(ys=[y], xs=[theta.x, inputs.coeff])\n dx_val, d_coeff_val = sess.run([dx, d_coeff])\n\n # 2 + 6*x\n self.assertAllClose(dx_val, 14.)\n self.assertAllClose(d_coeff_val, [1., 2., 4.])\n\n # acc = [1, 1+2x, 1+2x+3x^2]\n # sum(acc) = 3 + 4x + 3x^2\n acc = ret[0].value\n dx, d_coeff = tf.gradients(\n ys=[tf.reduce_sum(acc)], xs=[theta.x, inputs.coeff])\n dx_val, d_coeff_val = sess.run([dx, d_coeff])\n # 4 + 6*x\n self.assertAllClose(dx_val, 16.)\n self.assertAllClose(d_coeff_val, [3., 4., 4.])\n\n def testBasicWithAccumulator(self):\n\n with self.session() as sess:\n\n p = _SampleAccumulatorLayer.Params()\n p.name = 'sample'\n accum_layer = _SampleAccumulatorLayer(p)\n accum_obj = accum_layer.accumulators[accum_layer.accumulator_name]\n\n theta = py_utils.NestedMap()\n theta.x = tf.constant(2.0)\n state = py_utils.NestedMap()\n state.value = tf.constant(0.0)\n state.x_power = tf.constant(1.0)\n inputs = py_utils.NestedMap()\n inputs.coeff = tf.constant([1., 2., 3.])\n\n def _CellFn(theta, state, inputs):\n print('TEST ACCUM WITHIN CellFn = ', accum_obj.GetValue())\n accum_obj.Update(inputs.coeff)\n return _Poly(theta, state, inputs)\n\n # By doing one accumulate prior to recurrent, we ensure that incoming\n # recurrent state is preserved.\n accum_obj.Update(10.)\n\n # x = 2\n # 1 + 2*x + 3*x^2\n ret = recurrent.Recurrent(\n theta, state, inputs, _CellFn, accumulator_layer=accum_layer)\n\n # Verify bprop.\n y = ret[1].value\n dx, d_coeff = tf.gradients(ys=[y], xs=[theta.x, inputs.coeff])\n dx_val, d_coeff_val = sess.run([dx, d_coeff])\n\n # 2 + 6*x\n self.assertAllClose(dx_val, 14.)\n self.assertAllClose(d_coeff_val, [1., 2., 4.])\n\n # acc = [1, 1+2x, 1+2x+3x^2]\n # sum(acc) = 3 + 4x + 3x^2\n acc = ret[0].value\n dx, d_coeff = tf.gradients(\n ys=[tf.reduce_sum(acc)], xs=[theta.x, inputs.coeff])\n dx_val, d_coeff_val = sess.run([dx, d_coeff])\n # 4 + 6*x\n self.assertAllClose(dx_val, 16.)\n self.assertAllClose(d_coeff_val, [3., 4., 4.])\n\n # Verify fprop.\n (acc, state), accum_obj_value = sess.run((ret, accum_obj.GetValue()))\n\n # Verify that accumulators don't change fprop results.\n self.assertAllClose(acc.value, [1., 5., 17.])\n self.assertAllClose(acc.x_power, [2., 4., 8.])\n self.assertAllClose(state.value, 17.)\n self.assertAllClose(state.x_power, 8.)\n\n # Verify accumulator (should be 10 (initial increment) + 1 + 2 + 3).\n self.assertEqual(0, accum_obj._disable_count)\n self.assertAllClose([accum_obj_value], [16.0])\n\n def testTimeBasedStopFn(self):\n\n with self.session() as sess:\n\n def StopFn(t, unused_theta, unused_state):\n # This stops after 3 iterations.\n return t >= 3\n\n theta = py_utils.NestedMap()\n theta.x = tf.constant(2.0)\n state = py_utils.NestedMap()\n state.value = tf.constant(0.0)\n state.x_power = tf.constant(1.0)\n inputs = py_utils.NestedMap()\n inputs.coeff = tf.constant([1., 2., 3., 4.])\n\n # x = 2\n # 1 + 2*x + 3*x^2\n ret = recurrent.Recurrent(theta, state, inputs, _Poly, stop_fn=StopFn)\n\n acc, state = sess.run(ret)\n self.assertAllClose([1., 5., 17., 0.], acc.value)\n self.assertAllClose([2., 4., 8., 0.], acc.x_power)\n self.assertAllClose(17., state.value)\n self.assertAllClose(8., state.x_power)\n\n y = ret[1].value\n dx, d_coeff = tf.gradients(ys=[y], xs=[theta.x, inputs.coeff])\n dx_val, d_coeff_val = sess.run([dx, d_coeff])\n\n # 2 + 6*x\n self.assertAllClose(14., dx_val)\n self.assertAllClose([1., 2., 4., 0.], d_coeff_val)\n\n # acc = [1, 1+2x, 1+2x+3x^2]\n # sum(acc) = 3 + 4x + 3x^2\n acc = ret[0].value\n dx, d_coeff = tf.gradients(\n ys=[tf.reduce_sum(acc)], xs=[theta.x, inputs.coeff])\n dx_val, d_coeff_val = sess.run([dx, d_coeff])\n # 4 + 6*x\n self.assertAllClose(16., dx_val)\n self.assertAllClose([3., 4., 4., 0.], d_coeff_val)\n\n def testStateBasedStopFn(self):\n\n with self.session() as sess:\n\n def StopFn(unused_t, unused_theta, state):\n # This stops after 3 iterations.\n return state.value >= 15.\n\n theta = py_utils.NestedMap()\n theta.x = tf.constant(2.0)\n state = py_utils.NestedMap()\n state.value = tf.constant(0.0)\n state.x_power = tf.constant(1.0)\n inputs = py_utils.NestedMap()\n inputs.coeff = tf.constant([1., 2., 3., 4.])\n\n # x = 2\n # 1 + 2*x + 3*x^2\n ret = recurrent.Recurrent(theta, state, inputs, _Poly, stop_fn=StopFn)\n\n acc, state = sess.run(ret)\n self.assertAllClose([1., 5., 17., 0.], acc.value)\n self.assertAllClose([2., 4., 8., 0.], acc.x_power)\n self.assertAllClose(17., state.value)\n self.assertAllClose(8., state.x_power)\n\n y = ret[1].value\n dx, d_coeff = tf.gradients(ys=[y], xs=[theta.x, inputs.coeff])\n dx_val, d_coeff_val = sess.run([dx, d_coeff])\n\n # 2 + 6*x\n self.assertAllClose(14., dx_val)\n self.assertAllClose([1., 2., 4., 0.], d_coeff_val)\n\n # acc = [1, 1+2x, 1+2x+3x^2]\n # sum(acc) = 3 + 4x + 3x^2\n acc = ret[0].value\n dx, d_coeff = tf.gradients(\n ys=[tf.reduce_sum(acc)], xs=[theta.x, inputs.coeff])\n dx_val, d_coeff_val = sess.run([dx, d_coeff])\n # 4 + 6*x\n self.assertAllClose(16., dx_val)\n self.assertAllClose([3., 4., 4., 0.], d_coeff_val)\n\n def testStopFnNotTriggeredBeforeEOS(self):\n\n with self.session() as sess:\n\n def StopFn(t, unused_theta, unused_state):\n # The input sequence is only length 4, so this is never true.\n # However, the Recurrent call should still terminate after iteration 4.\n return t >= 5\n\n theta = py_utils.NestedMap()\n theta.x = tf.constant(2.0)\n state = py_utils.NestedMap()\n state.value = tf.constant(0.0)\n state.x_power = tf.constant(1.0)\n inputs = py_utils.NestedMap()\n inputs.coeff = tf.constant([1., 2., 3., 4.])\n\n # x = 2\n # 1 + 2*x + 3*x^2 + 4*x^3\n ret = recurrent.Recurrent(theta, state, inputs, _Poly, stop_fn=StopFn)\n\n acc, state = sess.run(ret)\n self.assertAllClose([1., 5., 17., 49.], acc.value)\n self.assertAllClose([2., 4., 8., 16.], acc.x_power)\n self.assertAllClose(49., state.value)\n self.assertAllClose(16., state.x_power)\n\n y = ret[1].value\n dx, d_coeff = tf.gradients(ys=[y], xs=[theta.x, inputs.coeff])\n dx_val, d_coeff_val = sess.run([dx, d_coeff])\n\n # 2 + 6*x + 12*x^2\n self.assertAllClose(62., dx_val)\n self.assertAllClose([1., 2., 4., 8.], d_coeff_val)\n\n # acc = [1, 1+2x, 1+2x+3x^2, 1+2x+3x^2+4x^3]\n # sum(acc) = 4 + 6x + 6x^2 + 4x^3\n acc = ret[0].value\n dx, d_coeff = tf.gradients(\n ys=[tf.reduce_sum(acc)], xs=[theta.x, inputs.coeff])\n dx_val, d_coeff_val = sess.run([dx, d_coeff])\n # 6 + 12*x + 12*x^2\n self.assertAllClose(78., dx_val)\n self.assertAllClose([4., 6., 8., 8.], d_coeff_val)\n\n def testCapture(self):\n\n with self.session() as sess:\n\n theta = py_utils.NestedMap()\n theta.x = tf.constant(2.0)\n state0 = py_utils.NestedMap()\n state0.value = tf.constant(0.0)\n inputs = py_utils.NestedMap()\n inputs.coeff = tf.constant([1., 2., 3.])\n captured = tf.constant(1.2, name='captured_const')\n\n def CellFn(theta, state, inputs):\n next_state = py_utils.NestedMap()\n # Captured is pulled from outside of the function and captured via the\n # internal Defun.\n next_state.value = state.value + inputs.coeff * captured * theta.x\n return next_state, py_utils.NestedMap()\n\n # Run static fprop reference implementation.\n ref_acc, ref_staten = _ReferenceStaticUnroll(theta, state0, inputs,\n CellFn)\n ref_acc_values, ref_staten_values = sess.run((ref_acc, ref_staten))\n print('Ref fprop: acc =', ref_acc, ', stateN =', ref_staten)\n print('Ref fprop values: acc =', ref_acc_values, ', stateN =',\n ref_staten_values)\n self.assertAllClose(ref_acc_values.value, [2.4, 7.2, 14.4])\n self.assertAllClose(ref_staten_values.value, 14.4)\n\n # Run real fprop implementation.\n real_acc, real_staten = recurrent.Recurrent(\n theta, state0, inputs, CellFn, allow_implicit_capture=True)\n real_acc_values, real_staten_values = sess.run((real_acc, real_staten))\n print('Real fprop: acc =', real_acc, ', stateN =', real_staten)\n print('Real fprop values: acc =', real_acc_values, ', stateN =',\n real_staten_values)\n self.assertAllClose(ref_acc_values.value, real_acc_values.value)\n self.assertAllClose(ref_staten_values.value, real_staten_values.value)\n\n # BProp real vs ref of stateN.\n ref_dx, ref_dcaptured = tf.gradients(\n ys=[ref_staten.value], xs=[theta.x, captured])\n ref_dx_values, ref_dcaptured_values = sess.run([ref_dx, ref_dcaptured])\n real_dx, real_dcaptured = tf.gradients(\n ys=[real_staten.value], xs=[theta.x, captured])\n real_dx_values, real_dcaptured_values = sess.run(\n [real_dx, real_dcaptured])\n print('Ref Dstate/[dx,dcaptured] =', ref_dx_values, ', ',\n ref_dcaptured_values)\n print('Real Dstate/[dx,dcaptured] =', real_dx_values, ', ',\n real_dcaptured_values)\n self.assertAllClose(ref_dx_values, 7.2)\n self.assertAllClose(ref_dcaptured_values, 12.0)\n self.assertAllClose(ref_dx_values, real_dx_values)\n self.assertAllClose(ref_dcaptured_values, real_dcaptured_values)\n\n def testCaptureDisallowed(self):\n\n with self.session() as unused_sess:\n\n theta = py_utils.NestedMap()\n theta.x = tf.constant(2.0)\n state0 = py_utils.NestedMap()\n state0.value = tf.constant(0.0)\n inputs = py_utils.NestedMap()\n inputs.coeff = tf.constant([1., 2., 3.])\n captured = tf.constant(1.2, name='captured_const')\n\n def CellFn(theta, state, inputs):\n next_state = py_utils.NestedMap()\n # Captured is pulled from outside of the function and captured via the\n # internal Defun.\n next_state.value = state.value + inputs.coeff * captured * theta.x\n return next_state, py_utils.NestedMap()\n\n # Run real fprop implementation.\n with self.assertRaisesRegexp(AssertionError,\n 'implicit capture is disabled'):\n unused_real_acc, unused_real_staten = recurrent.Recurrent(\n theta, state0, inputs, CellFn, allow_implicit_capture=False)\n\n def testStatefulCellFn(self):\n\n def Rand(theta, state, inputs):\n del theta\n next_state = py_utils.NestedMap()\n next_state.value = (\n state.value +\n inputs.coeff * tf.random_uniform(shape=[], dtype=state.value.dtype))\n return next_state, py_utils.NestedMap()\n\n with self.session():\n theta = py_utils.NestedMap()\n state = py_utils.NestedMap()\n state.value = tf.constant(0.0)\n inputs = py_utils.NestedMap()\n inputs.coeff = tf.constant([1., 2., 3.])\n\n with self.assertRaisesRegexp(ValueError, 'stateful.*random_uniform'):\n recurrent.Recurrent(theta, state, inputs, Rand, check_stateful_ops=True)\n\n def testNestedCellFn(self):\n \"\"\"Tests when cell_fn calls another function.\"\"\"\n\n @function.Defun(tf.float32)\n def RandWithCoeff(coeff):\n return coeff * tf.random_uniform(shape=[], dtype=coeff.dtype)\n\n def Rand(theta, state, inputs):\n del theta\n next_state = py_utils.NestedMap()\n next_state.value = state.value + RandWithCoeff(inputs.coeff)\n return next_state, py_utils.NestedMap()\n\n @function.Defun(tf.float32)\n def Coeff(coeff):\n return coeff * 2\n\n def Deterministic(theta, state, inputs):\n del theta\n next_state = py_utils.NestedMap()\n next_state.value = state.value + Coeff(inputs.coeff)\n return next_state, py_utils.NestedMap()\n\n with self.session():\n theta = py_utils.NestedMap()\n state = py_utils.NestedMap()\n state.value = tf.constant(0.0)\n inputs = py_utils.NestedMap()\n inputs.coeff = tf.constant([1., 2., 3.])\n\n recurrent.Recurrent(\n theta, state, inputs, Deterministic, check_stateful_ops=True)\n with self.assertRaisesRegexp(ValueError, 'stateful.*RandWithCoeff'):\n recurrent.Recurrent(theta, state, inputs, Rand, check_stateful_ops=True)\n\n def testSeqLenActual(self):\n for value, expected in [([[1.0], [1.0], [1.0]],\n [0, 3]), ([[1.0], [1.0], [0.0]],\n [2, 0]), ([[1.0], [0.0], [1.0]], [1, 1]),\n ([[1.0], [0.0], [0.0]],\n [1, 0]), ([[0.0], [1.0], [1.0]],\n [0, 2]), ([[0.0], [1.0], [0.0]], [0, 0]),\n ([[0.0], [0.0], [1.0]], [0, 1]), ([[0.0], [0.0],\n [0.0]], [0, 0])]:\n with self.session() as sess:\n inputs = py_utils.NestedMap()\n inputs.padding = tf.constant(value)\n\n slen_op = recurrent._SeqPaddingLength(inputs)\n slen, = sess.run([slen_op])\n self.assertEqual(expected, slen)\n\n @staticmethod\n def Rand(shape):\n return tf.random_uniform(shape, minval=-0.2, maxval=0.2, dtype=tf.float64)\n\n @staticmethod\n def Elman(theta, state0, inputs):\n h0, w, b, x = state0.h, theta.w, theta.b, inputs.x\n xw = py_utils.Matmul(tf.concat([x, h0], axis=1), w) # 1st part\n # 2nd part\n padding = inputs.get('padding', None)\n h1 = _ApplyPadding(padding, v_no_pad=tf.sigmoid(xw + b), v_pad=state0.h)\n\n state1 = py_utils.NestedMap(h=h1)\n if padding is not None:\n state1.padding = inputs.padding\n\n return (state1, py_utils.NestedMap(h=h1))\n\n @staticmethod\n def ElmanGrad(theta, state0, inputs, extras, dstate1):\n\n @function.Defun()\n def Grad(h0, w, b, x, padding, h1, dh1):\n del b\n dh1_orig = dh1\n dh1 = _ApplyPadding(padding, dh1, tf.zeros_like(dh1, dtype=dh1.dtype))\n\n # We hand-roll the gradient for the 2nd half of the cell as a demo.\n # h1 = tf.sigmoid(xw + b)\n # 𝛔'(x) = ((1 - 𝛔(x)) * 𝛔(x))\n dxwb = (dh1 * (1 - h1) * h1)\n dxw, db = dxwb, tf.reduce_sum(dxwb, axis=0)\n\n # Uses tf.gradient for the 1nd half of the cell as a demo.\n xw = py_utils.Matmul(tf.concat([x, h0], axis=1), w)\n dh0, dx, dw = tf.gradients(ys=[xw], xs=[h0, x, w], grad_ys=[dxw])\n\n dh0 = _ApplyPadding(padding, dh0, dh1_orig)\n\n return dh0, dx, dw, db\n\n dh0, dx, dw, db = Grad(state0.h, theta.w, theta.b, inputs.x,\n inputs.get('padding', 0), extras.h, dstate1.h)\n dstate0 = py_utils.NestedMap(h=dh0)\n dinputs = py_utils.NestedMap(x=dx)\n if 'padding' in dstate1:\n dstate0.padding = dstate1.padding\n dinputs.padding = dstate1.padding\n return (py_utils.NestedMap(w=dw, b=db), dstate0, dinputs, None)\n\n @staticmethod\n def ElmanOut(state1):\n return py_utils.NestedMap(x=state1.h, padding=state1.padding)\n\n @staticmethod\n def ElmanOutGrad(dout):\n return py_utils.NestedMap(h=dout.x, padding=dout.padding)\n\n def _testElmanHelper(self, seqlen, use_grad, stop_fn=None):\n with self.session() as sess:\n tf.set_random_seed(342462)\n\n batch = 3\n dims = 4\n theta = py_utils.NestedMap()\n theta.w = self.Rand([2 * dims, dims])\n theta.b = self.Rand([dims])\n state0 = py_utils.NestedMap()\n state0.h = self.Rand([batch, dims])\n inputs = py_utils.NestedMap()\n inputs.x = self.Rand([seqlen, batch, dims])\n\n # Static unrolled.\n s = state0\n out = []\n for i in range(seqlen):\n inp = py_utils.NestedMap()\n inp.x = inputs.x[i, :]\n s, _ = self.Elman(theta, s, inp)\n out += [s.h]\n if stop_fn and stop_fn(i + 1, theta, s):\n out += [tf.zeros_like(out[-1]) for _ in range(seqlen - i - 1)]\n break\n acc0, final0 = tf.stack(out), s.h\n loss0 = tf.reduce_sum(acc0) + tf.reduce_sum(final0)\n (dw0, db0, dh0,\n di0) = tf.gradients(loss0, [theta.w, theta.b, state0.h, inputs.x])\n\n # Uses the Recurrent() library.\n acc1, final1 = recurrent.Recurrent(\n theta=theta,\n state0=state0,\n inputs=inputs,\n cell_fn=self.Elman,\n cell_grad=self.ElmanGrad if use_grad else None,\n stop_fn=stop_fn)\n acc1, final1 = acc1.h, final1.h\n loss1 = tf.reduce_sum(acc1) + tf.reduce_sum(final1)\n (dw1, db1, dh1,\n di1) = tf.gradients(loss1, [theta.w, theta.b, state0.h, inputs.x])\n\n # Fetches a bunch of values and compare them.\n (acc0, acc1, final0, final1, dw0, dw1, db0, db1, dh0, dh1, di0,\n di1) = sess.run(\n [acc0, acc1, final0, final1, dw0, dw1, db0, db1, dh0, dh1, di0, di1])\n self.assertAllClose(acc0, acc1)\n self.assertAllClose(final0, final1)\n self.assertAllClose(dw0, dw1)\n self.assertAllClose(db0, db1)\n self.assertAllClose(dh0, dh1)\n self.assertAllClose(di0, di1)\n\n def testElman(self):\n self._testElmanHelper(1, False)\n self._testElmanHelper(1, True)\n self._testElmanHelper(7, False)\n self._testElmanHelper(7, True)\n\n def StopFn(t, unused_theta, unused_state):\n return t >= 4\n\n self._testElmanHelper(7, False, StopFn)\n self._testElmanHelper(7, True, StopFn)\n\n def testSetShape(self):\n dst = py_utils.NestedMap(\n a=tf.placeholder(tf.int32, shape=None),\n b=py_utils.NestedMap(\n b1=tf.placeholder(tf.int32, shape=None),\n b2=tf.placeholder(tf.int32, shape=None)))\n src = py_utils.NestedMap(\n a=tf.constant(0, shape=[2, 4], dtype=tf.int32),\n b=py_utils.NestedMap(\n b1=tf.constant(0, shape=[1, 3], dtype=tf.int32),\n b2=tf.constant(0, shape=[5, 8], dtype=tf.int32)))\n recurrent._SetShapes(dst, src)\n self.assertAllClose(\n [2, 4],\n py_utils.GetShape(dst.a, 2),\n )\n self.assertAllClose([1, 3], py_utils.GetShape(dst.b.b1, 2))\n self.assertAllClose([5, 8], py_utils.GetShape(dst.b.b2, 2))\n\n\nclass StackedRecurrentTest(RecurrentTest):\n\n @staticmethod\n def Poly(theta, state0, inputs):\n x = theta.x\n s = state0.s\n c = inputs.c\n return py_utils.NestedMap(s=s * x + c), py_utils.NestedMap()\n\n @staticmethod\n def Identity(theta, state0, inputs):\n del theta, state0\n return py_utils.NestedMap(s=inputs.s), py_utils.NestedMap()\n\n def testSimpleStacked(self):\n g = tf.Graph()\n with g.as_default():\n devices = ['/cpu:0'] * 3\n cell_fns = [self.Poly, self.Identity, self.Identity]\n cell_grads = [None] * 3\n cell_outs = [lambda x: x] * 3\n cell_out_grads = [lambda x: x] * 3\n w0 = tf.constant(2.)\n w1 = tf.constant(0.)\n w2 = tf.constant(0.)\n thetas = [\n py_utils.NestedMap(x=w0),\n py_utils.NestedMap(x=w1),\n py_utils.NestedMap(x=w2)\n ]\n init_states = [py_utils.NestedMap(s=tf.constant(0.))] * 3\n inputs = py_utils.NestedMap(\n c=tf.constant([1., 2., 1., 0.]),\n padding=tf.constant([0., 0., 0., 1.]))\n output, _ = recurrent.StackedRecurrent(\n devices=devices,\n cell_fns=cell_fns,\n cell_grads=cell_grads,\n cell_outs=cell_outs,\n cell_out_grads=cell_out_grads,\n thetas=thetas,\n init_states=init_states,\n inputs=inputs)\n dw0, dw1, dw2 = tf.gradients(tf.reduce_sum(output.s), [w0, w1, w2])\n\n with self.session(graph=g) as sess:\n (output, dw0, dw1, dw2) = sess.run([output.s, dw0, dw1, dw2])\n\n self.assertAllClose(output, [1., 4., 9., 0.])\n self.assertAllClose(dw2, 0.)\n self.assertAllClose(dw1, 0.)\n self.assertAllClose(dw0, 7.)\n\n def _BuildStackedRecurrentElman(self, seqlen, trailing_pad_len, batch, dims,\n layers):\n tf.set_random_seed(342462)\n np.random.seed(32540)\n\n seqlen += trailing_pad_len\n dtype = tf.float64\n\n def CreateTheta():\n return py_utils.NestedMap(\n w=tf.constant(\n np.random.uniform(0, 0.2, (2 * dims, dims)), dtype=dtype),\n b=tf.constant(np.random.uniform(0, 0.2, (dims,)), dtype=dtype))\n\n def CreateState0():\n return py_utils.NestedMap(\n h=tf.constant(np.random.uniform(0, 0.2, (batch, dims)), dtype=dtype),\n padding=tf.constant([[0]] * batch, dtype=dtype))\n\n devices = ['/cpu:0'] * layers\n cell_fns = [self.Elman] * layers\n cell_grads = [self.ElmanGrad] * layers\n cell_outs = [self.ElmanOut] * layers\n cell_out_grads = [self.ElmanOutGrad] * layers\n thetas = [CreateTheta() for _ in range(layers)]\n init_states = [CreateState0() for _ in range(layers)]\n padding = np.zeros((seqlen, batch, 1))\n padding[-trailing_pad_len:, :, :] = 1.\n padding[-trailing_pad_len - 3:-trailing_pad_len - 1, :, :] = 1.\n inputs = py_utils.NestedMap(\n x=tf.constant(\n np.random.uniform(0, 0.2, (seqlen, batch, dims)), dtype=dtype),\n padding=tf.constant(padding, dtype=dtype))\n output, _ = recurrent.StackedRecurrent(\n devices=devices,\n cell_fns=cell_fns,\n cell_grads=cell_grads,\n cell_outs=cell_outs,\n cell_out_grads=cell_out_grads,\n thetas=thetas,\n init_states=init_states,\n inputs=inputs)\n o = output.x\n if 'padding' in inputs:\n o *= (1 - inputs.padding)\n loss = tf.reduce_sum(tf.square(o))\n\n xs = recurrent.Flatten(thetas + [py_utils.NestedMap(x=inputs.x)])\n dxs = tf.gradients(ys=loss, xs=xs)\n\n # Reference implementation using Recurrent().\n ref = inputs\n for i in range(layers):\n ref = self.ElmanOut(\n recurrent.Recurrent(\n cell_fn=cell_fns[i],\n cell_grad=cell_grads[i],\n theta=thetas[i],\n state0=init_states[i],\n inputs=ref)[0])\n return ref.x, output.x, loss, xs, dxs\n\n def _LogDiff(self, x, y):\n tf.logging.info('max(abs(x - y)) = %s', np.max(np.abs(x - y)))\n\n def _CompareStackedElman(self, seqlen, batch, dims, layers):\n \"\"\"Tests that StackedRecurrent computest the same output as Recurrent().\"\"\"\n trailing_pad_len = 2\n g = tf.Graph()\n with g.as_default():\n ref, output, _, _, _ = self._BuildStackedRecurrentElman(\n seqlen, trailing_pad_len, batch, dims, layers)\n ref = ref[:-trailing_pad_len]\n output = output[:-trailing_pad_len]\n with self.session(graph=g) as sess:\n ref_val, out_val = sess.run([ref, output])\n self._LogDiff(ref_val, out_val)\n self.assertAllClose(ref_val, out_val)\n\n def testStackedElman_2(self):\n self._CompareStackedElman(4, 3, 8, 2)\n\n def testStackedElman_4(self):\n self._CompareStackedElman(8, 5, 8, 4)\n\n def testStackedElman_8(self):\n self._CompareStackedElman(11, 1, 4, 8)\n\n def _TestStackedElmanGradient(self, num, seqlen=7, batch=5):\n \"\"\"Tests a stacked Elman recurrent network with num layers.\"\"\"\n g = tf.Graph()\n with g.as_default():\n # Sequence length, batdh size, hidden dimension\n trailing_pad_len, dims, layers = 2, 8, num\n _, _, loss, xs, dxs = self._BuildStackedRecurrentElman(\n seqlen, trailing_pad_len, batch, dims, layers)\n\n # Fetches all gradients (dxs) in one session run and compare\n # them with their respective numerical gradient.\n with self.session(graph=g) as sess:\n s_dxs = sess.run(dxs)\n for (x, s_dx) in zip(xs, s_dxs):\n n_dx = test_utils.ComputeNumericGradient(sess, loss, x)\n self._LogDiff(n_dx, s_dx)\n self.assertAllClose(n_dx, s_dx)\n\n # Randomly pick a few (x, dx) pairs, and fetch dx via one sess.run\n # and compare with its numerical gradient.\n xs_dxs = list(zip(xs, dxs))\n np.random.shuffle(xs_dxs)\n with self.session(graph=g) as sess:\n for (x, dx) in xs_dxs[:4]:\n s_dx = sess.run(dx)\n n_dx = test_utils.ComputeNumericGradient(sess, loss, x)\n self._LogDiff(n_dx, s_dx)\n self.assertAllClose(n_dx, s_dx)\n\n def testStackedElmanGrad_1(self):\n self._TestStackedElmanGradient(1)\n\n def testStackedElmanGrad_2(self):\n self._TestStackedElmanGradient(2)\n\n def testStackedElmanGrad_4(self):\n self._TestStackedElmanGradient(4)\n\n def testStackedElmanGrad_8(self):\n self._TestStackedElmanGradient(8, seqlen=5, batch=3)\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
] |
[
[
"numpy.square",
"numpy.random.normal",
"numpy.array",
"numpy.array_repr",
"numpy.random.rand",
"numpy.asarray",
"numpy.zeros",
"numpy.random.seed",
"numpy.sum",
"numpy.ones",
"tensorflow.python.framework.ops.reset_default_graph",
"numpy.random.randint",
"numpy.argmax",
"numpy.sqrt",
"numpy.random.uniform",
"numpy.arange",
"numpy.linspace",
"numpy.var"
],
[
"numpy.zeros",
"numpy.random.seed",
"numpy.random.shuffle",
"tensorflow.python.framework.function.Defun",
"numpy.random.uniform",
"numpy.abs"
]
] |
guruprasaad123/all_dl_projects
|
[
"04c869f7f001ef94c467740260663d91a34815e0"
] |
[
"GTSRB/init.py"
] |
[
"# The German Traffic Sign Recognition Benchmark\n#\n# sample code for reading the traffic sign images and the\n# corresponding labels\n#\n# example:\n#\n# trainImages, trainLabels = readTrafficSigns('GTSRB/Training')\n# print len(trainLabels), len(trainImages)\n# plt.imshow(trainImages[42])\n# plt.show()\n#\n# have fun, Christian\n\n# import matplotlib.pyplot as plt\nfrom matplotlib import pyplot as plt\nimport csv\nimport os\nimport h5py\nimport numpy as np\nfrom skimage.io import imread\nfrom skimage.transform import resize\n\ndef pre_process_image(path,normalize=False,resize_img=False):\n\n # reading the image using path\n img = imread( path )\n\n if normalize == True:\n # normalize the pixel values\n img = img/255\n\n if resize_img == True:\n # resizing the image to (28,28,3)\n img = resize(img, output_shape=(32,32,3), mode='constant', anti_aliasing=True)\n\n # converting the type of pixel to float 32\n img = img.astype('float32')\n\n return img\n\n\ndef create_dataset( obj=dict({}) , name='data' ):\n\n filename = '{}.h5'.format(name)\n\n hf = h5py.File( filename , 'w' )\n\n for key in obj:\n hf.create_dataset( key , data=obj[key] )\n\n hf.close()\n\n# function for reading the images\n# arguments: path to the traffic sign data, for example './GTSRB/Training'\n# returns: list of images, list of corresponding labels\ndef readTrafficSigns(rootpath):\n '''Reads traffic sign data for German Traffic Sign Recognition Benchmark.\n\n Arguments: path to the traffic sign data, for example './GTSRB/Training'\n Returns: list of images, list of corresponding labels'''\n images = [] # images\n arr_images = np.array([\n [],\n [],\n [],\n []\n ]) # numpy array\n labels = [] # corresponding labels\n # loop over all 42 classes\n for c in range(0,43):\n prefix = rootpath + '/' + format(c, '05d') + '/' # subdirectory for class\n gtFile = open(prefix + 'GT-'+ format(c, '05d') + '.csv') # annotations file\n\n print('gtfile : ',gtFile)\n\n gtReader = csv.reader(gtFile, delimiter=';') # csv parser for annotations file\n # gtReader.next() # skip header\n next(gtReader)\n # loop over all images in current annotations file\n for row in gtReader:\n img = pre_process_image( prefix + row[0] , normalize=True , resize_img=True )\n # print('shape : ',img.shape)\n images.append( img ) # the 1th column is the filename\n # value = np.array( plt.imread(prefix + row[0]) )\n # print('value : shape ',value.shape)\n # np.append( arr_images , value , axis=0 )\n labels.append(row[7]) # the 8th column is the label\n gtFile.close()\n return images, labels\n\n\nroot_path = os.path.join('GTSRB_Final_Training_Images','GTSRB','Final_Training','Images')\n# root_path = 'GTSRB_Final_Training_Images/GTSRB/Final_Training/Images'\n\nimages , labels = readTrafficSigns(root_path)\n\narr_images = np.array(images)\n\n# arr_images.astype(np.float64)\n\nprint('Images : ', arr_images.dtype)\n\ntrain_obj = dict( { 'train_images' : arr_images , 'train_labels' : np.array( labels , dtype='S' ) } )\n\ncreate_dataset( train_obj , 'training_new' )\n"
] |
[
[
"numpy.array"
]
] |
sibeshkar/jiminy
|
[
"7754f86fb0f246e7d039ea0cbfd9950fcae4adfb"
] |
[
"jiminy/gym/envs/box2d/car_racing.py"
] |
[
"import sys, math\nimport numpy as np\n\nimport Box2D\nfrom Box2D.b2 import (edgeShape, circleShape, fixtureDef, polygonShape, revoluteJointDef, contactListener)\n\nimport jiminy.gym as gym\nfrom jiminy.gym import spaces\nfrom jiminy.gym.envs.box2d.car_dynamics import Car\nfrom jiminy.gym.utils import colorize, seeding\n\nimport pyglet\nfrom pyglet import gl\n\n# Easiest continuous control task to learn from pixels, a top-down racing environment.\n# Discreet control is reasonable in this environment as well, on/off discretisation is\n# fine.\n#\n# State consists of STATE_W x STATE_H pixels.\n#\n# Reward is -0.1 every frame and +1000/N for every track tile visited, where N is\n# the total number of tiles in track. For example, if you have finished in 732 frames,\n# your reward is 1000 - 0.1*732 = 926.8 points.\n#\n# Game is solved when agent consistently gets 900+ points. Track is random every episode.\n#\n# Episode finishes when all tiles are visited. Car also can go outside of PLAYFIELD, that\n# is far off the track, then it will get -100 and die.\n#\n# Some indicators shown at the bottom of the window and the state RGB buffer. From\n# left to right: true speed, four ABS sensors, steering wheel position, gyroscope.\n#\n# To play yourself (it's rather fast for humans), type:\n#\n# python gym/envs/box2d/car_racing.py\n#\n# Remember it's powerful rear-wheel drive car, don't press accelerator and turn at the\n# same time.\n#\n# Created by Oleg Klimov. Licensed on the same terms as the rest of OpenAI Gym.\n\nSTATE_W = 96 # less than Atari 160x192\nSTATE_H = 96\nVIDEO_W = 600\nVIDEO_H = 400\nWINDOW_W = 1200\nWINDOW_H = 1000\n\nSCALE = 6.0 # Track scale\nTRACK_RAD = 900/SCALE # Track is heavily morphed circle with this radius\nPLAYFIELD = 2000/SCALE # Game over boundary\nFPS = 50\nZOOM = 2.7 # Camera zoom\nZOOM_FOLLOW = True # Set to False for fixed view (don't use zoom)\n\n\nTRACK_DETAIL_STEP = 21/SCALE\nTRACK_TURN_RATE = 0.31\nTRACK_WIDTH = 40/SCALE\nBORDER = 8/SCALE\nBORDER_MIN_COUNT = 4\n\nROAD_COLOR = [0.4, 0.4, 0.4]\n\nclass FrictionDetector(contactListener):\n def __init__(self, env):\n contactListener.__init__(self)\n self.env = env\n def BeginContact(self, contact):\n self._contact(contact, True)\n def EndContact(self, contact):\n self._contact(contact, False)\n def _contact(self, contact, begin):\n tile = None\n obj = None\n u1 = contact.fixtureA.body.userData\n u2 = contact.fixtureB.body.userData\n if u1 and \"road_friction\" in u1.__dict__:\n tile = u1\n obj = u2\n if u2 and \"road_friction\" in u2.__dict__:\n tile = u2\n obj = u1\n if not tile: return\n\n tile.color[0] = ROAD_COLOR[0]\n tile.color[1] = ROAD_COLOR[1]\n tile.color[2] = ROAD_COLOR[2]\n if not obj or \"tiles\" not in obj.__dict__: return\n if begin:\n obj.tiles.add(tile)\n #print tile.road_friction, \"ADD\", len(obj.tiles)\n if not tile.road_visited:\n tile.road_visited = True\n self.env.reward += 1000.0/len(self.env.track)\n self.env.tile_visited_count += 1\n else:\n obj.tiles.remove(tile)\n #print tile.road_friction, \"DEL\", len(obj.tiles) -- should delete to zero when on grass (this works)\n\nclass CarRacing(gym.Env):\n metadata = {\n 'render.modes': ['human', 'rgb_array', 'state_pixels'],\n 'video.frames_per_second' : FPS\n }\n\n def __init__(self):\n self._seed()\n self.contactListener_keepref = FrictionDetector(self)\n self.world = Box2D.b2World((0,0), contactListener=self.contactListener_keepref)\n self.viewer = None\n self.invisible_state_window = None\n self.invisible_video_window = None\n self.road = None\n self.car = None\n self.reward = 0.0\n self.prev_reward = 0.0\n\n self.action_space = spaces.Box( np.array([-1,0,0]), np.array([+1,+1,+1])) # steer, gas, brake\n self.observation_space = spaces.Box(low=0, high=255, shape=(STATE_H, STATE_W, 3))\n\n def _seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def _destroy(self):\n if not self.road: return\n for t in self.road:\n self.world.DestroyBody(t)\n self.road = []\n self.car.destroy()\n\n def _create_track(self):\n CHECKPOINTS = 12\n\n # Create checkpoints\n checkpoints = []\n for c in range(CHECKPOINTS):\n alpha = 2*math.pi*c/CHECKPOINTS + self.np_random.uniform(0, 2*math.pi*1/CHECKPOINTS)\n rad = self.np_random.uniform(TRACK_RAD/3, TRACK_RAD)\n if c==0:\n alpha = 0\n rad = 1.5*TRACK_RAD\n if c==CHECKPOINTS-1:\n alpha = 2*math.pi*c/CHECKPOINTS\n self.start_alpha = 2*math.pi*(-0.5)/CHECKPOINTS\n rad = 1.5*TRACK_RAD\n checkpoints.append( (alpha, rad*math.cos(alpha), rad*math.sin(alpha)) )\n\n #print \"\\n\".join(str(h) for h in checkpoints)\n #self.road_poly = [ ( # uncomment this to see checkpoints\n # [ (tx,ty) for a,tx,ty in checkpoints ],\n # (0.7,0.7,0.9) ) ]\n self.road = []\n\n # Go from one checkpoint to another to create track\n x, y, beta = 1.5*TRACK_RAD, 0, 0\n dest_i = 0\n laps = 0\n track = []\n no_freeze = 2500\n visited_other_side = False\n while 1:\n alpha = math.atan2(y, x)\n if visited_other_side and alpha > 0:\n laps += 1\n visited_other_side = False\n if alpha < 0:\n visited_other_side = True\n alpha += 2*math.pi\n while True: # Find destination from checkpoints\n failed = True\n while True:\n dest_alpha, dest_x, dest_y = checkpoints[dest_i % len(checkpoints)]\n if alpha <= dest_alpha:\n failed = False\n break\n dest_i += 1\n if dest_i % len(checkpoints) == 0: break\n if not failed: break\n alpha -= 2*math.pi\n continue\n r1x = math.cos(beta)\n r1y = math.sin(beta)\n p1x = -r1y\n p1y = r1x\n dest_dx = dest_x - x # vector towards destination\n dest_dy = dest_y - y\n proj = r1x*dest_dx + r1y*dest_dy # destination vector projected on rad\n while beta - alpha > 1.5*math.pi: beta -= 2*math.pi\n while beta - alpha < -1.5*math.pi: beta += 2*math.pi\n prev_beta = beta\n proj *= SCALE\n if proj > 0.3: beta -= min(TRACK_TURN_RATE, abs(0.001*proj))\n if proj < -0.3: beta += min(TRACK_TURN_RATE, abs(0.001*proj))\n x += p1x*TRACK_DETAIL_STEP\n y += p1y*TRACK_DETAIL_STEP\n track.append( (alpha,prev_beta*0.5 + beta*0.5,x,y) )\n if laps > 4: break\n no_freeze -= 1\n if no_freeze==0: break\n #print \"\\n\".join([str(t) for t in enumerate(track)])\n\n # Find closed loop range i1..i2, first loop should be ignored, second is OK\n i1, i2 = -1, -1\n i = len(track)\n while True:\n i -= 1\n if i==0: return False # Failed\n pass_through_start = track[i][0] > self.start_alpha and track[i-1][0] <= self.start_alpha\n if pass_through_start and i2==-1:\n i2 = i\n elif pass_through_start and i1==-1:\n i1 = i\n break\n print(\"Track generation: %i..%i -> %i-tiles track\" % (i1, i2, i2-i1))\n assert i1!=-1\n assert i2!=-1\n\n track = track[i1:i2-1]\n\n first_beta = track[0][1]\n first_perp_x = math.cos(first_beta)\n first_perp_y = math.sin(first_beta)\n # Length of perpendicular jump to put together head and tail\n well_glued_together = np.sqrt(\n np.square( first_perp_x*(track[0][2] - track[-1][2]) ) +\n np.square( first_perp_y*(track[0][3] - track[-1][3]) ))\n if well_glued_together > TRACK_DETAIL_STEP:\n return False\n\n # Red-white border on hard turns\n border = [False]*len(track)\n for i in range(len(track)):\n good = True\n oneside = 0\n for neg in range(BORDER_MIN_COUNT):\n beta1 = track[i-neg-0][1]\n beta2 = track[i-neg-1][1]\n good &= abs(beta1 - beta2) > TRACK_TURN_RATE*0.2\n oneside += np.sign(beta1 - beta2)\n good &= abs(oneside) == BORDER_MIN_COUNT\n border[i] = good\n for i in range(len(track)):\n for neg in range(BORDER_MIN_COUNT):\n border[i-neg] |= border[i]\n\n # Create tiles\n for i in range(len(track)):\n alpha1, beta1, x1, y1 = track[i]\n alpha2, beta2, x2, y2 = track[i-1]\n road1_l = (x1 - TRACK_WIDTH*math.cos(beta1), y1 - TRACK_WIDTH*math.sin(beta1))\n road1_r = (x1 + TRACK_WIDTH*math.cos(beta1), y1 + TRACK_WIDTH*math.sin(beta1))\n road2_l = (x2 - TRACK_WIDTH*math.cos(beta2), y2 - TRACK_WIDTH*math.sin(beta2))\n road2_r = (x2 + TRACK_WIDTH*math.cos(beta2), y2 + TRACK_WIDTH*math.sin(beta2))\n t = self.world.CreateStaticBody( fixtures = fixtureDef(\n shape=polygonShape(vertices=[road1_l, road1_r, road2_r, road2_l])\n ))\n t.userData = t\n c = 0.01*(i%3)\n t.color = [ROAD_COLOR[0] + c, ROAD_COLOR[1] + c, ROAD_COLOR[2] + c]\n t.road_visited = False\n t.road_friction = 1.0\n t.fixtures[0].sensor = True\n self.road_poly.append(( [road1_l, road1_r, road2_r, road2_l], t.color ))\n self.road.append(t)\n if border[i]:\n side = np.sign(beta2 - beta1)\n b1_l = (x1 + side* TRACK_WIDTH *math.cos(beta1), y1 + side* TRACK_WIDTH *math.sin(beta1))\n b1_r = (x1 + side*(TRACK_WIDTH+BORDER)*math.cos(beta1), y1 + side*(TRACK_WIDTH+BORDER)*math.sin(beta1))\n b2_l = (x2 + side* TRACK_WIDTH *math.cos(beta2), y2 + side* TRACK_WIDTH *math.sin(beta2))\n b2_r = (x2 + side*(TRACK_WIDTH+BORDER)*math.cos(beta2), y2 + side*(TRACK_WIDTH+BORDER)*math.sin(beta2))\n self.road_poly.append(( [b1_l, b1_r, b2_r, b2_l], (1,1,1) if i%2==0 else (1,0,0) ))\n self.track = track\n return True\n\n def _reset(self):\n self._destroy()\n self.reward = 0.0\n self.prev_reward = 0.0\n self.tile_visited_count = 0\n self.t = 0.0\n self.road_poly = []\n self.human_render = False\n\n while True:\n success = self._create_track()\n if success: break\n print(\"retry to generate track (normal if there are not many of this messages)\")\n self.car = Car(self.world, *self.track[0][1:4])\n\n return self._step(None)[0]\n\n def _step(self, action):\n if action is not None:\n self.car.steer(-action[0])\n self.car.gas(action[1])\n self.car.brake(action[2])\n\n self.car.step(1.0/FPS)\n self.world.Step(1.0/FPS, 6*30, 2*30)\n self.t += 1.0/FPS\n\n self.state = self._render(\"state_pixels\")\n\n step_reward = 0\n done = False\n if action is not None: # First step without action, called from reset()\n self.reward -= 0.1\n # We actually don't want to count fuel spent, we want car to be faster.\n #self.reward -= 10 * self.car.fuel_spent / ENGINE_POWER\n self.car.fuel_spent = 0.0\n step_reward = self.reward - self.prev_reward\n self.prev_reward = self.reward\n if self.tile_visited_count==len(self.track):\n done = True\n x, y = self.car.hull.position\n if abs(x) > PLAYFIELD or abs(y) > PLAYFIELD:\n done = True\n step_reward = -100\n\n return self.state, step_reward, done, {}\n\n def _render(self, mode='human', close=False):\n if close:\n if self.viewer is not None:\n self.viewer.close()\n self.viewer = None\n return\n\n if self.viewer is None:\n from jiminy.gym.envs.classic_control import rendering\n self.viewer = rendering.Viewer(WINDOW_W, WINDOW_H)\n self.score_label = pyglet.text.Label('0000', font_size=36,\n x=20, y=WINDOW_H*2.5/40.00, anchor_x='left', anchor_y='center',\n color=(255,255,255,255))\n self.transform = rendering.Transform()\n\n if \"t\" not in self.__dict__: return # reset() not called yet\n\n zoom = 0.1*SCALE*max(1-self.t, 0) + ZOOM*SCALE*min(self.t, 1) # Animate zoom first second\n zoom_state = ZOOM*SCALE*STATE_W/WINDOW_W\n zoom_video = ZOOM*SCALE*VIDEO_W/WINDOW_W\n scroll_x = self.car.hull.position[0]\n scroll_y = self.car.hull.position[1]\n angle = -self.car.hull.angle\n vel = self.car.hull.linearVelocity\n if np.linalg.norm(vel) > 0.5:\n angle = math.atan2(vel[0], vel[1])\n self.transform.set_scale(zoom, zoom)\n self.transform.set_translation(\n WINDOW_W/2 - (scroll_x*zoom*math.cos(angle) - scroll_y*zoom*math.sin(angle)),\n WINDOW_H/4 - (scroll_x*zoom*math.sin(angle) + scroll_y*zoom*math.cos(angle)) )\n self.transform.set_rotation(angle)\n\n self.car.draw(self.viewer, mode!=\"state_pixels\")\n\n arr = None\n win = self.viewer.window\n if mode != 'state_pixels':\n win.switch_to()\n win.dispatch_events()\n if mode==\"rgb_array\" or mode==\"state_pixels\":\n win.clear()\n t = self.transform\n if mode=='rgb_array':\n VP_W = VIDEO_W\n VP_H = VIDEO_H\n else:\n VP_W = STATE_W\n VP_H = STATE_H\n gl.glViewport(0, 0, VP_W, VP_H)\n t.enable()\n self._render_road()\n for geom in self.viewer.onetime_geoms:\n geom.render()\n t.disable()\n self._render_indicators(WINDOW_W, WINDOW_H) # TODO: find why 2x needed, wtf\n image_data = pyglet.image.get_buffer_manager().get_color_buffer().get_image_data()\n arr = np.fromstring(image_data.data, dtype=np.uint8, sep='')\n arr = arr.reshape(VP_H, VP_W, 4)\n arr = arr[::-1, :, 0:3]\n\n if mode==\"rgb_array\" and not self.human_render: # agent can call or not call env.render() itself when recording video.\n win.flip()\n\n if mode=='human':\n self.human_render = True\n win.clear()\n t = self.transform\n gl.glViewport(0, 0, WINDOW_W, WINDOW_H)\n t.enable()\n self._render_road()\n for geom in self.viewer.onetime_geoms:\n geom.render()\n t.disable()\n self._render_indicators(WINDOW_W, WINDOW_H)\n win.flip()\n\n self.viewer.onetime_geoms = []\n return arr\n\n def _render_road(self):\n gl.glBegin(gl.GL_QUADS)\n gl.glColor4f(0.4, 0.8, 0.4, 1.0)\n gl.glVertex3f(-PLAYFIELD, +PLAYFIELD, 0)\n gl.glVertex3f(+PLAYFIELD, +PLAYFIELD, 0)\n gl.glVertex3f(+PLAYFIELD, -PLAYFIELD, 0)\n gl.glVertex3f(-PLAYFIELD, -PLAYFIELD, 0)\n gl.glColor4f(0.4, 0.9, 0.4, 1.0)\n k = PLAYFIELD/20.0\n for x in range(-20, 20, 2):\n for y in range(-20, 20, 2):\n gl.glVertex3f(k*x + k, k*y + 0, 0)\n gl.glVertex3f(k*x + 0, k*y + 0, 0)\n gl.glVertex3f(k*x + 0, k*y + k, 0)\n gl.glVertex3f(k*x + k, k*y + k, 0)\n for poly, color in self.road_poly:\n gl.glColor4f(color[0], color[1], color[2], 1)\n for p in poly:\n gl.glVertex3f(p[0], p[1], 0)\n gl.glEnd()\n\n def _render_indicators(self, W, H):\n gl.glBegin(gl.GL_QUADS)\n s = W/40.0\n h = H/40.0\n gl.glColor4f(0,0,0,1)\n gl.glVertex3f(W, 0, 0)\n gl.glVertex3f(W, 5*h, 0)\n gl.glVertex3f(0, 5*h, 0)\n gl.glVertex3f(0, 0, 0)\n def vertical_ind(place, val, color):\n gl.glColor4f(color[0], color[1], color[2], 1)\n gl.glVertex3f((place+0)*s, h + h*val, 0)\n gl.glVertex3f((place+1)*s, h + h*val, 0)\n gl.glVertex3f((place+1)*s, h, 0)\n gl.glVertex3f((place+0)*s, h, 0)\n def horiz_ind(place, val, color):\n gl.glColor4f(color[0], color[1], color[2], 1)\n gl.glVertex3f((place+0)*s, 4*h , 0)\n gl.glVertex3f((place+val)*s, 4*h, 0)\n gl.glVertex3f((place+val)*s, 2*h, 0)\n gl.glVertex3f((place+0)*s, 2*h, 0)\n true_speed = np.sqrt(np.square(self.car.hull.linearVelocity[0]) + np.square(self.car.hull.linearVelocity[1]))\n vertical_ind(5, 0.02*true_speed, (1,1,1))\n vertical_ind(7, 0.01*self.car.wheels[0].omega, (0.0,0,1)) # ABS sensors\n vertical_ind(8, 0.01*self.car.wheels[1].omega, (0.0,0,1))\n vertical_ind(9, 0.01*self.car.wheels[2].omega, (0.2,0,1))\n vertical_ind(10,0.01*self.car.wheels[3].omega, (0.2,0,1))\n horiz_ind(20, -10.0*self.car.wheels[0].joint.angle, (0,1,0))\n horiz_ind(30, -0.8*self.car.hull.angularVelocity, (1,0,0))\n gl.glEnd()\n self.score_label.text = \"%04i\" % self.reward\n self.score_label.draw()\n\n\nif __name__==\"__main__\":\n from pyglet.window import key\n a = np.array( [0.0, 0.0, 0.0] )\n def key_press(k, mod):\n global restart\n if k==0xff0d: restart = True\n if k==key.LEFT: a[0] = -1.0\n if k==key.RIGHT: a[0] = +1.0\n if k==key.UP: a[1] = +1.0\n if k==key.DOWN: a[2] = +0.8 # set 1.0 for wheels to block to zero rotation\n def key_release(k, mod):\n if k==key.LEFT and a[0]==-1.0: a[0] = 0\n if k==key.RIGHT and a[0]==+1.0: a[0] = 0\n if k==key.UP: a[1] = 0\n if k==key.DOWN: a[2] = 0\n env = CarRacing()\n env.render()\n record_video = False\n if record_video:\n env.monitor.start('/tmp/video-test', force=True)\n env.viewer.window.on_key_press = key_press\n env.viewer.window.on_key_release = key_release\n while True:\n env.reset()\n total_reward = 0.0\n steps = 0\n restart = False\n while True:\n s, r, done, info = env.step(a)\n total_reward += r\n if steps % 200 == 0 or done:\n print(\"\\naction \" + str([\"{:+0.2f}\".format(x) for x in a]))\n print(\"step {} total_reward {:+0.2f}\".format(steps, total_reward))\n #import matplotlib.pyplot as plt\n #plt.imshow(s)\n #plt.savefig(\"test.jpeg\")\n steps += 1\n if not record_video: # Faster, but you can as well call env.render() every time to play full window.\n env.render()\n if done or restart: break\n env.close()\n"
] |
[
[
"numpy.square",
"numpy.array",
"numpy.linalg.norm",
"numpy.sign",
"numpy.fromstring"
]
] |
LoopTilingBenchmark/benchmark
|
[
"52a3d2e70216552a498fd91de02a2fa9cb62122c"
] |
[
"ppo/baselines/common/tests/test_doc_examples.py"
] |
[
"import pytest\ntry:\n import mujoco_py\n _mujoco_present = True\nexcept BaseException:\n mujoco_py = None\n _mujoco_present = False\n\n\n@pytest.mark.skipif(\n not _mujoco_present,\n reason='error loading mujoco - either mujoco / mujoco key not present, or LD_LIBRARY_PATH is not pointing to mujoco library'\n)\ndef test_lstm_example():\n import tensorflow as tf\n from ppo.baselines.common import policies, models, cmd_util\n from ppo.baselines.common.vec_env.dummy_vec_env import DummyVecEnv\n\n # create vectorized environment\n venv = DummyVecEnv([lambda: cmd_util.make_mujoco_env('Reacher-v2', seed=0)])\n\n with tf.Session() as sess:\n # build policy based on lstm network with 128 units\n policy = policies.build_policy(venv, models.lstm(128))(nbatch=1, nsteps=1)\n\n # initialize tensorflow variables\n sess.run(tf.global_variables_initializer())\n\n # prepare environment variables\n ob = venv.reset()\n state = policy.initial_state\n done = [False]\n step_counter = 0\n\n # run a single episode until the end (i.e. until done)\n while True:\n action, _, state, _ = policy.step(ob, S=state, M=done)\n ob, reward, done, _ = venv.step(action)\n step_counter += 1\n if done:\n break\n\n\n assert step_counter > 5\n"
] |
[
[
"tensorflow.Session",
"tensorflow.global_variables_initializer"
]
] |
chenzhihan2020/bert
|
[
"52883d912d1a626d9462a0c2d974761ae5b159e1"
] |
[
"run_squad_final.py"
] |
[
"# coding=utf-8\r\n# Copyright 2018 The Google AI Language Team Authors.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"Run BERT on SQuAD 1.1 and SQuAD 2.0.\"\"\"\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport collections\r\nimport json\r\nimport math\r\nimport os\r\nimport random\r\nimport modeling\r\nimport optimization\r\nimport tokenization\r\nimport six\r\nimport tensorflow as tf\r\nimport io\r\n\r\nflags = tf.flags\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\r\nFLAGS = flags.FLAGS\r\n\r\n## Required parameters\r\nflags.DEFINE_string(\r\n \"bert_config_file\", None,\r\n \"The config json file corresponding to the pre-trained BERT model. \"\r\n \"This specifies the model architecture.\")\r\n\r\nflags.DEFINE_string(\"vocab_file\", None,\r\n \"The vocabulary file that the BERT model was trained on.\")\r\n\r\nflags.DEFINE_string(\r\n \"output_dir\", None,\r\n \"The output directory where the model checkpoints will be written.\")\r\n\r\n## Other parameters\r\nflags.DEFINE_string(\"train_file\", None,\r\n \"SQuAD json for training. E.g., train-v1.1.json\")\r\n\r\nflags.DEFINE_string(\r\n \"predict_file\", None,\r\n \"SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json\")\r\n\r\nflags.DEFINE_string(\r\n \"init_checkpoint\", None,\r\n \"Initial checkpoint (usually from a pre-trained BERT model).\")\r\n\r\nflags.DEFINE_bool(\r\n \"do_lower_case\", True,\r\n \"Whether to lower case the input text. Should be True for uncased \"\r\n \"models and False for cased models.\")\r\n\r\nflags.DEFINE_integer(\r\n \"max_seq_length\", 384,\r\n \"The maximum total input sequence length after WordPiece tokenization. \"\r\n \"Sequences longer than this will be truncated, and sequences shorter \"\r\n \"than this will be padded.\")\r\n\r\nflags.DEFINE_integer(\r\n \"doc_stride\", 128,\r\n \"When splitting up a long document into chunks, how much stride to \"\r\n \"take between chunks.\")\r\n\r\nflags.DEFINE_integer(\r\n \"max_query_length\", 64,\r\n \"The maximum number of tokens for the question. Questions longer than \"\r\n \"this will be truncated to this length.\")\r\n\r\nflags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\")\r\n\r\nflags.DEFINE_bool(\"do_predict\", False, \"Whether to run eval on the dev set.\")\r\n\r\nflags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\")\r\n\r\nflags.DEFINE_integer(\"predict_batch_size\", 8,\r\n \"Total batch size for predictions.\")\r\n\r\nflags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\")\r\n\r\nflags.DEFINE_float(\"num_train_epochs\", 3.0,\r\n \"Total number of training epochs to perform.\")\r\n\r\nflags.DEFINE_float(\r\n \"warmup_proportion\", 0.1,\r\n \"Proportion of training to perform linear learning rate warmup for. \"\r\n \"E.g., 0.1 = 10% of training.\")\r\n\r\nflags.DEFINE_integer(\"save_checkpoints_steps\", 1000,\r\n \"How often to save the model checkpoint.\")\r\n\r\nflags.DEFINE_integer(\"iterations_per_loop\", 1000,\r\n \"How many steps to make in each estimator call.\")\r\n\r\nflags.DEFINE_integer(\r\n \"n_best_size\", 20,\r\n \"The total number of n-best predictions to generate in the \"\r\n \"nbest_predictions.json output file.\")\r\n\r\nflags.DEFINE_integer(\r\n \"max_answer_length\", 30,\r\n \"The maximum length of an answer that can be generated. This is needed \"\r\n \"because the start and end predictions are not conditioned on one another.\")\r\n\r\nflags.DEFINE_bool(\"use_tpu\", False, \"Whether to use TPU or GPU/CPU.\")\r\n\r\ntf.flags.DEFINE_string(\r\n \"tpu_name\", None,\r\n \"The Cloud TPU to use for training. This should be either the name \"\r\n \"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 \"\r\n \"url.\")\r\n\r\ntf.flags.DEFINE_string(\r\n \"tpu_zone\", None,\r\n \"[Optional] GCE zone where the Cloud TPU is located in. If not \"\r\n \"specified, we will attempt to automatically detect the GCE project from \"\r\n \"metadata.\")\r\n\r\ntf.flags.DEFINE_string(\r\n \"gcp_project\", None,\r\n \"[Optional] Project name for the Cloud TPU-enabled project. If not \"\r\n \"specified, we will attempt to automatically detect the GCE project from \"\r\n \"metadata.\")\r\n\r\ntf.flags.DEFINE_string(\"master\", None, \"[Optional] TensorFlow master URL.\")\r\n\r\nflags.DEFINE_integer(\r\n \"num_tpu_cores\", 8,\r\n \"Only used if `use_tpu` is True. Total number of TPU cores to use.\")\r\n\r\nflags.DEFINE_bool(\r\n \"verbose_logging\", False,\r\n \"If true, all of the warnings related to data processing will be printed. \"\r\n \"A number of warnings are expected for a normal SQuAD evaluation.\")\r\n\r\nflags.DEFINE_bool(\r\n \"version_2_with_negative\", False,\r\n \"If true, the SQuAD examples contain some that do not have an answer.\")\r\n\r\nflags.DEFINE_float(\r\n \"null_score_diff_threshold\", 0.0,\r\n \"If null_score - best_non_null is greater than the threshold predict null.\")\r\n\r\n\r\nclass SquadExample(object):\r\n \"\"\"A single training/test example for simple sequence classification.\r\n\r\n For examples without an answer, the start and end position are -1.\r\n \"\"\"\r\n\r\n def __init__(self,\r\n qas_id,\r\n question_text,\r\n doc_tokens,\r\n orig_answer_text=None,\r\n start_position=None,\r\n end_position=None,\r\n is_impossible=False):\r\n self.qas_id = qas_id\r\n self.question_text = question_text\r\n self.doc_tokens = doc_tokens\r\n## squadexample has multiple answers\r\n self.orig_answer_text = orig_answer_text\r\n self.start_position = start_position\r\n self.end_position = end_position\r\n## above become list\r\n self.is_impossible = is_impossible\r\n\r\n def __str__(self):\r\n return self.__repr__()\r\n\r\n def __repr__(self):\r\n s = \"\"\r\n s += \"qas_id: %s\" % (tokenization.printable_text(self.qas_id))\r\n s += \", question_text: %s\" % (\r\n tokenization.printable_text(self.question_text))\r\n s += \", doc_tokens: [%s]\" % (\" \".join(self.doc_tokens))\r\n if self.start_position:\r\n s += \", start_position: %d\" % (self.start_position)\r\n if self.start_position:\r\n s += \", end_position: %d\" % (self.end_position)\r\n if self.start_position:\r\n s += \", is_impossible: %r\" % (self.is_impossible)\r\n return s\r\n\r\n\r\nclass InputFeatures(object):\r\n \"\"\"A single set of features of data.\"\"\"\r\n\r\n def __init__(self,\r\n unique_id,\r\n example_index,\r\n doc_span_index,\r\n tokens,\r\n token_to_orig_map,\r\n token_is_max_context,\r\n input_ids,\r\n input_mask,\r\n segment_ids,\r\n start_position=None,\r\n end_position=None,\r\n is_impossible=None):\r\n self.unique_id = unique_id \r\n self.example_index = example_index\r\n self.doc_span_index = doc_span_index\r\n self.tokens = tokens\r\n self.token_to_orig_map = token_to_orig_map\r\n self.token_is_max_context = token_is_max_context\r\n self.input_ids = input_ids\r\n self.input_mask = input_mask\r\n self.segment_ids = segment_ids\r\n self.start_position = start_position\r\n self.end_position = end_position\r\n self.is_impossible = is_impossible\r\n##find answer index in document\r\ndef answer_index_in_document(answer_list, document):\r\n\r\n indexs=[]\r\n doc=document.lower()\r\n for answer_string_in_doc in answer_list: \r\n index = doc.find(answer_string_in_doc.lower())\r\n \r\n while(index!=-1):\r\n indexs.append((answer_string_in_doc.lower(),index))\r\n index = doc.find(answer_string_in_doc.lower(),index+1)\r\n return indexs\r\n##\r\n\r\n\r\ndef read_squad_examples(input_file, is_training):\r\n \"\"\"Read a SQuAD json file into a list of SquadExample.\"\"\"\r\n with io.open(input_file, \"r\",encoding='utf8') as reader:\r\n input_data = json.load(reader)[\"data\"]\r\n\r\n def is_whitespace(c):\r\n if c == \" \" or c == \"\\t\" or c == \"\\r\" or c == \"\\n\" or ord(c) == 0x202F:\r\n return True\r\n return False\r\n\r\n examples = []\r\n #i_num_cnt = 0\r\n for entry in input_data:\r\n '''\r\n i_num_cnt += 1\r\n if (i_num_cnt > 10):\r\n break;\r\n '''\r\n for i_num,paragraph in enumerate(entry[\"paragraphs\"]):\r\n\r\n paragraph_text = paragraph[\"context\"]#[0:2000]\r\n\r\n doc_tokens = []\r\n char_to_word_offset = []\r\n prev_is_whitespace = True\r\n for c in paragraph_text:\r\n if is_whitespace(c):\r\n prev_is_whitespace = True\r\n else:\r\n if prev_is_whitespace:\r\n doc_tokens.append(c)\r\n else:\r\n doc_tokens[-1] += c\r\n prev_is_whitespace = False\r\n char_to_word_offset.append(len(doc_tokens) - 1)\r\n #print(char_to_word_offset)\r\n\r\n for qa in paragraph[\"qas\"]:\r\n qas_id = qa[\"id\"]\r\n question_text = qa[\"question\"]\r\n start_position = []\r\n end_position = []\r\n orig_answer_text = []\r\n is_impossible = False\r\n if is_training:\r\n\r\n if FLAGS.version_2_with_negative:\r\n is_impossible = qa[\"is_impossible\"]\r\n## if (len(qa[\"answers\"]) != 1) and (not is_impossible):\r\n## raise ValueError(\r\n## \"For training, each question should have exactly 1 answer.\")\r\n if not is_impossible:\r\n## read answer list\r\n answers= qa[\"answers\"]\r\n indexs=answer_index_in_document(answers,paragraph_text)\r\n if not len(indexs):\r\n tf.logging.warning(\"Could not find answer for %s \\n\",qa['id'])\r\n for index in indexs: \r\n orig_answer_text.append(index[0])\r\n answer_offset = index[1]\r\n answer_length = len(index[0])\r\n start_position.append(char_to_word_offset[answer_offset])\r\n if(answer_offset + answer_length - 1>len(char_to_word_offset)-1):\r\n print(qa['id'])\r\n print('\\n')\r\n print(index[1])\r\n print(index[0])\r\n print(answer_length)\r\n print(len(char_to_word_offset))\r\n print('\\n')\r\n print(paragraph_text)\r\n end_position.append(char_to_word_offset[answer_offset + answer_length - \r\n 1])\r\n##\r\n # Only add answers where the text can be exactly recovered from the\r\n # document. If this CAN'T happen it's likely due to weird Unicode\r\n # stuff so we will just skip the example.\r\n #\r\n # Note that this means for training mode, every example is NOT\r\n # guaranteed to be preserved.\r\n actual_text = \" \".join(\r\n doc_tokens[char_to_word_offset[answer_offset]:(char_to_word_offset[answer_offset + answer_length - \r\n 1] + 1)])\r\n cleaned_answer_text = \" \".join(\r\n tokenization.whitespace_tokenize(index[0]))\r\n## not checking things above \r\n if actual_text.lower().find(cleaned_answer_text) == -1:\r\n tf.logging.warning(\"Could not find answer: '%s' vs. '%s'\",\r\n actual_text, cleaned_answer_text)\r\n continue\r\n \r\n## else:\r\n## start_position = -1\r\n## end_position = -1\r\n## orig_answer_text = \"\"\r\n \r\n example = SquadExample(\r\n qas_id=qas_id,\r\n question_text=question_text,\r\n doc_tokens=doc_tokens,\r\n orig_answer_text=orig_answer_text,\r\n start_position=start_position,\r\n end_position=end_position,\r\n is_impossible=is_impossible)\r\n examples.append(example)\r\n##\r\n print(\"total example:\")\r\n print(len(examples))\r\n print(\"\\n\")\r\n##\r\n return examples\r\n\r\n\r\ndef convert_examples_to_features(examples, tokenizer, max_seq_length,\r\n doc_stride, max_query_length, is_training,\r\n output_fn):\r\n \"\"\"Loads a data file into a list of `InputBatch`s.\"\"\"\r\n\r\n unique_id = 1000000000\r\n example_num=0\r\n for (example_index, example) in enumerate(examples):\r\n##\r\n example_num+=1\r\n if(example_num % 100==0):\r\n print(\"processing example %d\",example_num)\r\n print('\\n')\r\n##\r\n query_tokens = tokenizer.tokenize(example.question_text)\r\n\r\n if len(query_tokens) > max_query_length:\r\n query_tokens = query_tokens[0:max_query_length]\r\n\r\n tok_to_orig_index = []\r\n orig_to_tok_index = []\r\n all_doc_tokens = []\r\n for (i, token) in enumerate(example.doc_tokens):\r\n orig_to_tok_index.append(len(all_doc_tokens))\r\n sub_tokens = tokenizer.tokenize(token)\r\n for sub_token in sub_tokens:\r\n tok_to_orig_index.append(i)\r\n all_doc_tokens.append(sub_token)\r\n\r\n tok_start_position = []\r\n tok_end_position = []\r\n if is_training and example.is_impossible:\r\n tok_start_position = -1\r\n tok_end_position = -1\r\n if is_training and not example.is_impossible:\r\n## convert char_index to token_index \r\n for i in range(len(example.start_position)):\r\n i_tok_start_position=orig_to_tok_index[example.start_position[i]]\r\n if example.end_position[i] < len(example.doc_tokens) - 1:\r\n i_tok_end_position= orig_to_tok_index[example.end_position[i] + 1] - 1\r\n else:\r\n i_tok_end_position= len(all_doc_tokens) - 1\r\n (i_tok_start_position, i_tok_end_position) = _improve_answer_span(\r\n all_doc_tokens, i_tok_start_position, i_tok_end_position, tokenizer,\r\n example.orig_answer_text[i])\r\n tok_start_position.append(i_tok_start_position)\r\n tok_end_position.append(i_tok_end_position)\r\n##\r\n # The -3 accounts for [CLS], [SEP] and [SEP]\r\n max_tokens_for_doc = max_seq_length - len(query_tokens) - 3\r\n\r\n # We can have documents that are longer than the maximum sequence length.\r\n # To deal with this we do a sliding window approach, where we take chunks\r\n # of the up to our max length with a stride of `doc_stride`.\r\n _DocSpan = collections.namedtuple( # pylint: disable=invalid-name\r\n \"DocSpan\", [\"start\", \"length\"])\r\n doc_spans = []\r\n start_offset = 0\r\n while start_offset < len(all_doc_tokens):\r\n length = len(all_doc_tokens) - start_offset\r\n if length > max_tokens_for_doc:\r\n length = max_tokens_for_doc\r\n doc_spans.append(_DocSpan(start=start_offset, length=length))\r\n if start_offset + length == len(all_doc_tokens):\r\n break\r\n start_offset += min(length, doc_stride)\r\n \r\n #连接文章和问题 [CLS]+ query + [SEP] + context + [SEP],问题放在前面\r\n for (doc_span_index, doc_span) in enumerate(doc_spans):\r\n tokens = []\r\n token_to_orig_map = {}\r\n token_is_max_context = {}\r\n segment_ids = []\r\n tokens.append(\"[CLS]\")\r\n segment_ids.append(0)\r\n for token in query_tokens:\r\n tokens.append(token)\r\n segment_ids.append(0)\r\n tokens.append(\"[SEP]\")\r\n segment_ids.append(0)\r\n\r\n for i in range(doc_span.length):\r\n split_token_index = doc_span.start + i\r\n token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]\r\n\r\n is_max_context = _check_is_max_context(doc_spans, doc_span_index,\r\n split_token_index)\r\n token_is_max_context[len(tokens)] = is_max_context\r\n tokens.append(all_doc_tokens[split_token_index])\r\n segment_ids.append(1)\r\n tokens.append(\"[SEP]\")\r\n segment_ids.append(1)\r\n\r\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\r\n\r\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\r\n # tokens are attended to.\r\n input_mask = [1] * len(input_ids)\r\n\r\n # Zero-pad up to the sequence length.\r\n while len(input_ids) < max_seq_length:\r\n input_ids.append(0)\r\n input_mask.append(0)\r\n segment_ids.append(0)\r\n\r\n assert len(input_ids) == max_seq_length\r\n assert len(input_mask) == max_seq_length\r\n assert len(segment_ids) == max_seq_length\r\n\r\n start_position = None\r\n end_position = None\r\n if is_training and not example.is_impossible:\r\n # For training, if our document chunk does not contain an annotation\r\n # we throw it out, since there is nothing to predict.\r\n doc_start = doc_span.start\r\n doc_end = doc_span.start + doc_span.length - 1\r\n out_of_span = True\r\n##find out whether a span contain any of answers\r\n start_position=[]\r\n end_position=[]\r\n for i in range(len(tok_start_position)): \r\n if (tok_start_position[i] >= doc_start and\r\n tok_end_position[i] <= doc_end):\r\n out_of_span=False\r\n doc_offset = len(query_tokens) + 2\r\n start_position.append(tok_start_position[i] - doc_start + doc_offset)\r\n end_position.append(tok_end_position[i] - doc_start + doc_offset)\r\n break\r\n##\r\n if out_of_span:\r\n continue\r\n start_position = [0]\r\n end_position = [0]\r\n \r\n## else:\r\n## doc_offset = len(query_tokens) + 2\r\n## start_position = tok_start_position - doc_start + doc_offset\r\n## end_position = tok_end_position - doc_start + doc_offset\r\n \r\n if is_training and example.is_impossible:\r\n start_position = 0\r\n end_position = 0\r\n '''\r\n if example_index < 20:\r\n tf.logging.info(\"*** Example ***\")\r\n tf.logging.info(\"unique_id: %s\" % (unique_id))\r\n tf.logging.info(\"example_index: %s\" % (example_index))\r\n tf.logging.info(\"doc_span_index: %s\" % (doc_span_index))\r\n tf.logging.info(\"tokens: %s\" % \" \".join(\r\n [tokenization.printable_text(x) for x in tokens]))\r\n tf.logging.info(\"token_to_orig_map: %s\" % \" \".join(\r\n [\"%d:%d\" % (x, y) for (x, y) in six.iteritems(token_to_orig_map)]))\r\n tf.logging.info(\"token_is_max_context: %s\" % \" \".join([\r\n \"%d:%s\" % (x, y) for (x, y) in six.iteritems(token_is_max_context)\r\n ]))\r\n tf.logging.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\r\n tf.logging.info(\r\n \"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\r\n tf.logging.info(\r\n \"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\r\n if is_training and example.is_impossible:\r\n tf.logging.info(\"impossible example\")\r\n if is_training and not example.is_impossible:\r\n answer_text = \" \".join(tokens[start_position:(end_position + 1)])\r\n tf.logging.info(\"start_position: %d\" % (start_position))\r\n tf.logging.info(\"end_position: %d\" % (end_position))\r\n tf.logging.info(\r\n \"answer: %s\" % (tokenization.printable_text(answer_text)))\r\n '''\r\n feature = InputFeatures(\r\n unique_id=unique_id,\r\n example_index=example_index,\r\n doc_span_index=doc_span_index,\r\n tokens=tokens,\r\n token_to_orig_map=token_to_orig_map,\r\n token_is_max_context=token_is_max_context,\r\n input_ids=input_ids,\r\n input_mask=input_mask,\r\n segment_ids=segment_ids,\r\n start_position=start_position,\r\n end_position=end_position,\r\n is_impossible=example.is_impossible)\r\n\r\n # Run callback\r\n output_fn(feature)\r\n \r\n unique_id += 1\r\n print(\"input_feature done.\")\r\n\r\ndef _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,\r\n orig_answer_text):\r\n \"\"\"Returns tokenized answer spans that better match the annotated answer.\"\"\"\r\n\r\n # The SQuAD annotations are character based. We first project them to\r\n # whitespace-tokenized words. But then after WordPiece tokenization, we can\r\n # often find a \"better match\". For example:\r\n #\r\n # Question: What year was John Smith born?\r\n # Context: The leader was John Smith (1895-1943).\r\n # Answer: 1895\r\n #\r\n # The original whitespace-tokenized answer will be \"(1895-1943).\". However\r\n # after tokenization, our tokens will be \"( 1895 - 1943 ) .\". So we can match\r\n # the exact answer, 1895.\r\n #\r\n # However, this is not always possible. Consider the following:\r\n #\r\n # Question: What country is the top exporter of electornics?\r\n # Context: The Japanese electronics industry is the lagest in the world.\r\n # Answer: Japan\r\n #\r\n # In this case, the annotator chose \"Japan\" as a character sub-span of\r\n # the word \"Japanese\". Since our WordPiece tokenizer does not split\r\n # \"Japanese\", we just use \"Japanese\" as the annotation. This is fairly rare\r\n # in SQuAD, but does happen.\r\n tok_answer_text = \" \".join(tokenizer.tokenize(orig_answer_text))\r\n\r\n for new_start in range(input_start, input_end + 1):\r\n for new_end in range(input_end, new_start - 1, -1):\r\n text_span = \" \".join(doc_tokens[new_start:(new_end + 1)])\r\n if text_span == tok_answer_text:\r\n return (new_start, new_end)\r\n\r\n return (input_start, input_end)\r\n\r\n\r\ndef _check_is_max_context(doc_spans, cur_span_index, position):\r\n \"\"\"Check if this is the 'max context' doc span for the token.\"\"\"\r\n\r\n # Because of the sliding window approach taken to scoring documents, a single\r\n # token can appear in multiple documents. E.g.\r\n # Doc: the man went to the store and bought a gallon of milk\r\n # Span A: the man went to the\r\n # Span B: to the store and bought\r\n # Span C: and bought a gallon of\r\n # ...\r\n #\r\n # Now the word 'bought' will have two scores from spans B and C. We only\r\n # want to consider the score with \"maximum context\", which we define as\r\n # the *minimum* of its left and right context (the *sum* of left and\r\n # right context will always be the same, of course).\r\n #\r\n # In the example the maximum context for 'bought' would be span C since\r\n # it has 1 left context and 3 right context, while span B has 4 left context\r\n # and 0 right context.\r\n best_score = None\r\n best_span_index = None\r\n for (span_index, doc_span) in enumerate(doc_spans):\r\n end = doc_span.start + doc_span.length - 1\r\n if position < doc_span.start:\r\n continue\r\n if position > end:\r\n continue\r\n num_left_context = position - doc_span.start\r\n num_right_context = end - position\r\n score = min(num_left_context, num_right_context) + 0.01 * doc_span.length\r\n if best_score is None or score > best_score:\r\n best_score = score\r\n best_span_index = span_index\r\n\r\n return cur_span_index == best_span_index\r\n\r\n\r\ndef create_model(bert_config, is_training, input_ids, input_mask, segment_ids,\r\n use_one_hot_embeddings):\r\n \"\"\"Creates a classification model.\"\"\"\r\n model = modeling.BertModel(\r\n config=bert_config,\r\n is_training=is_training,\r\n input_ids=input_ids,\r\n input_mask=input_mask,\r\n token_type_ids=segment_ids,\r\n use_one_hot_embeddings=use_one_hot_embeddings)\r\n\r\n final_hidden = model.get_sequence_output()\r\n\r\n final_hidden_shape = modeling.get_shape_list(final_hidden, expected_rank=3)\r\n batch_size = final_hidden_shape[0]\r\n seq_length = final_hidden_shape[1]\r\n hidden_size = final_hidden_shape[2]\r\n\r\n output_weights = tf.get_variable(\r\n \"cls/squad/output_weights\", [2, hidden_size],\r\n initializer=tf.truncated_normal_initializer(stddev=0.02))\r\n\r\n output_bias = tf.get_variable(\r\n \"cls/squad/output_bias\", [2], initializer=tf.zeros_initializer())\r\n\r\n final_hidden_matrix = tf.reshape(final_hidden,\r\n [batch_size * seq_length, hidden_size])\r\n logits = tf.matmul(final_hidden_matrix, output_weights, transpose_b=True)\r\n logits = tf.nn.bias_add(logits, output_bias)\r\n\r\n logits = tf.reshape(logits, [batch_size, seq_length, 2])\r\n logits = tf.transpose(logits, [2, 0, 1])\r\n\r\n unstacked_logits = tf.unstack(logits, axis=0)\r\n\r\n (start_logits, end_logits) = (unstacked_logits[0], unstacked_logits[1])\r\n\r\n return (start_logits, end_logits)\r\n\r\n\r\ndef model_fn_builder(bert_config, init_checkpoint, learning_rate,\r\n num_train_steps, num_warmup_steps, use_tpu,\r\n use_one_hot_embeddings):\r\n \"\"\"Returns `model_fn` closure for TPUEstimator.\"\"\"\r\n\r\n def model_fn(features, labels, mode, params): # pylint: disable=unused-argument\r\n \"\"\"The `model_fn` for TPUEstimator.\"\"\"\r\n\r\n tf.logging.info(\"*** Features ***\")\r\n for name in sorted(features.keys()):\r\n tf.logging.info(\" name = %s, shape = %s\" % (name, features[name].shape))\r\n\r\n unique_ids = features[\"unique_ids\"]\r\n input_ids = features[\"input_ids\"]\r\n input_mask = features[\"input_mask\"]\r\n segment_ids = features[\"segment_ids\"]\r\n\r\n is_training = (mode == tf.estimator.ModeKeys.TRAIN)\r\n\r\n (start_logits, end_logits) = create_model(\r\n bert_config=bert_config,\r\n is_training=is_training,\r\n input_ids=input_ids,\r\n input_mask=input_mask,\r\n segment_ids=segment_ids,\r\n use_one_hot_embeddings=use_one_hot_embeddings)\r\n\r\n tvars = tf.trainable_variables()\r\n\r\n initialized_variable_names = {}\r\n scaffold_fn = None\r\n if init_checkpoint:\r\n (assignment_map, initialized_variable_names\r\n ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)\r\n if use_tpu:\r\n\r\n def tpu_scaffold():\r\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\r\n return tf.train.Scaffold()\r\n\r\n scaffold_fn = tpu_scaffold\r\n else:\r\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\r\n\r\n tf.logging.info(\"**** Trainable Variables ****\")\r\n for var in tvars:\r\n init_string = \"\"\r\n if var.name in initialized_variable_names:\r\n init_string = \", *INIT_FROM_CKPT*\"\r\n tf.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape,\r\n init_string)\r\n\r\n output_spec = None\r\n if mode == tf.estimator.ModeKeys.TRAIN:\r\n seq_length = modeling.get_shape_list(input_ids)[1]\r\n\r\n def compute_loss(logits, positions):\r\n one_hot_positions = tf.one_hot(\r\n positions, depth=seq_length, dtype=tf.float32)\r\n log_probs = tf.nn.softmax(logits, axis=-1)\r\n loss = -tf.reduce_mean(tf.log(\r\n tf.reduce_sum(one_hot_positions * log_probs, axis=-1)))\r\n return loss\r\n\r\n start_positions = features[\"start_positions\"]\r\n end_positions = features[\"end_positions\"]\r\n\r\n start_loss = compute_loss(start_logits, start_positions)\r\n end_loss = compute_loss(end_logits, end_positions)\r\n\r\n total_loss = (start_loss + end_loss) / 2.0\r\n\r\n train_op = optimization.create_optimizer(\r\n total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)\r\n\r\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\r\n mode=mode,\r\n loss=total_loss,\r\n train_op=train_op,\r\n scaffold_fn=scaffold_fn)\r\n elif mode == tf.estimator.ModeKeys.PREDICT:\r\n predictions = {\r\n \"unique_ids\": unique_ids,\r\n \"start_logits\": start_logits,\r\n \"end_logits\": end_logits,\r\n }\r\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\r\n mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)\r\n else:\r\n raise ValueError(\r\n \"Only TRAIN and PREDICT modes are supported: %s\" % (mode))\r\n\r\n return output_spec\r\n\r\n return model_fn\r\n\r\n\r\ndef input_fn_builder(input_file, seq_length, is_training, drop_remainder):\r\n \"\"\"Creates an `input_fn` closure to be passed to TPUEstimator.\"\"\"\r\n\r\n name_to_features = {\r\n \"unique_ids\": tf.FixedLenFeature([], tf.int64),\r\n \"input_ids\": tf.FixedLenFeature([seq_length], tf.int64),\r\n \"input_mask\": tf.FixedLenFeature([seq_length], tf.int64),\r\n \"segment_ids\": tf.FixedLenFeature([seq_length], tf.int64),\r\n }\r\n\r\n if is_training:\r\n name_to_features[\"start_positions\"] = tf.FixedLenFeature([], tf.int64)\r\n name_to_features[\"end_positions\"] = tf.FixedLenFeature([], tf.int64)\r\n\r\n def _decode_record(record, name_to_features):\r\n \"\"\"Decodes a record to a TensorFlow example.\"\"\"\r\n example = tf.parse_single_example(record, name_to_features)\r\n\r\n # tf.Example only supports tf.int64, but the TPU only supports tf.int32.\r\n # So cast all int64 to int32.\r\n for name in list(example.keys()):\r\n t = example[name]\r\n if t.dtype == tf.int64:\r\n t = tf.to_int32(t)\r\n example[name] = t\r\n\r\n return example\r\n\r\n def input_fn(params):\r\n \"\"\"The actual input function.\"\"\"\r\n batch_size = params[\"batch_size\"]\r\n\r\n # For training, we want a lot of parallel reading and shuffling.\r\n # For eval, we want no shuffling and parallel reading doesn't matter.\r\n d = tf.data.TFRecordDataset(input_file)\r\n if is_training:\r\n d = d.repeat()\r\n d = d.shuffle(buffer_size=100)\r\n\r\n d = d.apply(\r\n tf.contrib.data.map_and_batch(\r\n lambda record: _decode_record(record, name_to_features),\r\n batch_size=batch_size,\r\n drop_remainder=drop_remainder))\r\n\r\n return d\r\n\r\n return input_fn\r\n\r\n\r\nRawResult = collections.namedtuple(\"RawResult\",\r\n [\"unique_id\", \"start_logits\", \"end_logits\"])\r\n\r\n\r\ndef write_predictions(all_examples, all_features, all_results, n_best_size,\r\n max_answer_length, do_lower_case, output_prediction_file,\r\n output_nbest_file, output_null_log_odds_file):\r\n \"\"\"Write final predictions to the json file and log-odds of null if needed.\"\"\"\r\n tf.logging.info(\"Writing predictions to: %s\" % (output_prediction_file))\r\n tf.logging.info(\"Writing nbest to: %s\" % (output_nbest_file))\r\n\r\n example_index_to_features = collections.defaultdict(list)\r\n for feature in all_features:\r\n example_index_to_features[feature.example_index].append(feature)\r\n\r\n unique_id_to_result = {}\r\n for result in all_results:\r\n unique_id_to_result[result.unique_id] = result\r\n\r\n _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name\r\n \"PrelimPrediction\",\r\n [\"feature_index\", \"start_index\", \"end_index\", \"start_logit\", \"end_logit\"])\r\n\r\n all_predictions = collections.OrderedDict()\r\n all_nbest_json = collections.OrderedDict()\r\n scores_diff_json = collections.OrderedDict()\r\n\r\n for (example_index, example) in enumerate(all_examples):\r\n features = example_index_to_features[example_index]\r\n\r\n prelim_predictions = []\r\n # keep track of the minimum score of null start+end of position 0\r\n score_null = 1000000 # large and positive\r\n min_null_feature_index = 0 # the paragraph slice with min mull score\r\n null_start_logit = 0 # the start logit at the slice with min null score\r\n null_end_logit = 0 # the end logit at the slice with min null score\r\n for (feature_index, feature) in enumerate(features):\r\n result = unique_id_to_result[feature.unique_id]\r\n start_indexes = _get_best_indexes(result.start_logits, n_best_size)\r\n end_indexes = _get_best_indexes(result.end_logits, n_best_size)\r\n # if we could have irrelevant answers, get the min score of irrelevant\r\n if FLAGS.version_2_with_negative:\r\n feature_null_score = result.start_logits[0] + result.end_logits[0]\r\n if feature_null_score < score_null:\r\n score_null = feature_null_score\r\n min_null_feature_index = feature_index\r\n null_start_logit = result.start_logits[0]\r\n null_end_logit = result.end_logits[0]\r\n for start_index in start_indexes:\r\n for end_index in end_indexes:\r\n # We could hypothetically create invalid predictions, e.g., predict\r\n # that the start of the span is in the question. We throw out all\r\n # invalid predictions.\r\n if start_index >= len(feature.tokens):\r\n continue\r\n if end_index >= len(feature.tokens):\r\n continue\r\n if start_index not in feature.token_to_orig_map:\r\n continue\r\n if end_index not in feature.token_to_orig_map:\r\n continue\r\n if not feature.token_is_max_context.get(start_index, False):\r\n continue\r\n if end_index < start_index:\r\n continue\r\n length = end_index - start_index + 1\r\n if length > max_answer_length:\r\n continue\r\n prelim_predictions.append(\r\n _PrelimPrediction(\r\n feature_index=feature_index,\r\n start_index=start_index,\r\n end_index=end_index,\r\n start_logit=result.start_logits[start_index],\r\n end_logit=result.end_logits[end_index]))\r\n\r\n if FLAGS.version_2_with_negative:\r\n prelim_predictions.append(\r\n _PrelimPrediction(\r\n feature_index=min_null_feature_index,\r\n start_index=0,\r\n end_index=0,\r\n start_logit=null_start_logit,\r\n end_logit=null_end_logit))\r\n prelim_predictions = sorted(\r\n prelim_predictions,\r\n key=lambda x: (x.start_logit + x.end_logit),\r\n reverse=True)\r\n\r\n _NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name\r\n \"NbestPrediction\", [\"text\", \"start_logit\", \"end_logit\"])\r\n\r\n seen_predictions = {}\r\n nbest = []\r\n for pred in prelim_predictions:\r\n if len(nbest) >= n_best_size:\r\n break\r\n feature = features[pred.feature_index]\r\n if pred.start_index > 0: # this is a non-null prediction\r\n tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)]\r\n orig_doc_start = feature.token_to_orig_map[pred.start_index]\r\n orig_doc_end = feature.token_to_orig_map[pred.end_index]\r\n orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)]\r\n tok_text = \" \".join(tok_tokens)\r\n\r\n # De-tokenize WordPieces that have been split off.\r\n tok_text = tok_text.replace(\" ##\", \"\")\r\n tok_text = tok_text.replace(\"##\", \"\")\r\n\r\n # Clean whitespace\r\n tok_text = tok_text.strip()\r\n tok_text = \" \".join(tok_text.split())\r\n orig_text = \" \".join(orig_tokens)\r\n\r\n final_text = get_final_text(tok_text, orig_text, do_lower_case)\r\n if final_text in seen_predictions:\r\n continue\r\n\r\n seen_predictions[final_text] = True\r\n else:\r\n final_text = \"\"\r\n seen_predictions[final_text] = True\r\n\r\n nbest.append(\r\n _NbestPrediction(\r\n text=final_text,\r\n start_logit=pred.start_logit,\r\n end_logit=pred.end_logit))\r\n\r\n # if we didn't inlude the empty option in the n-best, inlcude it\r\n if FLAGS.version_2_with_negative:\r\n if \"\" not in seen_predictions:\r\n nbest.append(\r\n _NbestPrediction(\r\n text=\"\", start_logit=null_start_logit,\r\n end_logit=null_end_logit))\r\n # In very rare edge cases we could have no valid predictions. So we\r\n # just create a nonce prediction in this case to avoid failure.\r\n if not nbest:\r\n nbest.append(\r\n _NbestPrediction(text=\"empty\", start_logit=0.0, end_logit=0.0))\r\n\r\n assert len(nbest) >= 1\r\n\r\n total_scores = []\r\n best_non_null_entry = None\r\n for entry in nbest:\r\n total_scores.append(entry.start_logit + entry.end_logit)\r\n if not best_non_null_entry:\r\n if entry.text:\r\n best_non_null_entry = entry\r\n\r\n probs = _compute_softmax(total_scores)\r\n\r\n nbest_json = []\r\n for (i, entry) in enumerate(nbest):\r\n output = collections.OrderedDict()\r\n output[\"text\"] = entry.text\r\n output[\"probability\"] = probs[i]\r\n output[\"start_logit\"] = entry.start_logit\r\n output[\"end_logit\"] = entry.end_logit\r\n nbest_json.append(output)\r\n\r\n assert len(nbest_json) >= 1\r\n \r\n \r\n if not FLAGS.version_2_with_negative:\r\n all_predictions[example.qas_id] = nbest_json[0][\"text\"]\r\n else:\r\n # predict \"\" iff the null score - the score of best non-null > threshold\r\n score_diff = score_null - best_non_null_entry.start_logit - (\r\n best_non_null_entry.end_logit)\r\n scores_diff_json[example.qas_id] = score_diff\r\n if score_diff > FLAGS.null_score_diff_threshold:\r\n all_predictions[example.qas_id] = \"\"\r\n else:\r\n all_predictions[example.qas_id] = best_non_null_entry.text\r\n\r\n all_nbest_json[example.qas_id] = nbest_json\r\n\r\n with tf.gfile.GFile(output_prediction_file, \"w\") as writer:\r\n writer.write(json.dumps(all_predictions, indent=4) + \"\\n\")\r\n\r\n with tf.gfile.GFile(output_nbest_file, \"w\") as writer:\r\n writer.write(json.dumps(all_nbest_json, indent=4) + \"\\n\")\r\n\r\n if FLAGS.version_2_with_negative:\r\n with tf.gfile.GFile(output_null_log_odds_file, \"w\") as writer:\r\n writer.write(json.dumps(scores_diff_json, indent=4) + \"\\n\")\r\n\r\n\r\n\r\ndef get_final_text(pred_text, orig_text, do_lower_case):\r\n \"\"\"Project the tokenized prediction back to the original text.\"\"\"\r\n\r\n # When we created the data, we kept track of the alignment between original\r\n # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So\r\n # now `orig_text` contains the span of our original text corresponding to the\r\n # span that we predicted.\r\n #\r\n # However, `orig_text` may contain extra characters that we don't want in\r\n # our prediction.\r\n #\r\n # For example, let's say:\r\n # pred_text = steve smith\r\n # orig_text = Steve Smith's\r\n #\r\n # We don't want to return `orig_text` because it contains the extra \"'s\".\r\n #\r\n # We don't want to return `pred_text` because it's already been normalized\r\n # (the SQuAD eval script also does punctuation stripping/lower casing but\r\n # our tokenizer does additional normalization like stripping accent\r\n # characters).\r\n #\r\n # What we really want to return is \"Steve Smith\".\r\n #\r\n # Therefore, we have to apply a semi-complicated alignment heruistic between\r\n # `pred_text` and `orig_text` to get a character-to-charcter alignment. This\r\n # can fail in certain cases in which case we just return `orig_text`.\r\n\r\n def _strip_spaces(text):\r\n ns_chars = []\r\n ns_to_s_map = collections.OrderedDict()\r\n for (i, c) in enumerate(text):\r\n if c == \" \":\r\n continue\r\n ns_to_s_map[len(ns_chars)] = i\r\n ns_chars.append(c)\r\n ns_text = \"\".join(ns_chars)\r\n return (ns_text, ns_to_s_map)\r\n\r\n # We first tokenize `orig_text`, strip whitespace from the result\r\n # and `pred_text`, and check if they are the same length. If they are\r\n # NOT the same length, the heuristic has failed. If they are the same\r\n # length, we assume the characters are one-to-one aligned.\r\n tokenizer = tokenization.BasicTokenizer(do_lower_case=do_lower_case)\r\n\r\n tok_text = \" \".join(tokenizer.tokenize(orig_text))\r\n\r\n start_position = tok_text.find(pred_text)\r\n if start_position == -1:\r\n if FLAGS.verbose_logging:\r\n tf.logging.info(\r\n \"Unable to find text: '%s' in '%s'\" % (pred_text, orig_text))\r\n return orig_text\r\n end_position = start_position + len(pred_text) - 1\r\n\r\n (orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)\r\n (tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)\r\n\r\n if len(orig_ns_text) != len(tok_ns_text):\r\n if FLAGS.verbose_logging:\r\n tf.logging.info(\"Length not equal after stripping spaces: '%s' vs '%s'\",\r\n orig_ns_text, tok_ns_text)\r\n return orig_text\r\n\r\n # We then project the characters in `pred_text` back to `orig_text` using\r\n # the character-to-character alignment.\r\n tok_s_to_ns_map = {}\r\n for (i, tok_index) in six.iteritems(tok_ns_to_s_map):\r\n tok_s_to_ns_map[tok_index] = i\r\n\r\n orig_start_position = None\r\n if start_position in tok_s_to_ns_map:\r\n ns_start_position = tok_s_to_ns_map[start_position]\r\n if ns_start_position in orig_ns_to_s_map:\r\n orig_start_position = orig_ns_to_s_map[ns_start_position]\r\n\r\n if orig_start_position is None:\r\n if FLAGS.verbose_logging:\r\n tf.logging.info(\"Couldn't map start position\")\r\n return orig_text\r\n\r\n orig_end_position = None\r\n if end_position in tok_s_to_ns_map:\r\n ns_end_position = tok_s_to_ns_map[end_position]\r\n if ns_end_position in orig_ns_to_s_map:\r\n orig_end_position = orig_ns_to_s_map[ns_end_position]\r\n\r\n if orig_end_position is None:\r\n if FLAGS.verbose_logging:\r\n tf.logging.info(\"Couldn't map end position\")\r\n return orig_text\r\n\r\n output_text = orig_text[orig_start_position:(orig_end_position + 1)]\r\n return output_text\r\n\r\n\r\ndef _get_best_indexes(logits, n_best_size):\r\n \"\"\"Get the n-best logits from a list.\"\"\"\r\n index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)\r\n\r\n best_indexes = []\r\n for i in range(len(index_and_score)):\r\n if i >= n_best_size:\r\n break\r\n best_indexes.append(index_and_score[i][0])\r\n return best_indexes\r\n\r\n\r\ndef _compute_softmax(scores):\r\n \"\"\"Compute softmax probability over raw logits.\"\"\"\r\n if not scores:\r\n return []\r\n\r\n max_score = None\r\n for score in scores:\r\n if max_score is None or score > max_score:\r\n max_score = score\r\n\r\n exp_scores = []\r\n total_sum = 0.0\r\n for score in scores:\r\n x = math.exp(score - max_score)\r\n exp_scores.append(x)\r\n total_sum += x\r\n\r\n probs = []\r\n for score in exp_scores:\r\n probs.append(score / total_sum)\r\n return probs\r\n\r\n\r\nclass FeatureWriter(object):\r\n \"\"\"Writes InputFeature to TF example file.\"\"\"\r\n\r\n def __init__(self, filename, is_training):\r\n self.filename = filename\r\n self.is_training = is_training\r\n self.num_features = 0\r\n self._writer = tf.python_io.TFRecordWriter(filename)\r\n\r\n def process_feature(self, feature):\r\n \"\"\"Write a InputFeature to the TFRecordWriter as a tf.train.Example.\"\"\"\r\n self.num_features += 1\r\n\r\n def create_int_feature(values):\r\n feature = tf.train.Feature(\r\n int64_list=tf.train.Int64List(value=list(values)))\r\n return feature\r\n\r\n features = collections.OrderedDict()\r\n features[\"unique_ids\"] = create_int_feature([feature.unique_id])\r\n features[\"input_ids\"] = create_int_feature(feature.input_ids)\r\n features[\"input_mask\"] = create_int_feature(feature.input_mask)\r\n features[\"segment_ids\"] = create_int_feature(feature.segment_ids)\r\n\r\n if self.is_training:\r\n features[\"start_positions\"] = create_int_feature(feature.start_position)\r\n features[\"end_positions\"] = create_int_feature(feature.end_position)\r\n impossible = 0\r\n if feature.is_impossible:\r\n impossible = 1\r\n features[\"is_impossible\"] = create_int_feature([impossible])\r\n\r\n tf_example = tf.train.Example(features=tf.train.Features(feature=features))\r\n self._writer.write(tf_example.SerializeToString())\r\n\r\n def close(self):\r\n self._writer.close()\r\n\r\n\r\ndef validate_flags_or_throw(bert_config):\r\n \"\"\"Validate the input FLAGS or throw an exception.\"\"\"\r\n tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,\r\n FLAGS.init_checkpoint)\r\n\r\n if not FLAGS.do_train and not FLAGS.do_predict:\r\n raise ValueError(\"At least one of `do_train` or `do_predict` must be True.\")\r\n\r\n if FLAGS.do_train:\r\n if not FLAGS.train_file:\r\n raise ValueError(\r\n \"If `do_train` is True, then `train_file` must be specified.\")\r\n if FLAGS.do_predict:\r\n if not FLAGS.predict_file:\r\n raise ValueError(\r\n \"If `do_predict` is True, then `predict_file` must be specified.\")\r\n\r\n if FLAGS.max_seq_length > bert_config.max_position_embeddings:\r\n raise ValueError(\r\n \"Cannot use sequence length %d because the BERT model \"\r\n \"was only trained up to sequence length %d\" %\r\n (FLAGS.max_seq_length, bert_config.max_position_embeddings))\r\n\r\n if FLAGS.max_seq_length <= FLAGS.max_query_length + 3:\r\n raise ValueError(\r\n \"The max_seq_length (%d) must be greater than max_query_length \"\r\n \"(%d) + 3\" % (FLAGS.max_seq_length, FLAGS.max_query_length))\r\n\r\n\r\ndef main(_):\r\n tf.logging.set_verbosity(tf.logging.INFO)\r\n\r\n bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)\r\n\r\n validate_flags_or_throw(bert_config)\r\n\r\n tf.gfile.MakeDirs(FLAGS.output_dir)\r\n\r\n tokenizer = tokenization.FullTokenizer(\r\n vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)\r\n\r\n tpu_cluster_resolver = None\r\n if FLAGS.use_tpu and FLAGS.tpu_name:\r\n tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(\r\n FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)\r\n\r\n is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2\r\n run_config = tf.contrib.tpu.RunConfig(\r\n cluster=tpu_cluster_resolver,\r\n master=FLAGS.master,\r\n model_dir=FLAGS.output_dir,\r\n save_checkpoints_steps=FLAGS.save_checkpoints_steps,\r\n tpu_config=tf.contrib.tpu.TPUConfig(\r\n iterations_per_loop=FLAGS.iterations_per_loop,\r\n num_shards=FLAGS.num_tpu_cores,\r\n per_host_input_for_training=is_per_host))\r\n\r\n train_examples = None\r\n num_train_steps = None\r\n num_warmup_steps = None\r\n if FLAGS.do_train:\r\n \r\n train_examples = read_squad_examples(\r\n input_file=FLAGS.train_file, is_training=True)\r\n ## Calculate the number of features first to calculate the num_train_steps\r\n # We write to a temporary file to avoid storing very large constant tensors\r\n # in memory.\r\n \r\n train_writer = FeatureWriter(\r\n filename=os.path.join(FLAGS.output_dir, \"train.tf_record\"),\r\n is_training=True)\r\n convert_examples_to_features(\r\n examples=train_examples,\r\n tokenizer=tokenizer,\r\n max_seq_length=FLAGS.max_seq_length,\r\n doc_stride=FLAGS.doc_stride,\r\n max_query_length=FLAGS.max_query_length,\r\n is_training=True,\r\n output_fn=train_writer.process_feature)\r\n ## The total number of features\r\n train_features = train_writer.num_features\r\n ##\r\n train_writer.close()\r\n \r\n tf.logging.info(\"***** Running training *****\")\r\n tf.logging.info(\" Num orig examples = %d\", len(train_examples))\r\n tf.logging.info(\" Num split examples = %d\", train_writer.num_features)\r\n tf.logging.info(\" Batch size = %d\", FLAGS.train_batch_size)\r\n tf.logging.info(\" Num steps = %d\", num_train_steps)\r\n \r\n ##\r\n #train_features = 591335\r\n #\r\n num_train_steps = int(\r\n #len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)\r\n train_features / FLAGS.train_batch_size * FLAGS.num_train_epochs)\r\n num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)\r\n\r\n # Pre-shuffle the input to avoid having to make a very large shuffle\r\n # buffer in in the `input_fn`.\r\n rng = random.Random(12345)\r\n rng.shuffle(train_examples)\r\n\r\n model_fn = model_fn_builder(\r\n bert_config=bert_config,\r\n init_checkpoint=FLAGS.init_checkpoint,\r\n learning_rate=FLAGS.learning_rate,\r\n num_train_steps=num_train_steps,\r\n num_warmup_steps=num_warmup_steps,\r\n use_tpu=FLAGS.use_tpu,\r\n use_one_hot_embeddings=FLAGS.use_tpu)\r\n\r\n # If TPU is not available, this will fall back to normal Estimator on CPU\r\n # or GPU.\r\n estimator = tf.contrib.tpu.TPUEstimator(\r\n use_tpu=FLAGS.use_tpu,\r\n model_fn=model_fn,\r\n config=run_config,\r\n train_batch_size=FLAGS.train_batch_size,\r\n predict_batch_size=FLAGS.predict_batch_size)\r\n \r\n if FLAGS.do_train:\r\n #del train_examples\r\n\r\n train_input_fn = input_fn_builder(\r\n input_file=os.path.join(FLAGS.output_dir, \"train.tf_record\"),\r\n seq_length=FLAGS.max_seq_length,\r\n is_training=True,\r\n drop_remainder=True)\r\n \r\n estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)\r\n\r\n if FLAGS.do_predict:\r\n\r\n eval_examples = read_squad_examples(\r\n input_file=FLAGS.predict_file, is_training=False)\r\n \r\n eval_writer = FeatureWriter(\r\n filename=os.path.join(FLAGS.output_dir, \"eval.tf_record\"),\r\n is_training=False)\r\n eval_features = []\r\n \r\n def append_feature(feature):\r\n eval_features.append(feature)\r\n eval_writer.process_feature(feature)\r\n \r\n convert_examples_to_features(\r\n examples=eval_examples,\r\n tokenizer=tokenizer,\r\n max_seq_length=FLAGS.max_seq_length,\r\n doc_stride=FLAGS.doc_stride,\r\n max_query_length=FLAGS.max_query_length,\r\n is_training=False,\r\n output_fn=append_feature)\r\n eval_writer.close()\r\n \r\n tf.logging.info(\"***** Running predictions *****\")\r\n tf.logging.info(\" Num orig examples = %d\", len(eval_examples))\r\n tf.logging.info(\" Num split examples = %d\", len(eval_features))\r\n tf.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size)\r\n## write features to file\r\n tf.logging.info(\"Writing features\")\r\n json_file=os.path.join(FLAGS.output_dir, \"test_features.json\")\r\n with open(json_file, 'r') as outfile:\r\n all_features=[]\r\n for temp_feature in eval_features:\r\n feature_dict={\r\n \"tokens\":temp_feature.tokens,\r\n \"token_to_orig_map\":temp_feature.token_to_orig_map\r\n }\r\n all_features.append(feature_dict)\r\n json.dump(all_features, outfile, indent=4, sort_keys=True, ensure_ascii=False)\r\n \r\n## read features from file \r\n eval_features=[]\r\n \r\n with io.open(json_file, \"r\",encoding='utf8') as reader:\r\n input_data = json.load(reader)\r\n for entry in input_data:\r\n InputFeatures(temp_feature)\r\n temp_feature.tokens=entry[\"tokens\"]\r\n temp_feature.token_to_orig_map==entry[\"token_to_orig_map\"]\r\n eval_features.append(temp_feature)\r\n\r\n\r\n##\r\n all_results = []\r\n\r\n predict_input_fn = input_fn_builder(\r\n## input_file=eval_writer.filename,\r\n input_file=os.path.join(FLAGS.output_dir, \"eval.tf_record\"),\r\n seq_length=FLAGS.max_seq_length,\r\n is_training=False,\r\n drop_remainder=False)\r\n\r\n # If running eval on the TPU, you will need to specify the number of\r\n # steps.\r\n all_results = []\r\n for result in estimator.predict(\r\n predict_input_fn, yield_single_examples=True):\r\n if len(all_results) % 1000 == 0:\r\n tf.logging.info(\"Processing example: %d\" % (len(all_results)))\r\n unique_id = int(result[\"unique_ids\"])\r\n start_logits = [float(x) for x in result[\"start_logits\"].flat]\r\n end_logits = [float(x) for x in result[\"end_logits\"].flat]\r\n all_results.append(\r\n RawResult(\r\n unique_id=unique_id,\r\n start_logits=start_logits,\r\n end_logits=end_logits))\r\n\r\n output_prediction_file = os.path.join(FLAGS.output_dir, \"predictions.json\")\r\n output_nbest_file = os.path.join(FLAGS.output_dir, \"nbest_predictions.json\")\r\n output_null_log_odds_file = os.path.join(FLAGS.output_dir, \"null_odds.json\")\r\n\r\n write_predictions(eval_examples, eval_features, all_results,\r\n FLAGS.n_best_size, FLAGS.max_answer_length,\r\n FLAGS.do_lower_case, output_prediction_file,\r\n output_nbest_file, output_null_log_odds_file)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n flags.mark_flag_as_required(\"vocab_file\")\r\n flags.mark_flag_as_required(\"bert_config_file\")\r\n flags.mark_flag_as_required(\"output_dir\")\r\n tf.app.run()\r\n"
] |
[
[
"tensorflow.contrib.tpu.TPUEstimatorSpec",
"tensorflow.data.TFRecordDataset",
"tensorflow.train.Features",
"tensorflow.contrib.tpu.TPUEstimator",
"tensorflow.matmul",
"tensorflow.reshape",
"tensorflow.nn.softmax",
"tensorflow.one_hot",
"tensorflow.logging.warning",
"tensorflow.parse_single_example",
"tensorflow.trainable_variables",
"tensorflow.flags.DEFINE_string",
"tensorflow.contrib.tpu.TPUConfig",
"tensorflow.FixedLenFeature",
"tensorflow.logging.info",
"tensorflow.transpose",
"tensorflow.gfile.MakeDirs",
"tensorflow.contrib.cluster_resolver.TPUClusterResolver",
"tensorflow.app.run",
"tensorflow.nn.bias_add",
"tensorflow.logging.set_verbosity",
"tensorflow.python_io.TFRecordWriter",
"tensorflow.gfile.GFile",
"tensorflow.reduce_sum",
"tensorflow.train.init_from_checkpoint",
"tensorflow.to_int32",
"tensorflow.unstack",
"tensorflow.zeros_initializer",
"tensorflow.train.Scaffold",
"tensorflow.truncated_normal_initializer"
]
] |
JieRen98/rlkit-pmoe
|
[
"5ef4e056764d2c4a8d6e4c6da89295304b1fec3f"
] |
[
"rlkit/torch/sac/sac.py"
] |
[
"from collections import OrderedDict\n\nimport numpy as np\nimport torch\nimport torch.optim as optim\nfrom torch import nn as nn\n\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.core.eval_util import create_stats_ordered_dict\nfrom rlkit.torch.torch_rl_algorithm import TorchTrainer\n\n\nclass SACTrainer(TorchTrainer):\n def __init__(\n self,\n env,\n policy,\n qf1,\n qf2,\n target_qf1,\n target_qf2,\n\n discount=0.99,\n reward_scale=1.0,\n\n policy_lr=1e-3,\n qf_lr=1e-3,\n optimizer_class=optim.Adam,\n\n soft_target_tau=1e-2,\n target_update_period=1,\n plotter=None,\n render_eval_paths=False,\n\n use_automatic_entropy_tuning=True,\n target_entropy=None,\n k=4\n ):\n super().__init__()\n self.k = k\n self.env = env\n self.policy = policy\n self.qf1 = qf1\n self.qf2 = qf2\n self.target_qf1 = target_qf1\n self.target_qf2 = target_qf2\n self.soft_target_tau = soft_target_tau\n self.target_update_period = target_update_period\n\n self.use_automatic_entropy_tuning = use_automatic_entropy_tuning\n if self.use_automatic_entropy_tuning:\n if target_entropy:\n self.target_entropy = target_entropy\n else:\n self.target_entropy = -np.prod(self.env.action_space.shape).item() # heuristic value from Tuomas\n self.log_alpha = ptu.zeros(1, requires_grad=True)\n self.alpha_optimizer = optimizer_class(\n [self.log_alpha],\n lr=policy_lr,\n )\n\n self.plotter = plotter\n self.render_eval_paths = render_eval_paths\n\n self.qf_criterion = nn.MSELoss()\n self.vf_criterion = nn.MSELoss()\n\n self.policy_optimizer = optimizer_class(\n self.policy.parameters(),\n lr=policy_lr,\n )\n self.qf1_optimizer = optimizer_class(\n self.qf1.parameters(),\n lr=qf_lr,\n )\n self.qf2_optimizer = optimizer_class(\n self.qf2.parameters(),\n lr=qf_lr,\n )\n\n self.discount = discount\n self.reward_scale = reward_scale\n self.eval_statistics = OrderedDict()\n self._n_train_steps_total = 0\n self._need_to_update_eval_statistics = True\n\n def train_from_torch(self, batch):\n rewards = batch['rewards']\n terminals = batch['terminals']\n obs = batch['observations']\n actions = batch['actions']\n next_obs = batch['next_observations']\n\n \"\"\"\n Policy and Alpha Loss\n \"\"\"\n new_obs_actions, policy_mean, policy_log_std, log_pi, *_ = self.policy(\n obs, reparameterize=True, return_log_prob=True,\n )\n if self.use_automatic_entropy_tuning:\n alpha_loss = -(self.log_alpha * (log_pi + self.target_entropy).detach()).mean()\n self.alpha_optimizer.zero_grad()\n alpha_loss.backward()\n self.alpha_optimizer.step()\n alpha = self.log_alpha.exp()\n else:\n alpha_loss = 0\n alpha = 1\n\n q_new_actions = torch.min(\n self.qf1(obs, new_obs_actions),\n self.qf2(obs, new_obs_actions),\n )\n policy_loss = (alpha*log_pi - q_new_actions).mean()\n\n \"\"\"\n QF Loss\n \"\"\"\n q1_pred = self.qf1(obs, actions)\n q2_pred = self.qf2(obs, actions)\n # Make sure policy accounts for squashing functions like tanh correctly!\n new_next_actions, _, _, new_log_pi, *_ = self.policy(\n next_obs, reparameterize=True, return_log_prob=True,\n )\n target_q_values = torch.min(\n self.target_qf1(next_obs, new_next_actions),\n self.target_qf2(next_obs, new_next_actions),\n ) - alpha * new_log_pi\n\n q_target = self.reward_scale * rewards + (1. - terminals) * self.discount * target_q_values\n qf1_loss = self.qf_criterion(q1_pred, q_target.detach())\n qf2_loss = self.qf_criterion(q2_pred, q_target.detach())\n\n \"\"\"\n Update networks\n \"\"\"\n self.qf1_optimizer.zero_grad()\n qf1_loss.backward()\n self.qf1_optimizer.step()\n\n self.qf2_optimizer.zero_grad()\n qf2_loss.backward()\n self.qf2_optimizer.step()\n\n self.policy_optimizer.zero_grad()\n policy_loss.backward()\n self.policy_optimizer.step()\n\n \"\"\"\n Soft Updates\n \"\"\"\n if self._n_train_steps_total % self.target_update_period == 0:\n ptu.soft_update_from_to(\n self.qf1, self.target_qf1, self.soft_target_tau\n )\n ptu.soft_update_from_to(\n self.qf2, self.target_qf2, self.soft_target_tau\n )\n\n \"\"\"\n Save some statistics for eval\n \"\"\"\n if self._need_to_update_eval_statistics:\n self._need_to_update_eval_statistics = False\n \"\"\"\n Eval should set this to None.\n This way, these statistics are only computed for one batch.\n \"\"\"\n policy_loss = (log_pi - q_new_actions).mean()\n\n self.eval_statistics['QF1 Loss'] = np.mean(ptu.get_numpy(qf1_loss))\n self.eval_statistics['QF2 Loss'] = np.mean(ptu.get_numpy(qf2_loss))\n self.eval_statistics['Policy Loss'] = np.mean(ptu.get_numpy(\n policy_loss\n ))\n self.eval_statistics.update(create_stats_ordered_dict(\n 'Q1 Predictions',\n ptu.get_numpy(q1_pred),\n ))\n self.eval_statistics.update(create_stats_ordered_dict(\n 'Q2 Predictions',\n ptu.get_numpy(q2_pred),\n ))\n self.eval_statistics.update(create_stats_ordered_dict(\n 'Q Targets',\n ptu.get_numpy(q_target),\n ))\n self.eval_statistics.update(create_stats_ordered_dict(\n 'Log Pis',\n ptu.get_numpy(log_pi),\n ))\n self.eval_statistics.update(create_stats_ordered_dict(\n 'Policy mu',\n ptu.get_numpy(policy_mean),\n ))\n self.eval_statistics.update(create_stats_ordered_dict(\n 'Policy log std',\n ptu.get_numpy(policy_log_std),\n ))\n if self.use_automatic_entropy_tuning:\n self.eval_statistics['Alpha'] = alpha.item()\n self.eval_statistics['Alpha Loss'] = alpha_loss.item()\n self._n_train_steps_total += 1\n\n def get_diagnostics(self):\n return self.eval_statistics\n\n def end_epoch(self, epoch):\n self._need_to_update_eval_statistics = True\n\n @property\n def networks(self):\n return [\n self.policy,\n self.qf1,\n self.qf2,\n self.target_qf1,\n self.target_qf2,\n ]\n\n def get_snapshot(self):\n return dict(\n policy=self.policy,\n qf1=self.qf1,\n qf2=self.qf2,\n target_qf1=self.qf1,\n target_qf2=self.qf2,\n )\n"
] |
[
[
"numpy.prod",
"torch.nn.MSELoss"
]
] |
ferr26/toolMusicPlagiarism
|
[
"cc6985d9847ca5589b5a0792845b7e85ce80e634"
] |
[
"spectClustering.py"
] |
[
"import chars2vec\nimport csv\nfrom sklearn.cluster import SpectralClustering\n\n\ndef spectralClustering():\n words=[]\n\n with open('./datasetFit.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n for row in csv_reader:\n if line_count == 0:\n #print(f'Column names are {\", \".join(row)}')\n line_count += 1\n else:\n words.append(row[2])\n line_count += 1\n\n with open('./datasetCouple.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n arrayDiStringhe=[]\n for row in csv_reader:\n if line_count == 0:\n #print(f'Column names are {\", \".join(row)}')\n line_count += 1\n else:\n words.append(row)\n line_count += 1\n for i in range(len(words)):\n if(words[i]):\n\n stringa = str(words[i])\n stringa = stringa.replace(\"[\", \"\")\n stringa = stringa.replace(\"]\", \"\")\n stringa = stringa.replace(\"'\", \"\")\n arrayDiStringhe.append(stringa)\n\n\n c2v_model = chars2vec.load_model('eng_50')\n word_embeddings = c2v_model.vectorize_words(arrayDiStringhe)\n #print(word_embeddings)\n #print(len(word_embeddings))\n\n clustering = SpectralClustering(n_clusters=9,\n assign_labels=\"discretize\",\n random_state=0).fit(word_embeddings)\n labels=clustering.labels_\n #print(labels)\n l=len(labels)\n\n if (labels[l-1]==labels[l-2]):\n #print('TRUE')\n return True\n else:\n #print('FALSE')\n return False\n"
] |
[
[
"sklearn.cluster.SpectralClustering"
]
] |
agamemnonc/axopy
|
[
"e8c324a4ecfc0abdec3016bca62dcf84d371b6c0"
] |
[
"axopy/design.py"
] |
[
"\"\"\"Task design containers.\"\"\"\n\nimport numpy\nimport random\nimport pprint\n\n__all__ = ['Design', 'Block', 'Trial', 'Array']\n\n\nclass Design(list):\n \"\"\"Top-level task design container.\n\n The :class:`Design` is a list of :class:`Block` objects, which themselves\n are lists of :class:`Trial` objects.\n \"\"\"\n\n def add_block(self):\n \"\"\"Add a block to the design.\n\n Returns\n -------\n block : design.Block\n The created block.\n \"\"\"\n block = Block(len(self))\n self.append(block)\n return block\n\n\nclass Block(list):\n \"\"\"List of trials.\n\n Experiments often consist of a set of blocks, each containing the same set\n of trials in randomized order. You usually shouldn't need to create a block\n directly -- use :meth:`Design.add_block` instead.\n\n Parameters\n ----------\n index : int\n Index of the block in the design. This is required to pass along to\n each trial in the block, so that the trial knows which block it belongs\n to.\n \"\"\"\n\n def __init__(self, index, *args, **kwargs):\n super(Block, self).__init__(*args, **kwargs)\n self.index = index\n\n def add_trial(self, attrs=None):\n \"\"\"Add a trial to the block.\n\n A :class:`Trial` object is created and added to the block. You can\n optionally provide a dictionary of attribute name/value pairs to\n initialize the trial.\n\n Parameters\n ----------\n attrs : dict, optional\n Dictionary of attribute name/value pairs.\n\n Returns\n -------\n trial : Trial\n The trial object created. This can be used to add new attributes or\n arrays. See :class:`Trial`.\n \"\"\"\n if attrs is None:\n attrs = {}\n\n attrs.update({'block': self.index, 'trial': len(self)})\n\n trial = Trial(attrs=attrs)\n self.append(trial)\n return trial\n\n def shuffle(self, reset_index=True, seed=None):\n \"\"\"Shuffle the block's trials in random order.\n\n Parameters\n ----------\n reset_index : bool, optional\n Whether or not to set the ``trial`` attribute of each trial such\n that they remain in sequential order after shuffling. This is the\n default.\n seed : int, optional\n If provided, the random seed will be set to the specified value to\n ensure reproducible shuffling. Note that if you have multiple\n identical blocks and want to shuffle them differently, use a\n different seed value for each block.\n \"\"\"\n if seed is not None:\n random.seed(seed)\n\n random.shuffle(self)\n if reset_index:\n for i, trial in enumerate(self):\n trial.attrs['trial'] = i\n\n\nclass Trial(object):\n \"\"\"Container of trial data.\n\n There are two kinds of data typically needed during a trial: attributes and\n arrays. Attributes are scalar quantities or primitives like integers,\n floating point numbers, booleans, strings, etc. Arrays are NumPy arrays,\n useful for holding things like cursor trajectories.\n\n There are two primary purposes for each of these two kinds of data. First,\n it's useful to design a task with pre-determined values, such as the target\n location or the cursor trajectory to follow. The other purpose is to\n temporarily hold runtime data using the same interface, such as the final\n cursor position or the time-to-target.\n\n You shouldn't normally need to create a trial directly -- instead, use\n :meth:`Block.add_trial`.\n\n Attributes\n ----------\n attrs : dict\n Dictionary mapping attribute names to their values.\n arrays : dict\n Dictionary mapping array names to :class:`Array` objects, which contain\n the array data.\n \"\"\"\n\n def __init__(self, attrs):\n self.attrs = attrs\n self.arrays = {}\n\n def add_array(self, name, **kwargs):\n \"\"\"Add an array to the trial.\n\n Parameters\n ----------\n name : str\n Name of the array.\n kwargs : dict\n Keyword arguments passed along to :class:`Array`.\n \"\"\"\n self.arrays[name] = Array(**kwargs)\n\n def add_bufferedarray(self, name, **kwargs):\n \"\"\"Add a buffered array to the trial.\n\n Parameters\n ----------\n name : str\n Name of the array.\n kwargs : dict\n Keyword arguments passed along to :class:`BufferedArray`.\n \"\"\"\n self.arrays[name] = BufferedArray(**kwargs)\n\n def __str__(self):\n return pprint.pformat(self.attrs)\n\n\nclass Array(object):\n \"\"\"Trial array.\n\n The array is not much more than a NumPy array with a :meth:`stack` method\n for conveniently adding new data to the array. This is useful in cases\n where you iteratively collect new segments of data and want to concatenate\n them. For example, you could use an :class:`Array` to collect the samples\n from a data acquisition device as they come in.\n\n You usually don't need to create an array manually -- instead, use\n :meth:`Trial.add_array`.\n\n Parameters\n ----------\n data : ndarray, optional\n Data to initialize the array with. If ``None``, the first array passed\n to :meth:`stack` is used for initialization.\n stack_axis : int, optional\n Axis to stack the data along.\n dtype : str, optional\n Array data type. Default is 'f'.\n\n Attributes\n ----------\n data : ndarray, optional\n The NumPy array holding the data.\n \"\"\"\n\n _stack_funcs = {0: numpy.vstack, 1: numpy.hstack, 2: numpy.dstack}\n\n def __init__(self, data=None, stack_axis=1, dtype='f'):\n self.data = data\n self.stack_axis = stack_axis\n self.dtype = dtype\n\n def stack(self, data):\n \"\"\"Stack new data onto the array.\n\n Parameters\n ----------\n data : ndarray\n New data to add. The direction to stack along is specified in the\n array's constructor (stack_axis).\n \"\"\"\n if self.data is None:\n self.data = data\n else:\n self.data = self._stack_funcs[self.stack_axis]([self.data, data])\n\n def clear(self):\n \"\"\"Clears the buffer.\n\n Anything that was in the buffer is not retrievable.\n \"\"\"\n self.data = None\n\n\nclass BufferedArray(object):\n \"\"\"Trial array.\n\n The buffered array preallocates an array an insert method for adding new\n data. The size of the buffer must be set manually. This is useful in cases\n where you are iteratively collecting new segments of data and you would\n like to record for longer periods of time. For example, you could use a\n :class:`BufferedArray` to collect samples from a data acquisition device\n as they come in for rather a long time and things should not start to lag\n because memory has already been allocated.\n\n The attribute data is empty until :meth:`BufferedArray.set_data` is\n called. If the size of the buffer is exceeded data will be empty.\n\n You usually don't need to create an buffered array manually -- instead,\n use :meth:`Trial.add_bufferedarray`.\n\n Parameters\n ----------\n buffer_dims: tuple(int, int, int)\n Tuple to determine the size of the buffered array.\n\n insert_axis : int, optional\n Axis to insert the data along.\n\n dtype : str, optional\n Array data type. Default is 'f'.\n\n Attributes\n ----------\n data : ndarray, optional\n The NumPy array holding the data.\n \"\"\"\n\n def __init__(self, buffer_dims=(8, 10), insert_axis=1, dtype='f'):\n self.insert_axis = insert_axis\n self.dtype = dtype\n self.buffer_dims = buffer_dims\n self.buffer = numpy.zeros(buffer_dims, self.dtype)\n self.pos = 0\n self.overflow = False\n self.data = numpy.empty((0, 0))\n\n def insert(self, data):\n \"\"\"Insert new data into the buffer.\n\n Parameters\n ----------\n data : ndarray\n New data to add. The direction to insert on is specified in the\n array's constructor (insert_axis).\n \"\"\"\n if self.overflow:\n return\n\n if data.ndim > 1:\n new_sample = data.shape[self.insert_axis]\n else:\n new_sample = 1\n\n new_pos = self.pos + new_sample\n if (new_pos > self.buffer_dims[self.insert_axis]):\n self.overflow = True\n return\n\n # about as stupid as Axopy's arbitrary stack dims\n idx = slice(self.pos, new_pos)\n if (self.insert_axis == 0):\n self.buffer[idx, :] = data\n elif(self.insert_axis == 1):\n self.buffer[:, idx] = data\n elif(self.insert_axis == 2):\n self.buffer[:, :, idx] = data\n\n self.pos += new_sample\n\n def clear(self):\n \"\"\"Clears the buffer and resets the interator\n\n Anything that was in the buffer is not retrievable.\n \"\"\"\n self.buffer.fill(0)\n self.pos = 0\n self.overflow = False\n self.data = numpy.empty((0, 0))\n\n def set_data(self):\n \"\"\"Creates the data attribute.\n\n In the case of overflow data will be empty.\n \"\"\"\n if self.overflow:\n return\n\n idx = slice(0, self.pos)\n if (self.insert_axis == 0):\n self.data = self.buffer[idx, :]\n elif(self.insert_axis == 1):\n self.data = self.buffer[:, idx]\n elif(self.insert_axis == 2):\n self.data = self.buffer[:, :, idx]"
] |
[
[
"numpy.empty",
"numpy.zeros"
]
] |
ieuTeamD/pangoro
|
[
"b093a995e0f4624c56f399ebf563b2b66ed5b700"
] |
[
"tests/test.py"
] |
[
"import unittest\nfrom pangoro.preprocessing import PangoroDataFrame\nimport pandas as pd\n\n\ndef broken_function():\n raise Exception('This is broken')\n\nclass TestDataFrame(unittest.TestCase):\n def test_simple_dataframe(self):\n df1 = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})\n df2 = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})\n self.assertEqual(True, df1.equals(df2))\n\n def test_numerical_transformation_unchanged(self): \n sample_data = pd.DataFrame({'pet': ['cat', 'dog', 'dog', pd.NA, 'cat', 'dog', 'cat', 'fish'],\n 'color': ['white', 'brown', 'black', 'gold', pd.NA,'black', 'white', 'silver'],\n 'weight': [50.5, 22.5, 4, pd.NA , 12, 39, 16, pd.NA]})\n sample_data['weight'] = pd.to_numeric(sample_data['weight'])\n #sample_data.dtypes\n \n pdf = PangoroDataFrame(sample_data)\n pdf.numerical_transformation()# without passing any parameters, this should not perform any change\n self.assertEqual(True, pdf.equals(sample_data))\n\n def test_numerical_transformation_na_treat_mode(self):\n df1 = pd.DataFrame({'a': [1, pd.NA,1,1,1,1,1,8,9.0,pd.NA]})\n df2 = pd.DataFrame({'a': [1, 1,1,1,1,1,1,8,9,1.0]})\n df1['a'] = pd.to_numeric(df1['a'])\n df2['a'] = pd.to_numeric(df2['a'])\n\n pdf = PangoroDataFrame(df1)\n pdf.numerical_transformation(col=['a'],na_treat = 'mode')# treating NAs with mode should yield same result as \n self.assertEqual(True, pdf.equals(df2))\n\n\n def test_numerical_transformation_raise_TypeError(self):\n df1_with_err = pd.DataFrame({'a': [1,'cat']})\n pdf = PangoroDataFrame(df1_with_err)\n\n with self.assertRaises(TypeError):\n pdf.numerical_transformation(col=['a'],na_treat = 'mode')# TypeError should be raised \n self.assertTrue('TypeError: Error: column a is not numeric' )\n \n def test_categorical_transformation_Transform(self):\n df1 = pd.DataFrame({'a': ['cat', pd.NA,'dog',pd.NA]})\n df2 = pd.DataFrame({'a_dog': [0.0,pd.NA,1.0]})\n df2=df2.dropna()\n df2['a_dog']=pd.to_numeric(df2['a_dog'],errors='coerce')\n \n pdf = PangoroDataFrame(df1) \n \n pdf.categorical_nominal_transformation(col=['a'],na_treat = 'drop' )\n pdf =pdf.categorical_nominal_transformation(col=['a'],transform=True )\n pdf.equals(df2)\n self.assertEqual(True, pdf.equals(df2))\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"pandas.DataFrame",
"pandas.to_numeric"
]
] |
FrancaCassol/ctapipe
|
[
"1e62e6800bdd52625cc8657a8f47c7dda0bd44e0",
"1e62e6800bdd52625cc8657a8f47c7dda0bd44e0",
"1e62e6800bdd52625cc8657a8f47c7dda0bd44e0"
] |
[
"ctapipe/visualization/bokeh.py",
"examples/stereo_reconstruction.py",
"ctapipe/image/tests/test_image_cleaner_component.py"
] |
[
"import warnings\nimport numpy as np\nfrom bokeh.plotting import figure\nfrom bokeh.events import Tap\nfrom bokeh import palettes\nfrom bokeh.models import (\n ColumnDataSource,\n TapTool,\n Span,\n ColorBar,\n LinearColorMapper,\n)\nfrom ctapipe.utils.rgbtohex import intensity_to_hex\n\nPLOTARGS = dict(tools=\"\", toolbar_location=None, outline_line_color='#595959')\n\n\nclass CameraDisplay:\n def __init__(self, geometry=None, image=None, fig=None):\n \"\"\"\n Camera display that utilises the bokeh visualisation library\n\n Parameters\n ----------\n geometry : `~ctapipe.instrument.CameraGeometry`\n Definition of the Camera/Image\n image : ndarray\n 1D array containing the image values for each pixel\n fig : bokeh.plotting.figure\n Figure to store the bokeh plot onto (optional)\n \"\"\"\n self._geom = None\n self._image = None\n self._colors = None\n self._image_min = None\n self._image_max = None\n self._fig = None\n\n self._n_pixels = None\n self._pix_sizes = np.ones(1)\n self._pix_areas = np.ones(1)\n self._pix_x = np.zeros(1)\n self._pix_y = np.zeros(1)\n\n self.glyphs = None\n self.cm = None\n self.cb = None\n\n cdsource_d = dict(image=[],\n x=[], y=[],\n width=[], height=[],\n outline_color=[], outline_alpha=[])\n self.cdsource = ColumnDataSource(data=cdsource_d)\n\n self._active_pixels = []\n self.active_index = 0\n self.active_colors = []\n self.automatic_index_increment = False\n\n self.geom = geometry\n self.image = image\n self.fig = fig\n\n self.layout = self.fig\n\n @property\n def fig(self):\n return self._fig\n\n @fig.setter\n def fig(self, val):\n if val is None:\n val = figure(plot_width=550, plot_height=500, **PLOTARGS)\n val.axis.visible = False\n val.grid.grid_line_color = None\n self._fig = val\n\n self._draw_camera()\n\n @property\n def geom(self):\n return self._geom\n\n @geom.setter\n def geom(self, val):\n self._geom = val\n\n if val is not None:\n self._pix_areas = val.pix_area.value\n self._pix_sizes = np.sqrt(self._pix_areas)\n self._pix_x = val.pix_x.value\n self._pix_y = val.pix_y.value\n\n self._n_pixels = self._pix_x.size\n if self._n_pixels == len(self.cdsource.data['x']):\n self.cdsource.data['x'] = self._pix_x\n self.cdsource.data['y'] = self._pix_y\n self.cdsource.data['width'] = self._pix_sizes\n self.cdsource.data['height'] = self._pix_sizes\n else:\n self._image = np.empty(self._pix_x.shape)\n alpha = [0] * self._n_pixels\n color = ['black'] * self._n_pixels\n cdsource_d = dict(image=self.image,\n x=self._pix_x, y=self._pix_y,\n width=self._pix_sizes, height=self._pix_sizes,\n outline_color=color, outline_alpha=alpha\n )\n self.cdsource.data = cdsource_d\n\n self.active_pixels = [0] * len(self.active_pixels)\n\n @property\n def image(self):\n return self._image\n\n @image.setter\n def image(self, val):\n if val is None:\n val = np.zeros(self._n_pixels)\n\n image_min = np.nanmin(val)\n image_max = np.nanmax(val)\n if image_max == image_min:\n image_min -= 1\n image_max += 1\n colors = intensity_to_hex(val, image_min, image_max)\n\n self._image = val\n self._colors = colors\n self.image_min = image_min\n self.image_max = image_max\n\n if len(colors) == self._n_pixels:\n with warnings.catch_warnings():\n warnings.simplefilter(action='ignore', category=FutureWarning)\n self.cdsource.data['image'] = colors\n else:\n raise ValueError(\"Image has a different size {} than the current \"\n \"CameraGeometry n_pixels {}\"\n .format(colors.size, self._n_pixels))\n\n @property\n def image_min(self):\n return self._image_min\n\n @image_min.setter\n def image_min(self, val):\n self._image_min = val\n if self.cb:\n self.cm.low = val.item()\n\n @property\n def image_max(self):\n return self._image_max\n\n @image_max.setter\n def image_max(self, val):\n self._image_max = val\n if self.cb:\n self.cm.high = val.item()\n\n @property\n def active_pixels(self):\n return self._active_pixels\n\n @active_pixels.setter\n def active_pixels(self, listval):\n self._active_pixels = listval\n\n palette = palettes.Set1[9]\n palette = [palette[0]] + palette[3:]\n self.active_colors = [palette[i % (len(palette))]\n for i in range(len(listval))]\n self.highlight_pixels()\n\n def reset_pixels(self):\n self.active_pixels = [0] * len(self.active_pixels)\n\n def _draw_camera(self):\n # TODO: Support other pixel shapes OR switch to ellipse\n # after https://github.com/bokeh/bokeh/issues/6985\n self.glyphs = self.fig.ellipse(\n 'x', 'y', color='image', width='width', height='height',\n line_color='outline_color',\n line_alpha='outline_alpha',\n line_width=2,\n nonselection_fill_color='image',\n nonselection_fill_alpha=1,\n nonselection_line_color='outline_color',\n nonselection_line_alpha='outline_alpha',\n source=self.cdsource\n )\n\n def enable_pixel_picker(self, n_active):\n \"\"\"\n Enables the selection of a pixel by clicking on it\n\n Parameters\n ----------\n n_active : int\n Number of active pixels to keep record of\n \"\"\"\n self.active_pixels = [0] * n_active\n self.fig.add_tools(TapTool())\n\n def source_change_response(_, __, val):\n if val:\n pix = val[0]\n ai = self.active_index\n self.active_pixels[ai] = pix\n\n self.highlight_pixels()\n self._on_pixel_click(pix)\n\n if self.automatic_index_increment:\n self.active_index = (ai + 1) % len(self.active_pixels)\n\n self.cdsource.selected.on_change('indices', source_change_response)\n\n def _on_pixel_click(self, pix_id):\n print(f\"Clicked pixel_id: {pix_id}\")\n print(f\"Active Pixels: {self.active_pixels}\")\n\n def highlight_pixels(self):\n alpha = [0] * self._n_pixels\n color = ['black'] * self._n_pixels\n for i, pix in enumerate(self.active_pixels):\n alpha[pix] = 1\n color[pix] = self.active_colors[i]\n self.cdsource.data['outline_alpha'] = alpha\n self.cdsource.data['outline_color'] = color\n\n def add_colorbar(self):\n self.cm = LinearColorMapper(palette=\"Viridis256\", low=0, high=100,\n low_color='white', high_color='red')\n self.cb = ColorBar(color_mapper=self.cm,\n border_line_color=None,\n background_fill_alpha=0,\n major_label_text_color='green',\n location=(0, 0))\n self.fig.add_layout(self.cb, 'right')\n self.cm.low = self.image_min.item()\n self.cm.high = self.image_max.item()\n\n\nclass FastCameraDisplay:\n def __init__(self, x_pix, y_pix, pix_size):\n \"\"\"\n A fast and simple version of the bokeh camera plotter that does not\n allow for geometry changes\n\n Parameters\n ----------\n x_pix : ndarray\n Pixel x positions\n y_pix : ndarray\n Pixel y positions\n pix_size : ndarray\n Pixel sizes\n \"\"\"\n self._image = None\n n_pix = x_pix.size\n\n cdsource_d = dict(image=np.empty(n_pix, dtype='<U8'), x=x_pix, y=y_pix)\n self.cdsource = ColumnDataSource(cdsource_d)\n self.fig = figure(plot_width=400, plot_height=400, **PLOTARGS)\n self.fig.grid.grid_line_color = None\n self.fig.rect('x', 'y', color='image', source=self.cdsource,\n width=pix_size[0], height=pix_size[0])\n\n self.layout = self.fig\n\n @property\n def image(self):\n return self._image\n\n @image.setter\n def image(self, val):\n \"\"\"\n Parameters\n ----------\n val : ndarray\n Array containing the image values, already converted into\n hexidecimal strings\n \"\"\"\n self.cdsource.data['image'] = val\n\n\nclass WaveformDisplay:\n def __init__(self, waveform=np.zeros(1), fig=None):\n \"\"\"\n Waveform display that utilises the bokeh visualisation library\n\n Parameters\n ----------\n waveform : ndarray\n 1D array containing the waveform samples\n fig : bokeh.plotting.figure\n Figure to store the bokeh plot onto (optional)\n \"\"\"\n self._waveform = None\n self._fig = None\n self._active_time = 0\n\n self.span = None\n\n cdsource_d = dict(t=[], samples=[])\n self.cdsource = ColumnDataSource(data=cdsource_d)\n\n self.waveform = waveform\n self.fig = fig\n\n self.layout = self.fig\n\n @property\n def fig(self):\n return self._fig\n\n @fig.setter\n def fig(self, val):\n if val is None:\n val = figure(plot_width=700, plot_height=180, **PLOTARGS)\n self._fig = val\n\n self._draw_waveform()\n\n @property\n def waveform(self):\n return self._waveform\n\n @waveform.setter\n def waveform(self, val):\n if val is None:\n val = np.full(1, np.nan)\n\n self._waveform = val\n\n if len(val) == len(self.cdsource.data['t']):\n self.cdsource.data['samples'] = val\n else:\n cdsource_d = dict(t=np.arange(val.size), samples=val)\n self.cdsource.data = cdsource_d\n\n @property\n def active_time(self):\n return self._active_time\n\n @active_time.setter\n def active_time(self, val):\n max_t = self.cdsource.data['t'][-1]\n if val is None:\n val = 0\n if val < 0:\n val = 0\n if val > max_t:\n val = max_t\n self.span.location = val\n self._active_time = val\n\n def _draw_waveform(self):\n self.fig.line(x=\"t\", y=\"samples\", source=self.cdsource, name='line')\n\n def enable_time_picker(self):\n \"\"\"\n Enables the selection of a time by clicking on the waveform\n \"\"\"\n self.span = Span(location=0, dimension='height',\n line_color='red', line_dash='dashed')\n self.fig.add_layout(self.span)\n\n taptool = TapTool()\n self.fig.add_tools(taptool)\n\n def wf_tap_response(event):\n time = event.x\n if time is not None:\n self.active_time = time\n self._on_waveform_click(time)\n\n self.fig.on_event(Tap, wf_tap_response)\n\n def _on_waveform_click(self, time):\n print(f\"Clicked time: {time}\")\n print(f\"Active time: {self.active_time}\")\n",
"import astropy.units as u\nfrom astropy.coordinates import SkyCoord, AltAz\n\nfrom ctapipe.io import event_source\nfrom ctapipe.calib import CameraCalibrator\nfrom ctapipe.image.cleaning import tailcuts_clean, number_of_islands\nfrom ctapipe.image import leakage, hillas_parameters\nfrom ctapipe.image.timing_parameters import timing_parameters\nfrom ctapipe.reco import HillasReconstructor\nfrom ctapipe.utils.datasets import get_dataset_path\n\nimport matplotlib.pyplot as plt\nfrom ctapipe.visualization import ArrayDisplay\n\n\n# unoptimized cleaning levels, copied from\n# https://github.com/tudo-astroparticlephysics/cta_preprocessing\ncleaning_level = {\n 'LSTCam': (3.5, 7.5, 2), # ?? (3, 6) for Abelardo...\n 'FlashCam': (4, 8, 2), # there is some scaling missing?\n 'ASTRICam': (5, 7, 2),\n}\n\n\ninput_url = get_dataset_path('gamma_test_large.simtel.gz')\nevent_source = event_source(input_url)\n\ncalibrator = CameraCalibrator()\nhorizon_frame = AltAz()\n\nreco = HillasReconstructor()\n\nfor event in event_source:\n print('Event', event.count)\n calibrator(event)\n\n # mapping of telescope_id to parameters for stereo reconstruction\n hillas_containers = {}\n\n time_gradients = {}\n\n for telescope_id, dl1 in event.dl1.tel.items():\n camera = event.inst.subarray.tels[telescope_id].camera\n\n image = dl1.image\n peakpos = dl1.pulse_time\n\n # cleaning\n boundary, picture, min_neighbors = cleaning_level[camera.cam_id]\n clean = tailcuts_clean(\n camera,\n image,\n boundary_thresh=boundary,\n picture_thresh=picture,\n min_number_picture_neighbors=min_neighbors\n )\n\n # ignore images with less than 5 pixels after cleaning\n if clean.sum() < 5:\n continue\n\n # image parameters\n hillas_c = hillas_parameters(camera[clean], image[clean])\n leakage_c = leakage(camera, image, clean)\n n_islands, island_ids = number_of_islands(camera, clean)\n\n timing_c = timing_parameters(\n camera[clean], image[clean], peakpos[clean], hillas_c, clean,\n )\n\n # store parameters for stereo reconstruction\n hillas_containers[telescope_id] = hillas_c\n\n # store timegradients for plotting\n # ASTRI has no timing in PROD3b, so we use skewness instead\n if camera.cam_id != 'ASTRICam':\n time_gradients[telescope_id] = timing_c.slope.value\n else:\n time_gradients[telescope_id] = hillas_c.skewness\n print(camera.cam_id, time_gradients[telescope_id])\n\n # make sure each telescope get's an arrow\n if abs(time_gradients[telescope_id]) < 0.2:\n time_gradients[telescope_id] = 1\n\n # ignore events with less than two telescopes\n if len(hillas_containers) < 2:\n continue\n array_pointing = SkyCoord(\n az=event.mcheader.run_array_direction[0],\n alt=event.mcheader.run_array_direction[1],\n frame=horizon_frame\n )\n stereo = reco.predict(\n hillas_containers,\n event.inst,\n array_pointing,\n )\n\n plt.figure()\n angle_offset = event.mcheader.run_array_direction[0]\n disp = ArrayDisplay(event.inst.subarray)\n\n disp.set_vector_hillas(\n hillas_containers,\n time_gradient=time_gradients,\n angle_offset=angle_offset,\n length=500\n )\n plt.scatter(\n event.mc.core_x, event.mc.core_y,\n s=200, c='k', marker='x', label='True Impact',\n )\n plt.scatter(\n stereo.core_x, stereo.core_y,\n s=200, c='r', marker='x', label='Estimated Impact',\n )\n\n plt.legend()\n plt.show()\n",
"import numpy as np\nimport pytest\nfrom traitlets.config import Config\n\nfrom ctapipe.image import ImageCleaner\nfrom ctapipe.instrument import TelescopeDescription, SubarrayDescription\n\n\n@pytest.mark.parametrize(\"method\", ImageCleaner.non_abstract_subclasses().keys())\ndef test_image_cleaner(method):\n \"\"\" Test that we can construct and use a component-based ImageCleaner\"\"\"\n\n config = Config(\n {\n \"TailcutsImageCleaner\": {\n \"boundary_threshold_pe\": 5.0,\n \"picture_threshold_pe\": 10.0,\n },\n \"MARSImageCleaner\": {\n \"boundary_threshold_pe\": 5.0,\n \"picture_threshold_pe\": 10.0,\n },\n \"FACTImageCleaner\": {\n \"boundary_threshold_pe\": 5.0,\n \"picture_threshold_pe\": 10.0,\n \"time_limit_ns\": 6.0,\n },\n }\n )\n\n tel = TelescopeDescription.from_name(\"MST\", \"NectarCam\")\n subarray = SubarrayDescription(\n name=\"test\", tel_positions={1: None}, tel_descriptions={1: tel}\n )\n\n clean = ImageCleaner.from_name(method, config=config, subarray=subarray)\n\n image = np.zeros_like(tel.camera.pix_x.value, dtype=np.float)\n image[10:30] = 20.0\n image[31:40] = 8.0\n times = np.linspace(-5, 10, image.shape[0])\n\n mask = clean(tel_id=1, image=image, arrival_times=times)\n\n # we're not testing the algorithm here, just that it does something (for the\n # algorithm tests, see test_cleaning.py\n assert np.count_nonzero(mask) > 0\n\n\n@pytest.mark.parametrize(\"method\", ImageCleaner.non_abstract_subclasses().keys())\ndef test_image_cleaner_no_subarray(method):\n with pytest.raises(TypeError):\n ImageCleaner.from_name(method)\n"
] |
[
[
"numpy.full",
"numpy.empty",
"numpy.zeros",
"numpy.ones",
"numpy.nanmin",
"numpy.arange",
"numpy.sqrt",
"numpy.nanmax"
],
[
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
],
[
"numpy.zeros_like",
"numpy.count_nonzero",
"numpy.linspace"
]
] |
cameronaaron/unintended-ml-bias-analysis
|
[
"cdf3eb08398b367b4b05245b42551eb03aa848e2"
] |
[
"unintended_ml_bias/model_bias_analysis.py"
] |
[
"\"\"\"Analysis of model bias.\n\nWe look at differences in model scores as a way to compare bias in different\nmodels.\n\nThe functions in this file expect scored data in a data frame with columns:\n\n<text_col>: Column containing text of the example. This column name is\n passed in as a parameter of any function that needs access to it.\n<label_col>: Column containing a boolean representing the example's\n true label.\n<model name>: One column per model, each containing the model's predicted\n score for this example.\n<subgroup>: One column per subgroup to evaluate bias for. These columns\n may be generated by add_subgroup_columns_from_text (when being \"in\"\n a subgroup means the text contains a certain term), or may be\n additional label columns from the original test data.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport datetime\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport re\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\nimport scipy.stats as stats\n\n\ndef compute_auc(y_true, y_pred):\n try:\n return metrics.roc_auc_score(y_true, y_pred)\n except ValueError:\n return np.nan\n\n\n### Per-subgroup pinned AUC analysis.\ndef model_family_auc(dataset, model_names, label_col):\n aucs = [\n compute_auc(dataset[label_col], dataset[model_name])\n for model_name in model_names\n ]\n return {\n 'aucs': aucs,\n 'mean': np.mean(aucs),\n 'median': np.median(aucs),\n 'std': np.std(aucs),\n }\n\n\ndef plot_model_family_auc(dataset, model_names, label_col, min_auc=0.9):\n result = model_family_auc(dataset, model_names, label_col)\n print('mean AUC:', result['mean'])\n print('median:', result['median'])\n print('stddev:', result['std'])\n plt.hist(result['aucs'])\n plt.gca().set_xlim([min_auc, 1.0])\n plt.show()\n return result\n\n\ndef read_identity_terms(identity_terms_path):\n with open(identity_terms_path) as f:\n return [term.strip() for term in f.readlines()]\n\n\ndef add_subgroup_columns_from_text(df, text_column, subgroups):\n \"\"\"Adds a boolean column for each subgroup to the data frame.\n\n New column contains True if the text contains that subgroup term.\n \"\"\"\n for term in subgroups:\n df[term] = df[text_column].apply(lambda x: bool(re.search(u'\\\\b{}\\\\b'.format(term), x, flags=re.IGNORECASE)))\n\n\ndef balanced_subgroup_subset(df, subgroup):\n \"\"\"Returns data subset containing subgroup balanced with sample of other data.\n\n We draw a random sample from the dataset of other examples because we don't\n care about the model's ability to distinguish toxic from non-toxic just\n within the subgroup-specific dataset, but rather its ability to distinguish\n for\n the subgroup-specific subset within the context of a larger distribution of\n data.\n\n Note: Uses a fixed random seed for reproducability.\n \"\"\"\n subgroup_df = df[df[subgroup]]\n nonsubgroup_df = df[~df[subgroup]].sample(len(subgroup_df), random_state=25)\n combined = pd.concat([subgroup_df, nonsubgroup_df])\n return combined\n\n\ndef model_family_name(model_names):\n \"\"\"Given a list of model names, returns the common prefix.\"\"\"\n prefix = os.path.commonprefix(model_names)\n if not prefix:\n raise ValueError(\"couldn't determine family name from model names\")\n return prefix.strip('_')\n\n\ndef normalized_mwu(data1, data2, model_name):\n \"\"\"Returns the number of pairs where the datapoint in data1 has a greater score than that from data2.\"\"\"\n scores_1 = data1[model_name]\n scores_2 = data2[model_name]\n n1 = len(scores_1)\n n2 = len(scores_2)\n if n1 == 0 or n2 == 0:\n return None\n u, _ = stats.mannwhitneyu(scores_1, scores_2, alternative = 'less')\n return u/(n1*n2)\n\ndef average_squared_equality_gap(df, subgroup, label, model_name):\n \"\"\"Returns the positive and negative ASEG metrics.\"\"\"\n subgroup_df = df[df[subgroup]]\n background_df = df[~df[subgroup]]\n if len(subgroup_df) == 0 or len(background_df) == 0:\n return None, None\n thresholds = np.linspace(1.0, 0.0, num = 1000)\n s_fpr, s_tpr = positive_rates(subgroup_df, model_name, label, thresholds)\n b_fpr, b_tpr = positive_rates(background_df, model_name, label, thresholds)\n if s_fpr and s_tpr and b_fpr and b_tpr:\n return squared_diff_integral(s_tpr, b_tpr), squared_diff_integral(s_fpr, b_fpr)\n return None, None\n\ndef squared_diff_integral(y, x):\n return np.trapz(np.square(np.subtract(y,x)), x)\n\ndef compute_within_negative_label_mwu(df, subgroup, label, model_name):\n mwu = normalized_mwu(df[~df[subgroup] & ~df[label]],\n df[df[subgroup] & ~df[label]],\n model_name)\n if mwu is None:\n return None\n return 0.5 - mwu\n\n\ndef compute_within_positive_label_mwu(df, subgroup, label, model_name):\n mwu = normalized_mwu(df[~df[subgroup] & df[label]],\n df[df[subgroup] & df[label]],\n model_name)\n if mwu is None:\n return None\n return 0.5 - mwu\n\n\ndef compute_within_subgroup_mwu(df, subgroup, label, model_name):\n mwu = normalized_mwu(df[df[subgroup] & ~df[label]],\n df[df[subgroup] & df[label]],\n model_name)\n if mwu is None:\n return None\n return 1 - mwu\n\n\ndef compute_cross_subgroup_negative_mwu(df, subgroup, label, model_name):\n mwu = normalized_mwu(df[df[subgroup] & ~df[label]],\n df[~df[subgroup] & df[label]],\n model_name)\n if mwu is None:\n return None\n return 1 - mwu\n\n\ndef compute_cross_subgroup_positive_mwu(df, subgroup, label, model_name):\n mwu = normalized_mwu(df[~df[subgroup] & ~df[label]],\n df[df[subgroup] & df[label]],\n model_name)\n if mwu is None:\n return None\n return 1 - mwu\n\ndef compute_normalized_pinned_auc(df, subgroup, label, model_name):\n within_subgroup = compute_within_subgroup_mwu(df, subgroup, label, model_name)\n cross_1 = compute_cross_subgroup_negative_mwu(df, subgroup, label, model_name)\n cross_2 = compute_cross_subgroup_positive_mwu(df, subgroup, label, model_name)\n if within_subgroup is None or cross_1 is None or cross_2 is None:\n return None\n return np.mean([within_subgroup, cross_1, cross_2])\n\ndef per_subgroup_aucs(dataset, subgroups, model_families, label_col, include_asegs=False):\n \"\"\"Computes per-subgroup 'pinned' AUC scores for each model family.\"\"\"\n records = []\n for subgroup in subgroups:\n subgroup_subset = balanced_subgroup_subset(dataset, subgroup)\n subgroup_record = {\n 'subgroup': subgroup,\n 'subset_size': len(subgroup_subset)\n }\n for model_family in model_families:\n family_name = model_family_name(model_family)\n aucs = [\n compute_auc(subgroup_subset[label_col], subgroup_subset[model_name])\n for model_name in model_family\n ]\n within_negative_label_mwus = [\n compute_within_negative_label_mwu(dataset, subgroup, label_col, model_name)\n for model_name in model_family\n ]\n within_positive_label_mwus = [\n compute_within_positive_label_mwu(dataset, subgroup, label_col, model_name)\n for model_name in model_family\n ]\n within_subgroup_mwus = [\n compute_within_subgroup_mwu(dataset, subgroup, label_col, model_name)\n for model_name in model_family\n ]\n cross_subgroup_negative_mwus = [\n compute_cross_subgroup_negative_mwu(dataset, subgroup, label_col, model_name)\n for model_name in model_family\n ]\n cross_subgroup_positive_mwus = [\n compute_cross_subgroup_positive_mwu(dataset, subgroup, label_col, model_name)\n for model_name in model_family\n ]\n normalized_pinned_aucs = [\n compute_normalized_pinned_auc(dataset, subgroup, label_col, model_name)\n for model_name in model_family\n ]\n subgroup_record.update({\n family_name + '_mean': np.mean(aucs),\n family_name + '_median': np.median(aucs),\n family_name + '_std': np.std(aucs),\n family_name + '_aucs': aucs,\n family_name + '_within_negative_label_mwus': within_negative_label_mwus,\n family_name + '_within_positive_label_mwus': within_positive_label_mwus,\n family_name + '_within_subgroup_mwus': within_subgroup_mwus,\n family_name + '_cross_subgroup_negative_mwus': cross_subgroup_negative_mwus,\n family_name + '_cross_subgroup_positive_mwus': cross_subgroup_positive_mwus,\n family_name + '_normalized_pinned_aucs': normalized_pinned_aucs\n })\n if include_asegs:\n positive_asegs, negative_asegs = zip(*[\n average_squared_equality_gap(dataset, subgroup, label_col, model_name)\n for model_name in model_family\n ])\n subgroup_record.update({\n family_name + '_positive_asegs': positive_asegs,\n family_name + '_negative_asegs': negative_asegs\n })\n records.append(subgroup_record)\n return pd.DataFrame(records)\n\n### Equality of opportunity negative rates analysis.\n\n\ndef confusion_matrix_counts(df, score_col, label_col, threshold):\n return {\n 'tp': len(df[(df[score_col] >= threshold) & (df[label_col] == True)]),\n 'tn': len(df[(df[score_col] < threshold) & (df[label_col] == False)]),\n 'fp': len(df[(df[score_col] >= threshold) & (df[label_col] == False)]),\n 'fn': len(df[(df[score_col] < threshold) & (df[label_col] == True)]),\n }\n\ndef positive_rates(df, score_col, label_col, thresholds):\n tpr = []\n fpr = []\n for threshold in thresholds:\n confusion = confusion_matrix_counts(df, score_col, label_col, threshold)\n if (confusion['tp'] + confusion['fn'] == 0 or\n confusion['fp'] + confusion['tn'] == 0):\n return None, None\n tpr.append(confusion['tp'] / (confusion['tp'] + confusion['fn']))\n fpr.append(confusion['fp'] / (confusion['fp'] + confusion['tn']))\n return fpr, tpr\n\n# https://en.wikipedia.org/wiki/Confusion_matrix\ndef compute_confusion_rates(df, score_col, label_col, threshold):\n confusion = confusion_matrix_counts(df, score_col, label_col, threshold)\n actual_positives = confusion['tp'] + confusion['fn']\n actual_negatives = confusion['tn'] + confusion['fp']\n # True positive rate, sensitivity, recall.\n tpr = confusion['tp'] / actual_positives\n # True negative rate, specificity.\n tnr = confusion['tn'] / actual_negatives\n # False positive rate, fall-out.\n fpr = 1 - tnr\n # False negative rate, miss rate.\n fnr = 1 - tpr\n # Precision, positive predictive value.\n precision = confusion['tp'] / (confusion['tp'] + confusion['fp'])\n return {\n 'tpr': tpr,\n 'tnr': tnr,\n 'fpr': fpr,\n 'fnr': fnr,\n 'precision': precision,\n 'recall': tpr,\n }\n\n\ndef compute_equal_error_rate(df, score_col, label_col, num_thresholds=101):\n \"\"\"Returns threshold where the false negative and false positive counts are equal.\"\"\"\n # Note: I'm not sure if this should be based on the false positive/negative\n # *counts*, or the *rates*. However, they should be equivalent for balanced\n # datasets.\n thresholds = np.linspace(0, 1, num_thresholds)\n min_threshold = None\n min_confusion_matrix = None\n min_diff = float('inf')\n for threshold in thresholds:\n confusion_matrix = confusion_matrix_counts(df, score_col, label_col,\n threshold)\n difference = abs(confusion_matrix['fn'] - confusion_matrix['fp'])\n if difference <= min_diff:\n min_diff = difference\n min_confusion_matrix = confusion_matrix\n min_threshold = threshold\n else:\n # min_diff should be monotonically non-decreasing, so once it\n # increases we can break. Yes, we could do a binary search instead.\n break\n return {\n 'threshold': min_threshold,\n 'confusion_matrix': min_confusion_matrix,\n }\n\n\ndef per_model_eer(dataset, label_col, model_names, num_eer_thresholds=101):\n \"\"\"Computes the equal error rate for every model on the given dataset.\"\"\"\n model_name_to_eer = {}\n for model_name in model_names:\n eer = compute_equal_error_rate(dataset, model_name, label_col,\n num_eer_thresholds)\n model_name_to_eer[model_name] = eer['threshold']\n return model_name_to_eer\n\n\ndef per_subgroup_negative_rates(df, subgroups, model_families, threshold,\n label_col):\n \"\"\"Computes per-subgroup true/false negative rates for all model families.\n\n Args:\n df: dataset to compute rates on.\n subgroups: negative rates are computed on subsets of the dataset\n containing\n each subgroup.\n label_col: column in df containing the boolean label.\n model_families: list of model families; each model family is a list of\n model names in the family.\n threshold: threshold to use to compute negative rates. Can either be a\n float, or a dictionary mapping model name to float threshold in order\n to use a different threshold for each model.\n\n Returns:\n DataFrame with per-subgroup false/true negative rates for each model\n family.\n Results are summarized across each model family, giving mean, median,\n and standard deviation of each negative rate.\n \"\"\"\n records = []\n for subgroup in subgroups:\n if subgroup is None:\n subgroup_subset = df\n else:\n subgroup_subset = df[df[subgroup]]\n subgroup_record = {\n 'subgroup': subgroup,\n 'subset_size': len(subgroup_subset)\n }\n for model_family in model_families:\n family_name = model_family_name(model_family)\n family_rates = []\n for model_name in model_family:\n model_threshold = (\n threshold[model_name] if isinstance(threshold, dict) else threshold)\n assert isinstance(model_threshold, float)\n model_rates = compute_confusion_rates(subgroup_subset, model_name,\n label_col, model_threshold)\n family_rates.append(model_rates)\n tnrs, fnrs = ([rates['tnr'] for rates in family_rates],\n [rates['fnr'] for rates in family_rates])\n subgroup_record.update({\n family_name + '_tnr_median': np.median(tnrs),\n family_name + '_tnr_mean': np.mean(tnrs),\n family_name + '_tnr_std': np.std(tnrs),\n family_name + '_tnr_values': tnrs,\n family_name + '_fnr_median': np.median(fnrs),\n family_name + '_fnr_mean': np.mean(fnrs),\n family_name + '_fnr_std': np.std(fnrs),\n family_name + '_fnr_values': fnrs,\n })\n records.append(subgroup_record)\n return pd.DataFrame(records)\n\n\n### Summary metrics\ndef diff_per_subgroup_from_overall(overall_metrics, per_subgroup_metrics,\n model_families, metric_column,\n squared_error):\n \"\"\"Computes the sum of differences between the per-subgroup metric values and the overall values\n\n summed over all subgroups and models. i.e. sum(|overall_i -\n per-subgroup_i,t|) for i in model\n instances and t in subgroups.\n\n Args:\n overall_metrics: dict of model familiy to list of score values for the\n overall\n dataset (one per model instance).\n per_subgroup_metrics: DataFrame of scored results, one subgroup per row.\n Expected to have\n a column named model family name + metric column, which contains a\n list of\n one score per model instance.\n model_families: list of model families; each model family is a list of\n model names in the family.\n metric_column: column name suffix in the per_subgroup_metrics df where the\n per-subgroup data\n to be diffed is stored.\n squared_error: boolean indicating whether to use squared error or just\n absolute difference.\n\n Returns:\n A dictionary of model family name to sum of differences value for that\n model family.\n \"\"\"\n\n def calculate_error(overall_score, per_group_score):\n diff = overall_score - per_group_score\n return diff**2 if squared_error else abs(diff)\n\n diffs = {}\n for fams in model_families:\n family_name = model_family_name(fams)\n family_overall_metrics = overall_metrics[family_name]\n metric_diff_sum = 0.0\n diffs[family_name] = 0.0\n # Loop over the subgroups. one_subgroup_metric_list is a list of the per-subgroup\n # values, one per model instance.\n for one_subgroup_metric_list in per_subgroup_metrics[family_name\n + metric_column]:\n # Zips the overall scores with the per-subgroup scores, pairing results\n # from the same model instance, then diffs those pairs and sums.\n per_subgroup_metric_diffs = [\n calculate_error(overall_score, per_subgroup_score)\n for overall_score, per_subgroup_score in zip(family_overall_metrics,\n one_subgroup_metric_list)\n ]\n diffs[family_name] += sum(per_subgroup_metric_diffs)\n return diffs\n\n\ndef per_subgroup_auc_diff_from_overall(dataset, subgroups, model_families,\n squared_error, normed_auc=False):\n \"\"\"Calculates the sum of differences between the per-subgroup pinned AUC and the overall AUC.\"\"\"\n per_subgroup_auc_results = per_subgroup_aucs(dataset, subgroups,\n model_families, 'label')\n overall_aucs = {}\n for fams in model_families:\n family_name = model_family_name(fams)\n overall_aucs[family_name] = model_family_auc(dataset, fams, 'label')['aucs']\n auc_column = '_normalized_pinned_aucs' if normed_auc else '_aucs'\n d = diff_per_subgroup_from_overall(overall_aucs, per_subgroup_auc_results,\n model_families, auc_column, squared_error)\n return pd.DataFrame(\n d.items(), columns=['model_family', 'pinned_auc_equality_difference'])\n\n\ndef per_subgroup_nr_diff_from_overall(df, subgroups, model_families, threshold,\n metric_column, squared_error):\n \"\"\"Calculates the sum of differences between the per-subgroup true or false negative rate and the overall rate.\"\"\"\n per_subgroup_nrs = per_subgroup_negative_rates(df, subgroups, model_families,\n threshold, 'label')\n all_nrs = per_subgroup_negative_rates(df, [None], model_families, threshold,\n 'label')\n overall_nrs = {}\n for fams in model_families:\n family_name = model_family_name(fams)\n overall_nrs[family_name] = all_nrs[family_name + metric_column][0]\n return diff_per_subgroup_from_overall(overall_nrs, per_subgroup_nrs,\n model_families, metric_column,\n squared_error)\n\n\ndef per_subgroup_fnr_diff_from_overall(df, subgroups, model_families, threshold,\n squared_error):\n \"\"\"Calculates the sum of differences between the per-subgroup false negative rate and the overall FNR.\"\"\"\n d = per_subgroup_nr_diff_from_overall(df, subgroups, model_families,\n threshold, '_fnr_values', squared_error)\n return pd.DataFrame(\n d.items(), columns=['model_family', 'fnr_equality_difference'])\n\n\ndef per_subgroup_tnr_diff_from_overall(df, subgroups, model_families, threshold,\n squared_error):\n \"\"\"Calculates the sum of differences between the per-subgroup true negative rate and the overall TNR.\"\"\"\n d = per_subgroup_nr_diff_from_overall(df, subgroups, model_families,\n threshold, '_tnr_values', squared_error)\n return pd.DataFrame(\n d.items(), columns=['model_family', 'tnr_equality_difference'])\n\n\n### Plotting.\n\n\ndef per_subgroup_scatterplots(df,\n subgroup_col,\n values_col,\n title='',\n y_lim=(0.8, 1.0),\n figsize=(15, 5),\n point_size=8,\n file_name='plot'):\n \"\"\"Displays a series of one-dimensional scatterplots, 1 scatterplot per subgroup.\n\n Args:\n df: DataFrame contain subgroup_col and values_col.\n subgroup_col: Column containing subgroups.\n values_col: Column containing collection of values to plot (each cell\n should contain a sequence of values, e.g. the AUCs for multiple models\n from the same family).\n title: Plot title.\n y_lim: Plot bounds for y axis.\n figsize: Plot figure size.\n \"\"\"\n fig = plt.figure(figsize=figsize)\n ax = fig.add_subplot(111)\n for i, (_index, row) in enumerate(df.iterrows()):\n # For each subgroup, we plot a 1D scatterplot. The x-value is the position\n # of the item in the dataframe. To change the ordering of the subgroups,\n # sort the dataframe before passing to this function.\n x = [i] * len(row[values_col])\n y = row[values_col]\n ax.scatter(x, y, s=point_size)\n ax.set_xticklabels(df[subgroup_col], rotation=90)\n ax.set_xticks(range(len(df)))\n ax.set_ylim(y_lim)\n ax.set_title(title)\n fig.tight_layout()\n fig.savefig('/tmp/%s_%s.eps' % (file_name, values_col), format='eps')\n"
] |
[
[
"numpy.median",
"pandas.DataFrame",
"matplotlib.pyplot.gca",
"scipy.stats.mannwhitneyu",
"numpy.mean",
"matplotlib.pyplot.figure",
"numpy.std",
"matplotlib.pyplot.hist",
"numpy.subtract",
"pandas.concat",
"matplotlib.pyplot.show",
"numpy.linspace",
"sklearn.metrics.roc_auc_score"
]
] |
ryangillard/P-CEAD
|
[
"d4e95fa17112af07eb99cd581470bd3146d1c8e5"
] |
[
"proganomaly_modules/training_module/trainer/export_berg.py"
] |
[
"# Copyright 2020 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nimport tensorflow as tf\n\n\nclass ExportBerg(object):\n \"\"\"Class used for exporting Berg model objects.\n \"\"\"\n def __init__(self):\n \"\"\"Instantiate instance of `ExportBerg`.\n \"\"\"\n pass\n\n def export_using_z_input_berg_encoded_generated_images(\n self,\n growth_idx,\n export_outputs,\n generator_model,\n encoded_generated_logits\n ):\n \"\"\"Adds encoded generated images to export for berg Z inputs.\n\n Args:\n growth_idx: int, index of growth phase to export.\n export_outputs: list, stores tensors for export output.\n generator_model: `Model`, generator model network.\n encoded_generated_logits: tensor, E(G(z)) of shape\n (batch_size, latent_size).\n \"\"\"\n encoded_generated_images = tf.identity(\n input=generator_model(\n inputs=encoded_generated_logits, training=False\n ),\n name=\"encoded_generated_images_{}\".format(\n growth_idx\n )\n )\n\n # shape = (batch_size, height, width, depth).\n # range = [-1., 1.].\n export_outputs.append(encoded_generated_images)\n\n def export_using_z_input_berg_encoded_generated_logits_and_beyond(\n self,\n growth_idx,\n export_dict,\n export_outputs,\n generator_model,\n encoder_model,\n generated_images\n ):\n \"\"\"Adds encoded generated logits & beyond to export for berg Z inputs.\n\n Args:\n growth_idx: int, index of growth phase to export.\n export_dict: dict, user passed export parameters.\n export_outputs: list, stores tensors for export output.\n generator_model: `Model`, generator model network.\n encoder_model: `Model`, encoder model network.\n generated_images: tensor, G(z) of shape\n (batch_size, height, width, depth).\n \"\"\"\n encoded_generated_logits = tf.identity(\n input=encoder_model(inputs=generated_images, training=False),\n name=\"encoded_generated_logits_{}\".format(growth_idx)\n )\n\n if export_dict[\"export_encoded_generated_logits\"]:\n # shape = (batch_size, 1).\n # range = (-inf, inf).\n export_outputs.append(encoded_generated_logits)\n\n if export_dict[\"export_encoded_generated_images\"]:\n self.export_using_z_input_berg_encoded_generated_images(\n growth_idx,\n export_outputs,\n generator_model,\n encoded_generated_logits\n )\n\n def export_using_z_input_berg_generated_images_and_beyond(\n self,\n growth_idx,\n export_dict,\n export_outputs,\n generator_model,\n encoder_model,\n Z\n ):\n \"\"\"Adds generated images & beyond to export for berg Z inputs.\n\n Args:\n growth_idx: int, index of growth phase to export.\n export_dict: dict, user passed export parameters.\n export_outputs: list, stores tensors for export output.\n generator_model: `Model`, generator model network.\n encoder_model: `Model`, encoder model network.\n Z: tensor, latent inputs of shape (batch_size, latent_size).\n \"\"\"\n generated_images = tf.identity(\n input=generator_model(inputs=Z, training=False),\n name=\"generated_images_{}\".format(growth_idx)\n )\n\n if export_dict[\"export_generated_images\"]:\n # shape = (batch_size, height, width, depth).\n # range = [-1., 1.].\n export_outputs.append(generated_images)\n\n if self.params[\"encoder\"][\"create\"] and any(\n [\n export_dict[\"export_encoded_generated_logits\"],\n export_dict[\"export_encoded_generated_images\"]\n ]\n ):\n self.export_using_z_input_berg_encoded_generated_logits_and_beyond(\n growth_idx,\n export_dict,\n export_outputs,\n generator_model,\n encoder_model,\n generated_images\n )\n\n def export_using_z_input_berg_z_and_beyond(\n self,\n growth_idx,\n export_dict,\n export_inputs_Z,\n export_outputs,\n generator_model,\n encoder_model\n ):\n \"\"\"Adds Z & beyond to export for berg Z inputs.\n\n Args:\n growth_idx: int, index of growth phase to export.\n export_dict: dict, user passed export parameters.\n export_inputs_Z: list, stores Z export inputs.\n export_outputs: list, stores tensors for export output.\n generator_model: `Model`, generator model network.\n encoder_model: `Model`, encoder model network.\n \"\"\"\n if self.params[\"training\"][\"subclass_models\"]:\n Z = generator_model.vector_to_image_input_layer\n else:\n Z = generator_model.inputs[0]\n export_inputs_Z.append(Z)\n\n if export_dict[\"export_Z\"]:\n # shape = (batch_size, generator_latent_size).\n # range = (-inf, inf).\n export_outputs.append(\n tf.identity(input=Z, name=\"Z_{}\".format(growth_idx))\n )\n\n if any(\n [\n export_dict[\"export_generated_images\"],\n (\n self.params[\"encoder\"][\"create\"] and\n any(\n [\n export_dict[\"export_encoded_generated_logits\"],\n export_dict[\"export_encoded_generated_images\"]\n ]\n )\n )\n ]\n ):\n self.export_using_z_input_berg_generated_images_and_beyond(\n growth_idx,\n export_dict,\n export_outputs,\n generator_model,\n encoder_model,\n Z\n )\n\n def export_using_z_input_berg(\n self,\n growth_idx,\n export_dict,\n export_inputs_Z,\n export_outputs,\n generator_model,\n encoder_model\n ):\n \"\"\"Adds inputs and outputs to export for berg Z inputs.\n\n Args:\n growth_idx: int, index of growth phase to export.\n export_dict: dict, user passed export parameters.\n export_inputs_Z: list, stores Z export inputs.\n export_outputs: list, stores tensors for export output.\n generator_model: `Model`, generator model network.\n encoder_model: `Model`, encoder model network.\n \"\"\"\n if any(\n [\n export_dict[\"export_Z\"],\n export_dict[\"export_generated_images\"],\n (\n self.params[\"encoder\"][\"create\"] and\n any(\n [\n export_dict[\"export_encoded_generated_logits\"],\n export_dict[\"export_encoded_generated_images\"]\n ]\n )\n )\n ]\n ):\n self.export_using_z_input_berg_z_and_beyond(\n growth_idx,\n export_dict,\n export_inputs_Z,\n export_outputs,\n generator_model,\n encoder_model\n )\n\n def export_using_query_images_input_berg_anomaly_images(\n self,\n growth_idx,\n export_dict,\n export_outputs,\n query_images,\n encoded_images\n ):\n \"\"\"Adds anomaly image outputs to export for berg query image inputs.\n\n Args:\n growth_idx: int, index of growth phase to export.\n export_dict: dict, user passed export parameters.\n export_outputs: list, stores tensors for export output.\n query_images: tensor, query image inputs of shape\n (batch_size, height, width, depth).\n encoded_images: tensor, G(E(x)) of shape\n (batch_size, height, width, depth).\n \"\"\"\n if export_dict[\"export_query_anomaly_images_sigmoid\"]:\n anomaly_images_sigmoid = self.anomaly_localization_sigmoid(\n query_images=query_images,\n encoded_images=encoded_images\n )\n\n anomaly_images_sigmoid = tf.identity(\n input=anomaly_images_sigmoid,\n name=\"query_anomaly_images_sigmoid_{}\".format(growth_idx)\n )\n\n # shape = (batch_size, height, width, depth).\n # range = [-1., 1.].\n export_outputs.append(anomaly_images_sigmoid)\n\n if export_dict[\"export_query_anomaly_images_linear\"]:\n anomaly_images_linear = self.anomaly_localization_linear(\n query_images=query_images,\n encoded_images=encoded_images\n )\n\n anomaly_images_linear = tf.identity(\n input=anomaly_images_linear,\n name=\"query_anomaly_images_linear_{}\".format(growth_idx)\n )\n\n # shape = (batch_size, height, width, depth).\n # range = [-1., 1.].\n export_outputs.append(anomaly_images_linear)\n\n def export_using_query_images_input_berg_mahalanobis_distance_images(\n self,\n growth_idx,\n export_dict,\n export_outputs,\n mahalanobis_distances\n ):\n \"\"\"Adds Mahalanobis distance image outputs to export for berg query image inputs.\n\n Args:\n growth_idx: int, index of growth phase to export.\n export_dict: dict, user passed export parameters.\n export_outputs: list, stores tensors for export output.\n mahalanobis_distances: tensor, Mahalanobis distance of image\n errors of shape (batch_size, height, width).\n \"\"\"\n if export_dict[\"export_query_mahalanobis_distance_images_sigmoid\"]:\n sigmoid_mahalanobis_distances_sigmoid = tf.math.sigmoid(\n x=mahalanobis_distances\n )\n\n mahalanobis_distance_images_sigmoid = (\n self.zero_center_sigmoid_absolute_values(\n absolute_values=sigmoid_mahalanobis_distances_sigmoid\n )\n )\n\n mahalanobis_distance_images_sigmoid = tf.expand_dims(\n input=mahalanobis_distance_images_sigmoid,\n axis=-1,\n name=\"query_mahalanobis_distance_images_sigmoid_{}\".format(\n growth_idx\n )\n )\n\n # shape = (batch_size, height, width, 1).\n # range = [-1., 1.].\n export_outputs.append(mahalanobis_distance_images_sigmoid)\n\n if export_dict[\"export_query_mahalanobis_distance_images_linear\"]:\n # Min-max normalize scores to scale range to [0, 1].\n normalized_distances = self.minmax_normalization(\n X=tf.expand_dims(input=mahalanobis_distances, axis=-1)\n )\n\n # Scale images to [-1, 1).\n mahalanobis_distance_images_linear = (\n normalized_distances * 2. - 1.\n )\n\n mahalanobis_distance_images_linear = tf.identity(\n input=mahalanobis_distance_images_linear,\n name=\"query_mahalanobis_distance_images_linear_{}\".format(\n growth_idx\n )\n )\n\n # shape = (batch_size, height, width, 1).\n # range = [-1., 1.].\n export_outputs.append(mahalanobis_distance_images_linear)\n\n def export_using_query_images_input_berg_pixel_anomaly_flag_counts_and_percentages(\n self,\n growth_idx,\n export_dict,\n export_outputs,\n pixel_anomaly_flag_images\n ):\n \"\"\"Adds pixel anomaly flag counts & percentages to export for berg query image inputs.\n\n Args:\n growth_idx: int, index of growth phase to export.\n export_dict: dict, user passed export parameters.\n export_outputs: list, stores tensors for export output.\n pixel_anomaly_flag_images: tensor, pixel anomaly flags image of\n shape (batch_size, height, width, 1).\n \"\"\"\n counts = tf.math.reduce_sum(\n input_tensor=tf.cast(\n x=pixel_anomaly_flag_images == 1,\n dtype=tf.int32\n ),\n axis=(1, 2, 3),\n name=\"query_pixel_anomaly_flag_counts\"\n )\n\n if export_dict[\"export_query_pixel_anomaly_flag_counts\"]:\n # shape = (batch_size,).\n # range = [0, inf).\n export_outputs.append(counts)\n\n if export_dict[\"export_query_pixel_anomaly_flag_percentages\"]:\n # shape = (batch_size,).\n # range = [0., inf).\n export_outputs.append(\n tf.identity(\n input=tf.math.divide_no_nan(\n x=tf.cast(x=counts, dtype=tf.float32),\n y=tf.cast(\n x=tf.math.reduce_prod(\n input_tensor=(\n pixel_anomaly_flag_images.shape[1:]\n )\n ),\n dtype=tf.float32\n )\n ),\n name=\"query_pixel_anomaly_flag_percentiles\"\n )\n )\n \n\n def export_using_query_images_input_berg_pixel_anomaly_flag_images_and_beyond(\n self,\n growth_idx,\n export_dict,\n export_outputs,\n mahalanobis_distances\n ):\n \"\"\"Adds pixel anomaly flag image outputs to export for berg query image inputs.\n\n Args:\n growth_idx: int, index of growth phase to export.\n export_dict: dict, user passed export parameters.\n export_outputs: list, stores tensors for export output.\n mahalanobis_distances: tensor, Mahalanobis distance of image\n errors of shape (batch_size, height, width).\n \"\"\"\n pixel_anomaly_flag_images = tf.expand_dims(\n input=tf.where(\n condition=tf.greater(\n x=mahalanobis_distances, y=self.dynamic_threshold\n ),\n x=tf.ones_like(input=mahalanobis_distances, dtype=tf.float32),\n y=-tf.ones_like(input=mahalanobis_distances, dtype=tf.float32)\n ),\n axis=-1,\n name=\"query_pixel_anomaly_flag_images_{}\".format(growth_idx)\n )\n\n # shape = (batch_size, height, width, 1).\n # range = [-1., 1.].\n export_outputs.append(pixel_anomaly_flag_images)\n\n if any(\n [\n export_dict[\"export_query_pixel_anomaly_flag_counts\"],\n export_dict[\"export_query_pixel_anomaly_flag_percentages\"]\n ]\n ):\n self.export_using_query_images_input_berg_pixel_anomaly_flag_counts_and_percentages(\n growth_idx,\n export_dict,\n export_outputs,\n pixel_anomaly_flag_images\n )\n\n def export_using_query_images_input_berg_mahalanobis_distances_and_beyond(\n self,\n growth_idx,\n export_dict,\n export_outputs,\n query_images,\n encoded_images\n ):\n \"\"\"Adds Mahalanobis distance outputs & beyond to export for berg query image inputs.\n\n Args:\n growth_idx: int, index of growth phase to export.\n export_dict: dict, user passed export parameters.\n export_outputs: list, stores tensors for export output.\n query_images: tensor, query image inputs of shape\n (batch_size, height, width, depth).\n encoded_images: tensor, G(E(x)) of shape\n (batch_size, height, width, depth).\n \"\"\"\n errors = self.reshape_image_absolute_errors(\n errors=tf.abs(x=query_images - encoded_images)\n )\n\n mahalanobis_distances = self.batch_mahalanobis_distance(\n batch_matrix=errors,\n mu=self.network_objects[\"error_distribution\"].col_means_vector\n )\n\n mahalanobis_distances_reshaped = tf.reshape(\n tensor=mahalanobis_distances,\n shape=(-1, query_images.shape[1], query_images.shape[2]),\n name=\"query_mahalanobis_distances_{}\".format(growth_idx)\n )\n\n # shape = (batch_size, height, width).\n # range = (0., inf).\n export_outputs.append(mahalanobis_distances_reshaped)\n\n if any(\n [\n export_dict[\"export_query_mahalanobis_distance_images_sigmoid\"],\n export_dict[\"export_query_mahalanobis_distance_images_linear\"]\n ]\n ):\n self.export_using_query_images_input_berg_mahalanobis_distance_images(\n growth_idx,\n export_dict,\n export_outputs,\n mahalanobis_distances=mahalanobis_distances_reshaped\n )\n\n if (\n self.training_phase.numpy() > 1 and any(\n [\n export_dict[\"export_query_pixel_anomaly_flag_images\"],\n export_dict[\"export_query_pixel_anomaly_flag_counts\"],\n export_dict[\"export_query_pixel_anomaly_flag_percentages\"]\n ]\n )\n ):\n self.export_using_query_images_input_berg_pixel_anomaly_flag_images_and_beyond(\n growth_idx,\n export_dict,\n export_outputs,\n mahalanobis_distances=mahalanobis_distances_reshaped\n )\n\n def export_using_query_images_input_berg_anomaly_scores_and_flags(\n self,\n growth_idx,\n export_dict,\n export_outputs,\n query_images,\n encoded_logits,\n encoded_images\n ):\n \"\"\"Adds anomaly score & flag outputs to export for berg query image inputs.\n\n Args:\n growth_idx: int, index of growth phase to export.\n export_dict: dict, user passed export parameters.\n export_outputs: list, stores tensors for export output.\n query_images: tensor, query image inputs of shape\n (batch_size, height, width, depth).\n encoded_logits: tensor, E(x) of shape (batch_size, latent_size).\n encoded_images: tensor, G(E(x)) of shape\n (batch_size, height, width, depth).\n \"\"\"\n anomaly_scores, anomaly_flags = self.anomaly_detection(\n query_images=query_images,\n encoded_logits=encoded_logits,\n encoded_images=encoded_images\n )\n\n if export_dict[\"export_query_anomaly_scores\"]:\n # shape = (batch_size,).\n # range = (-inf, inf).\n export_outputs.append(\n tf.identity(\n input=anomaly_scores,\n name=\"query_anomaly_scores_{}\".format(\n growth_idx\n )\n )\n )\n\n if export_dict[\"export_query_anomaly_flags\"]:\n # shape = (batch_size,).\n # range = [0, 1].\n export_outputs.append(\n tf.identity(\n input=anomaly_flags,\n name=\"query_anomaly_flags_{}\".format(\n growth_idx\n )\n )\n )\n\n def export_using_query_images_input_berg_encoded_images_and_beyond(\n self,\n growth_idx,\n export_dict,\n export_outputs,\n generator_model,\n query_images,\n encoded_logits\n ):\n \"\"\"Adds encoded image outputs & beyond to export for berg query image inputs.\n\n Args:\n growth_idx: int, index of growth phase to export.\n export_dict: dict, user passed export parameters.\n export_outputs: list, stores tensors for export output.\n generator_model: `Model`, generator model network.\n query_images: tensor, query image inputs of shape\n (batch_size, height, width, depth).\n encoded_logits: tensor, E(x) of shape (batch_size, latent_size).\n \"\"\"\n encoded_images = tf.identity(\n input=generator_model(inputs=encoded_logits, training=False),\n name=\"query_encoded_images_{}\".format(growth_idx)\n )\n\n if export_dict[\"export_query_encoded_images\"]:\n # shape = (batch_size, height, width, depth).\n # range = [-1., 1.].\n export_outputs.append(encoded_images)\n\n if any(\n [\n export_dict[\"export_query_anomaly_images_sigmoid\"],\n export_dict[\"export_query_anomaly_images_linear\"]\n ]\n ):\n self.export_using_query_images_input_berg_anomaly_images(\n growth_idx,\n export_dict,\n export_outputs,\n query_images,\n encoded_images\n )\n\n if any(\n [\n (\n self.training_phase.numpy() > 0 and any(\n [\n export_dict[\"export_query_mahalanobis_distances\"],\n export_dict[\"export_query_mahalanobis_distance_images_sigmoid\"],\n export_dict[\"export_query_mahalanobis_distance_images_linear\"]\n ]\n )\n ),\n (\n self.training_phase.numpy() > 1 and any(\n [\n export_dict[\"export_query_pixel_anomaly_flag_images\"],\n export_dict[\"export_query_pixel_anomaly_flag_counts\"],\n export_dict[\"export_query_pixel_anomaly_flag_percentages\"]\n ]\n )\n )\n ]\n ):\n self.export_using_query_images_input_berg_mahalanobis_distances_and_beyond(\n growth_idx,\n export_dict,\n export_outputs,\n query_images,\n encoded_images\n )\n\n if any(\n [\n export_dict[\"export_query_anomaly_scores\"],\n export_dict[\"export_query_anomaly_flags\"]\n ]\n ):\n self.export_using_query_images_input_berg_anomaly_scores_and_flags(\n growth_idx,\n export_dict,\n export_outputs,\n query_images,\n encoded_logits,\n encoded_images\n )\n\n def export_using_query_images_input_berg_encoded_logits_and_beyond(\n self,\n growth_idx,\n export_dict,\n export_outputs,\n generator_model,\n encoder_model,\n query_images\n ):\n \"\"\"Adds encoded logit outputs & beyond to export for berg query image inputs.\n\n Args:\n growth_idx: int, index of growth phase to export.\n export_dict: dict, user passed export parameters.\n export_outputs: list, stores tensors for export output.\n generator_model: `Model`, generator model network.\n encoder_model: `Model`, encoder model network.\n query_images: tensor, query image inputs of shape\n (batch_size, height, width, depth).\n \"\"\"\n encoded_logits = tf.identity(\n input=encoder_model(inputs=query_images, training=False),\n name=\"query_encoded_logits_{}\".format(growth_idx)\n )\n\n if export_dict[\"export_query_encoded_logits\"]:\n # shape = (batch_size, generator_latent_size).\n # range = (-inf, inf).\n export_outputs.append(encoded_logits)\n\n if any(\n [\n export_dict[\"export_query_encoded_images\"],\n export_dict[\"export_query_anomaly_images_sigmoid\"],\n export_dict[\"export_query_anomaly_images_linear\"],\n (\n self.training_phase.numpy() > 0 and any(\n [\n export_dict[\"export_query_mahalanobis_distances\"],\n export_dict[\"export_query_mahalanobis_distance_images_sigmoid\"],\n export_dict[\"export_query_mahalanobis_distance_images_linear\"]\n ]\n )\n ),\n (\n self.training_phase.numpy() > 1 and any(\n [\n export_dict[\"export_query_pixel_anomaly_flag_images\"],\n export_dict[\"export_query_pixel_anomaly_flag_counts\"],\n export_dict[\"export_query_pixel_anomaly_flag_percentages\"]\n ]\n )\n ),\n export_dict[\"export_query_anomaly_scores\"],\n export_dict[\"export_query_anomaly_flags\"]\n ]\n ):\n self.export_using_query_images_input_berg_encoded_images_and_beyond(\n growth_idx,\n export_dict,\n export_outputs,\n generator_model,\n query_images,\n encoded_logits\n )\n\n def export_using_query_images_input_berg_query_images_and_beyond(\n self,\n growth_idx,\n export_dict,\n export_inputs_query_images,\n export_outputs,\n generator_model,\n encoder_model\n ):\n \"\"\"Adds query image outputs & beyond to export for berg query image inputs.\n\n Args:\n growth_idx: int, index of growth phase to export.\n export_dict: dict, user passed export parameters.\n export_inputs_query_images: list, stores query image export\n inputs.\n export_outputs: list, stores tensors for export output.\n generator_model: `Model`, generator model network.\n encoder_model: `Model`, encoder model network.\n \"\"\"\n # x.\n if self.params[\"training\"][\"subclass_models\"]:\n block_idx = (growth_idx + 1) // 2\n query_images = (\n encoder_model.image_to_vector_input_layers[block_idx]\n )\n else:\n query_images = encoder_model.inputs[0]\n export_inputs_query_images.append(query_images)\n\n if export_dict[\"export_query_images\"]:\n # shape = (batch_size, height, width, depth).\n # range = [-1., 1.].\n export_outputs.append(\n tf.identity(\n input=query_images, name=\"query_images_{}\".format(\n growth_idx\n )\n )\n )\n\n if self.params[\"encoder\"][\"create\"] and any(\n [\n export_dict[\"export_query_encoded_logits\"],\n export_dict[\"export_query_encoded_images\"],\n export_dict[\"export_query_anomaly_images_sigmoid\"],\n export_dict[\"export_query_anomaly_images_linear\"],\n (\n self.training_phase.numpy() > 0 and any(\n [\n export_dict[\"export_query_mahalanobis_distances\"],\n export_dict[\"export_query_mahalanobis_distance_images_sigmoid\"],\n export_dict[\"export_query_mahalanobis_distance_images_linear\"]\n ]\n )\n ),\n (\n self.training_phase.numpy() > 1 and any(\n [\n export_dict[\"export_query_pixel_anomaly_flag_images\"],\n export_dict[\"export_query_pixel_anomaly_flag_counts\"],\n export_dict[\"export_query_pixel_anomaly_flag_percentages\"]\n ]\n )\n ),\n export_dict[\"export_query_anomaly_scores\"],\n export_dict[\"export_query_anomaly_flags\"]\n ]\n ):\n self.export_using_query_images_input_berg_encoded_logits_and_beyond(\n growth_idx,\n export_dict,\n export_outputs,\n generator_model,\n encoder_model,\n query_images\n )\n\n def export_using_query_images_input_berg(\n self,\n growth_idx,\n export_dict,\n export_inputs_query_images,\n export_outputs,\n generator_model,\n encoder_model\n ):\n \"\"\"Adds inputs and outputs to export for berg query image inputs.\n\n Args:\n growth_idx: int, index of growth phase to export.\n export_dict: dict, user passed export parameters.\n export_inputs_query_images: list, stores query image export\n inputs.\n export_outputs: list, stores tensors for export output.\n generator_model: `Model`, generator model network.\n encoder_model: `Model`, encoder model network.\n \"\"\"\n if any(\n [\n export_dict[\"export_query_images\"],\n export_dict[\"export_query_encoded_logits\"],\n export_dict[\"export_query_encoded_images\"],\n export_dict[\"export_query_anomaly_images_sigmoid\"],\n export_dict[\"export_query_anomaly_images_linear\"],\n (\n self.training_phase.numpy() > 0 and any(\n [\n export_dict[\"export_query_mahalanobis_distances\"],\n export_dict[\"export_query_mahalanobis_distance_images_sigmoid\"],\n export_dict[\"export_query_mahalanobis_distance_images_linear\"]\n ]\n )\n ),\n (\n self.training_phase.numpy() > 1 and any(\n [\n export_dict[\"export_query_pixel_anomaly_flag_images\"],\n export_dict[\"export_query_pixel_anomaly_flag_counts\"],\n export_dict[\"export_query_pixel_anomaly_flag_percentages\"]\n ]\n )\n ),\n export_dict[\"export_query_anomaly_scores\"],\n export_dict[\"export_query_anomaly_flags\"]\n ]\n ):\n self.export_using_query_images_input_berg_query_images_and_beyond(\n growth_idx,\n export_dict,\n export_inputs_query_images,\n export_outputs,\n generator_model,\n encoder_model\n )\n\n def create_serving_model_berg(self, growth_idx):\n \"\"\"Creates Keras `Model` for serving Berg paper.\n\n Args:\n growth_idx: int, index of growth phase to export.\n \"\"\"\n export_dict = self.params[\"export\"]\n export_inputs_Z = []\n export_inputs_query_images = []\n export_outputs = []\n\n generator_model = (\n self.network_objects[\"generator\"].models[growth_idx]\n )\n\n encoder_model = None\n if self.params[\"encoder\"][\"create\"]:\n encoder_model = (\n self.network_objects[\"encoder\"].models[growth_idx]\n )\n\n self.export_using_z_input_berg(\n growth_idx,\n export_dict,\n export_inputs_Z,\n export_outputs,\n generator_model,\n encoder_model\n )\n\n if self.params[\"encoder\"][\"create\"]:\n self.export_using_query_images_input_berg(\n growth_idx,\n export_dict,\n export_inputs_query_images,\n export_outputs,\n generator_model,\n encoder_model\n )\n\n if export_dict[\"export_all_growth_phases\"]:\n if export_inputs_Z:\n self.serving_inputs_Z = export_inputs_Z\n\n if export_inputs_query_images:\n query_images_name = export_inputs_query_images[0].name\n name_set = self.serving_inputs_query_images_names_set\n if query_images_name not in name_set:\n self.serving_inputs_query_images.extend(\n export_inputs_query_images\n )\n self.serving_inputs_query_images_names_set.add(\n query_images_name\n )\n\n self.serving_outputs.extend(export_outputs)\n\n serving_model = tf.keras.Model(\n inputs=export_inputs_Z + export_inputs_query_images,\n outputs=export_outputs,\n name=\"serving_model_growth_{}_epoch_{}\".format(\n growth_idx, self.epoch_idx\n )\n )\n\n if export_dict[\"print_serving_model_summaries\"]:\n print(\"\\nserving_model = {}\".format(serving_model.summary()))\n\n return serving_model\n\n def create_serving_models_berg(self):\n \"\"\"Creates Keras `Model`s for serving for Berg paper.\n\n Args:\n growth_idx: int, index of growth phase to export.\n \"\"\"\n if self.params[\"export\"][\"export_all_growth_phases\"]:\n # Reset.\n self.serving_inputs_query_images_names_set.clear()\n self.serving_inputs_query_images.clear()\n self.serving_outputs.clear()\n for i in range(self.num_growths):\n self.create_serving_model_berg(growth_idx=i)\n\n if self.params[\"export\"][\"print_serving_model_summaries\"]:\n print(\n \"create_serving_models: serving_inputs_Z = {}\".format(\n self.serving_inputs_Z\n )\n )\n print(\n \"create_serving_models: {} = {}\".format(\n \"serving_inputs_query_images\",\n self.serving_inputs_query_images\n )\n )\n print(\n \"create_serving_models: serving_outputs = {}\".format(\n self.serving_outputs\n )\n )\n\n self.serving_model = tf.keras.Model(\n inputs=(\n self.serving_inputs_Z + self.serving_inputs_query_images\n ),\n outputs=self.serving_outputs,\n name=\"serving_model_all_growth_{}_epoch_{}\".format(\n self.growth_idx, self.epoch_idx\n )\n )\n else:\n self.serving_model = self.create_serving_model_berg(\n growth_idx=self.growth_idx\n )\n"
] |
[
[
"tensorflow.abs",
"tensorflow.expand_dims",
"tensorflow.math.sigmoid",
"tensorflow.ones_like",
"tensorflow.greater",
"tensorflow.math.reduce_prod",
"tensorflow.cast"
]
] |
mgomesborges/Stone-Soup
|
[
"39c7f02ce11e10c9b3c612ad359f6d8bca495266",
"39c7f02ce11e10c9b3c612ad359f6d8bca495266"
] |
[
"stonesoup/types/tests/test_state.py",
"stonesoup/updater/tests/test_kalman.py"
] |
[
"# -*- coding: utf-8 -*-\nimport datetime\n\nimport numpy as np\nimport pytest\n\nfrom ..angle import Bearing\nfrom ..array import StateVector, CovarianceMatrix\nfrom ..numeric import Probability\nfrom ..particle import Particle\nfrom ..state import State, GaussianState, ParticleState, \\\n StateMutableSequence, WeightedGaussianState\n\n\ndef test_state():\n with pytest.raises(TypeError):\n State()\n\n # Test state initiation without timestamp\n state_vector = StateVector([[0], [1]])\n state = State(state_vector)\n assert np.array_equal(state.state_vector, state_vector)\n\n # Test state initiation with timestamp\n timestamp = datetime.datetime.now()\n state = State(state_vector, timestamp=timestamp)\n assert state.timestamp == timestamp\n\n\ndef test_state_invalid_vector():\n with pytest.raises(ValueError):\n State(StateVector([[[1, 2, 3, 4]]]))\n\n\ndef test_gaussianstate():\n \"\"\" GaussianState Type test \"\"\"\n\n with pytest.raises(TypeError):\n GaussianState()\n\n mean = StateVector([[-1.8513], [0.9994], [0], [0]]) * 1e4\n covar = CovarianceMatrix([[2.2128, 0, 0, 0],\n [0.0002, 2.2130, 0, 0],\n [0.3897, -0.00004, 0.0128, 0],\n [0, 0.3897, 0.0013, 0.0135]]) * 1e3\n timestamp = datetime.datetime.now()\n\n # Test state initiation without timestamp\n state = GaussianState(mean, covar)\n assert(np.array_equal(mean, state.mean))\n assert(np.array_equal(covar, state.covar))\n assert(state.ndim == mean.shape[0])\n assert(state.timestamp is None)\n\n # Test state initiation with timestamp\n state = GaussianState(mean, covar, timestamp)\n assert(np.array_equal(mean, state.mean))\n assert(np.array_equal(covar, state.covar))\n assert(state.ndim == mean.shape[0])\n assert(state.timestamp == timestamp)\n\n\ndef test_gaussianstate_invalid_covar():\n mean = StateVector([[1], [2], [3], [4]]) # 4D\n covar = CovarianceMatrix(np.diag([1, 2, 3])) # 3D\n with pytest.raises(ValueError):\n GaussianState(mean, covar)\n\n\ndef test_weighted_gaussian_state():\n mean = StateVector([[1], [2], [3], [4]]) # 4D\n covar = CovarianceMatrix(np.diag([1, 2, 3])) # 3D\n weight = 0.3\n with pytest.raises(ValueError):\n a = WeightedGaussianState(mean, covar, weight)\n assert a.weight == weight\n\n\ndef test_particlestate():\n with pytest.raises(TypeError):\n ParticleState()\n\n # 1D\n num_particles = 10\n state_vector1 = StateVector([[0.]])\n state_vector2 = StateVector([[100.]])\n weight = Probability(1/num_particles)\n particles = []\n particles.extend(Particle(\n state_vector1, weight=weight) for _ in range(num_particles//2))\n particles.extend(Particle(\n state_vector2, weight=weight) for _ in range(num_particles//2))\n\n # Test state without timestamp\n state = ParticleState(particles)\n assert np.allclose(state.state_vector, StateVector([[50]]))\n assert np.allclose(state.covar, CovarianceMatrix([[2500]]))\n\n # Test state with timestamp\n timestamp = datetime.datetime.now()\n state = ParticleState(particles, timestamp=timestamp)\n assert np.allclose(state.state_vector, StateVector([[50]]))\n assert np.allclose(state.covar, CovarianceMatrix([[2500]]))\n assert state.timestamp == timestamp\n\n # 2D\n state_vector1 = StateVector([[0.], [0.]])\n state_vector2 = StateVector([[100.], [200.]])\n particles = []\n particles.extend(Particle(\n state_vector1, weight=weight) for _ in range(num_particles//2))\n particles.extend(Particle(\n state_vector2, weight=weight) for _ in range(num_particles//2))\n\n state = ParticleState(particles)\n assert np.allclose(state.state_vector, StateVector([[50], [100]]))\n assert np.allclose(state.covar, CovarianceMatrix([[2500, 5000], [5000, 10000]]))\n\n\ndef test_particlestate_weighted():\n num_particles = 10\n\n # Half particles at high weight at 0\n state_vector1 = StateVector([[0.]])\n weight1 = Probability(0.75 / (num_particles / 2))\n\n # Other half of particles low weight at 100\n state_vector2 = StateVector([[100]])\n weight2 = Probability(0.25 / (num_particles / 2))\n\n particles = []\n particles.extend(Particle(\n state_vector1, weight=weight1) for _ in range(num_particles//2))\n particles.extend(Particle(\n state_vector2, weight=weight2) for _ in range(num_particles//2))\n\n # Check particles sum to 1 still\n assert pytest.approx(1) == sum(particle.weight for particle in particles)\n\n # Test state vector is now weighted towards 0 from 50 (non-weighted mean)\n state = ParticleState(particles)\n assert np.allclose(state.state_vector, StateVector([[25]]))\n assert np.allclose(state.covar, CovarianceMatrix([[1875]]))\n\n\ndef test_particlestate_angle():\n num_particles = 10\n\n state_vector1 = StateVector([[Bearing(np.pi + 0.1)], [-10.]])\n state_vector2 = StateVector([[Bearing(np.pi - 0.1)], [20.]])\n weight = Probability(1/num_particles)\n particles = []\n particles.extend(Particle(\n state_vector1, weight=weight) for _ in range(num_particles//2))\n particles.extend(Particle(\n state_vector2, weight=weight) for _ in range(num_particles//2))\n\n # Test state without timestamp\n state = ParticleState(particles)\n assert np.allclose(state.state_vector, StateVector([[np.pi], [5.]]))\n assert np.allclose(state.covar, CovarianceMatrix([[0.01, -1.5], [-1.5, 225]]))\n\n\ndef test_state_mutable_sequence_state():\n state_vector = StateVector([[0]])\n timestamp = datetime.datetime(2018, 1, 1, 14)\n delta = datetime.timedelta(minutes=1)\n sequence = StateMutableSequence(\n [State(state_vector, timestamp=timestamp+delta*n)\n for n in range(10)])\n\n assert sequence.state is sequence.states[-1]\n assert np.array_equal(sequence.state_vector, state_vector)\n assert sequence.timestamp == timestamp + delta*9\n\n del sequence[-1]\n assert sequence.timestamp == timestamp + delta*8\n\n\ndef test_state_mutable_sequence_slice():\n state_vector = StateVector([[0]])\n timestamp = datetime.datetime(2018, 1, 1, 14)\n delta = datetime.timedelta(minutes=1)\n sequence = StateMutableSequence(\n [State(state_vector, timestamp=timestamp+delta*n)\n for n in range(10)])\n\n assert isinstance(sequence[timestamp:], StateMutableSequence)\n assert isinstance(sequence[5:], StateMutableSequence)\n assert isinstance(sequence[timestamp], State)\n assert isinstance(sequence[5], State)\n\n assert len(sequence[timestamp:]) == 10\n assert len(sequence[:timestamp]) == 0\n assert len(sequence[timestamp+delta*5:]) == 5\n assert len(sequence[:timestamp+delta*5]) == 5\n assert len(sequence[timestamp+delta*4:timestamp+delta*6]) == 2\n assert len(sequence[timestamp+delta*2:timestamp+delta*8:3]) == 2\n assert len(sequence[timestamp+delta*1:][:timestamp+delta*2]) == 1\n\n assert sequence[timestamp] == sequence.states[0]\n\n with pytest.raises(TypeError):\n sequence[timestamp:1]\n\n with pytest.raises(IndexError):\n sequence[timestamp-delta]\n",
"# -*- coding: utf-8 -*-\n\"\"\"Test for updater.kalman module\"\"\"\nimport pytest\nimport numpy as np\n\nfrom stonesoup.models.measurement.linear import LinearGaussian\nfrom stonesoup.types.detection import Detection\nfrom stonesoup.types.hypothesis import SingleHypothesis\nfrom stonesoup.types.prediction import (\n GaussianStatePrediction, GaussianMeasurementPrediction)\nfrom stonesoup.types.state import GaussianState\nfrom stonesoup.updater.kalman import (\n KalmanUpdater, ExtendedKalmanUpdater, UnscentedKalmanUpdater)\n\n\n@pytest.mark.parametrize(\n \"UpdaterClass, measurement_model, prediction, measurement\",\n [\n ( # Standard Kalman\n KalmanUpdater,\n LinearGaussian(ndim_state=2, mapping=[0],\n noise_covar=np.array([[0.04]])),\n GaussianStatePrediction(np.array([[-6.45], [0.7]]),\n np.array([[4.1123, 0.0013],\n [0.0013, 0.0365]])),\n Detection(np.array([[-6.23]]))\n ),\n ( # Extended Kalman\n ExtendedKalmanUpdater,\n LinearGaussian(ndim_state=2, mapping=[0],\n noise_covar=np.array([[0.04]])),\n GaussianStatePrediction(np.array([[-6.45], [0.7]]),\n np.array([[4.1123, 0.0013],\n [0.0013, 0.0365]])),\n Detection(np.array([[-6.23]]))\n ),\n ( # Unscented Kalman\n UnscentedKalmanUpdater,\n LinearGaussian(ndim_state=2, mapping=[0],\n noise_covar=np.array([[0.04]])),\n GaussianStatePrediction(np.array([[-6.45], [0.7]]),\n np.array([[4.1123, 0.0013],\n [0.0013, 0.0365]])),\n Detection(np.array([[-6.23]]))\n )\n ],\n ids=[\"standard\", \"extended\", \"unscented\"]\n)\ndef test_kalman(UpdaterClass, measurement_model, prediction, measurement):\n\n # Calculate evaluation variables\n eval_measurement_prediction = GaussianMeasurementPrediction(\n measurement_model.matrix()@prediction.mean,\n measurement_model.matrix()@prediction.covar@measurement_model.matrix().T\n + measurement_model.covar(),\n cross_covar=prediction.covar@measurement_model.matrix().T)\n kalman_gain = eval_measurement_prediction.cross_covar@np.linalg.inv(\n eval_measurement_prediction.covar)\n eval_posterior = GaussianState(\n prediction.mean\n + kalman_gain@(measurement.state_vector\n - eval_measurement_prediction.mean),\n prediction.covar\n - kalman_gain@eval_measurement_prediction.covar@kalman_gain.T)\n\n # Initialise a kalman updater\n updater = UpdaterClass(measurement_model=measurement_model)\n\n # Get and assert measurement prediction\n measurement_prediction = updater.predict_measurement(prediction)\n assert(np.allclose(measurement_prediction.mean,\n eval_measurement_prediction.mean,\n 0, atol=1.e-14))\n assert(np.allclose(measurement_prediction.covar,\n eval_measurement_prediction.covar,\n 0, atol=1.e-14))\n assert(np.allclose(measurement_prediction.cross_covar,\n eval_measurement_prediction.cross_covar,\n 0, atol=1.e-14))\n\n # Perform and assert state update (without measurement prediction)\n posterior = updater.update(SingleHypothesis(\n prediction=prediction,\n measurement=measurement))\n assert(np.allclose(posterior.mean, eval_posterior.mean, 0, atol=1.e-14))\n assert(np.allclose(posterior.covar, eval_posterior.covar, 0, atol=1.e-14))\n assert(np.array_equal(posterior.hypothesis.prediction, prediction))\n assert (np.allclose(\n posterior.hypothesis.measurement_prediction.state_vector,\n measurement_prediction.state_vector, 0, atol=1.e-14))\n assert (np.allclose(posterior.hypothesis.measurement_prediction.covar,\n measurement_prediction.covar, 0, atol=1.e-14))\n assert(np.array_equal(posterior.hypothesis.measurement, measurement))\n assert(posterior.timestamp == prediction.timestamp)\n\n # Perform and assert state update\n posterior = updater.update(SingleHypothesis(\n prediction=prediction,\n measurement=measurement,\n measurement_prediction=measurement_prediction))\n assert(np.allclose(posterior.mean, eval_posterior.mean, 0, atol=1.e-14))\n assert(np.allclose(posterior.covar, eval_posterior.covar, 0, atol=1.e-14))\n assert(np.array_equal(posterior.hypothesis.prediction, prediction))\n assert (np.allclose(\n posterior.hypothesis.measurement_prediction.state_vector,\n measurement_prediction.state_vector, 0, atol=1.e-14))\n assert (np.allclose(posterior.hypothesis.measurement_prediction.covar,\n measurement_prediction.covar, 0, atol=1.e-14))\n assert(np.array_equal(posterior.hypothesis.measurement, measurement))\n assert(posterior.timestamp == prediction.timestamp)\n"
] |
[
[
"numpy.diag",
"numpy.array_equal"
],
[
"numpy.allclose",
"numpy.linalg.inv",
"numpy.array",
"numpy.array_equal"
]
] |
lillekemiker/blmath
|
[
"817ebec258388e6136765a392972b0835cabce5b"
] |
[
"blmath/geometry/primitives/plane.py"
] |
[
"import numpy as np\nfrom blmath.numerics import vx\n\nclass Plane(object):\n '''\n A 2-D plane in 3-space (not a hyperplane).\n\n Params:\n - point_on_plane, plane_normal:\n 1 x 3 np.arrays\n '''\n\n def __init__(self, point_on_plane, unit_normal):\n if vx.almost_zero(unit_normal):\n raise ValueError('unit_normal should not be the zero vector')\n\n unit_normal = vx.normalize(unit_normal)\n\n self._r0 = np.asarray(point_on_plane)\n self._n = np.asarray(unit_normal)\n\n def __repr__(self):\n return \"<Plane of {} through {}>\".format(self.normal, self.reference_point)\n\n @classmethod\n def from_points(cls, p1, p2, p3):\n '''\n If the points are oriented in a counterclockwise direction, the plane's\n normal extends towards you.\n\n '''\n from blmath.numerics import as_numeric_array\n\n p1 = as_numeric_array(p1, shape=(3,))\n p2 = as_numeric_array(p2, shape=(3,))\n p3 = as_numeric_array(p3, shape=(3,))\n\n v1 = p2 - p1\n v2 = p3 - p1\n normal = np.cross(v1, v2)\n\n return cls(point_on_plane=p1, unit_normal=normal)\n\n @classmethod\n def from_points_and_vector(cls, p1, p2, vector):\n '''\n Compute a plane which contains two given points and the given\n vector. Its reference point will be p1.\n\n For example, to find the vertical plane that passes through\n two landmarks:\n\n from_points_and_normal(p1, p2, vector)\n\n Another way to think about this: identify the plane to which\n your result plane should be perpendicular, and specify vector\n as its normal vector.\n\n '''\n from blmath.numerics import as_numeric_array\n\n p1 = as_numeric_array(p1, shape=(3,))\n p2 = as_numeric_array(p2, shape=(3,))\n\n v1 = p2 - p1\n v2 = as_numeric_array(vector, shape=(3,))\n normal = np.cross(v1, v2)\n\n return cls(point_on_plane=p1, unit_normal=normal)\n\n @classmethod\n def fit_from_points(cls, points):\n '''\n Fits a plane whose normal is orthgonal to the first two principal axes\n of variation in the data and centered on the points' centroid.\n '''\n eigval, eigvec = np.linalg.eig(np.cov(points.T))\n ordering = np.argsort(eigval)[::-1]\n normal = np.cross(eigvec[:, ordering[0]], eigvec[:, ordering[1]])\n return cls(points.mean(axis=0), normal)\n\n @property\n def equation(self):\n '''\n Returns parameters A, B, C, D as a 1 x 4 np.array, where\n\n Ax + By + Cz + D = 0\n\n defines the plane.\n\n params:\n - normalized:\n Boolean, indicates whether or not the norm of the vector [A, B, C] is 1.\n Useful when computing the distance from a point to the plane.\n '''\n A, B, C = self._n\n D = -self._r0.dot(self._n)\n\n return np.array([A, B, C, D])\n\n @property\n def reference_point(self):\n '''\n The point used to create this plane.\n\n '''\n return self._r0\n\n @property\n def canonical_point(self):\n '''\n A canonical point on the plane, the one at which the normal\n would intersect the plane if drawn from the origin (0, 0, 0).\n\n This is computed by projecting the reference point onto the\n normal.\n\n This is useful for partitioning the space between two planes,\n as we do when searching for planar cross sections.\n\n '''\n return self._r0.dot(self._n) * self._n\n\n @property\n def normal(self):\n '''\n Return the plane's normal vector.\n\n '''\n return self._n\n\n def flipped(self):\n '''\n Creates a new Plane with an inverted orientation.\n '''\n normal = self._n * -1\n return Plane(self._r0, normal)\n\n def sign(self, points):\n '''\n Given an array of points, return an array with +1 for points in front\n of the plane (in the direction of the normal), -1 for points behind\n the plane (away from the normal), and 0 for points on the plane.\n\n '''\n return np.sign(self.signed_distance(points))\n\n def points_in_front(self, points, inverted=False, ret_indices=False):\n '''\n Given an array of points, return the points which lie either on the\n plane or in the half-space in front of it (i.e. in the direction of\n the plane normal).\n\n points: An array of points.\n inverted: When `True`, invert the logic. Return the points that lie\n behind the plane instead.\n ret_indices: When `True`, return the indices instead of the points\n themselves.\n\n '''\n sign = self.sign(points)\n\n if inverted:\n mask = np.less_equal(sign, 0)\n else:\n mask = np.greater_equal(sign, 0)\n\n indices = np.flatnonzero(mask)\n\n return indices if ret_indices else points[indices]\n\n def signed_distance(self, points):\n '''\n Returns the signed distances given an np.array of 3-vectors.\n\n Params:\n - points:\n V x 3 np.array\n '''\n return np.dot(points, self.equation[:3]) + self.equation[3]\n\n def distance(self, points):\n return np.absolute(self.signed_distance(points))\n\n def project_point(self, point):\n '''\n Project a given point to the plane.\n\n '''\n # Translate the point back to the plane along the normal.\n signed_distance_to_point = self.signed_distance(point.reshape((-1, 3)))[0]\n return point - signed_distance_to_point * self._n\n\n def polyline_xsection(self, polyline):\n '''\n Returns the points of intersection between the plane and any of the\n edges of `polyline`, which should be an instance of Polyline.\n\n '''\n # Identify edges with endpoints that are not on the same side of the plane\n sgn_dists = self.signed_distance(polyline.v)\n which_es = np.abs(np.sign(sgn_dists)[polyline.e].sum(axis=1)) != 2\n # For the intersecting edges, compute the distance of the endpoints to the plane\n endpoint_distances = np.abs(sgn_dists[polyline.e[which_es]])\n # Normalize the rows of endpoint_distances\n t = endpoint_distances / endpoint_distances.sum(axis=1)[:, np.newaxis]\n # Take a weighted average of the endpoints to obtain the points of intersection\n intersection_points = ((1. - t[:, :, np.newaxis]) * polyline.v[polyline.e[which_es]]).sum(axis=1)\n #assert(np.all(self.distance(intersection_points) < 1e-10))\n return intersection_points\n\n def line_xsection(self, pt, ray):\n return self._line_xsection(np.asarray(pt).ravel(), np.asarray(ray).ravel())\n\n def _line_xsection(self, pt, ray):\n denom = np.dot(ray, self.normal)\n if denom == 0:\n return None # parallel, either coplanar or non-intersecting\n p = np.dot(self.reference_point - pt, self.normal) / denom\n return p * ray + pt\n\n def line_segment_xsection(self, a, b):\n return self._line_segment_xsection(np.asarray(a).ravel(), np.asarray(b).ravel())\n\n def _line_segment_xsection(self, a, b):\n pt = self._line_xsection(a, b-a)\n if pt is not None:\n if any(np.logical_and(pt > a, pt > b)) or any(np.logical_and(pt < a, pt < b)):\n return None\n return pt\n\n def line_xsections(self, pts, rays):\n denoms = np.dot(rays, self.normal)\n denom_is_zero = denoms == 0\n denoms[denom_is_zero] = np.nan\n p = np.dot(self.reference_point - pts, self.normal) / denoms\n return np.vstack([p, p, p]).T * rays + pts, ~denom_is_zero\n\n def line_segment_xsections(self, a, b):\n pts, pt_is_valid = self.line_xsections(a, b-a)\n pt_is_out_of_bounds = np.logical_or(np.any(np.logical_and(pts[pt_is_valid] > a[pt_is_valid], pts[pt_is_valid] > b[pt_is_valid]), axis=1),\n np.any(np.logical_and(pts[pt_is_valid] < a[pt_is_valid], pts[pt_is_valid] < b[pt_is_valid]), axis=1))\n pt_is_valid[pt_is_valid] = ~pt_is_out_of_bounds\n pts[~pt_is_valid] = np.nan\n return pts, pt_is_valid\n\n\n def mesh_xsection(self, m, neighborhood=None):\n '''\n Backwards compatible.\n Returns one polyline that may connect supposedly disconnected components.\n Returns an empty Polyline if there's no intersection.\n '''\n from blmath.geometry import Polyline\n\n components = self.mesh_xsections(m, neighborhood)\n if len(components) == 0:\n return Polyline(None)\n return Polyline(np.vstack([x.v for x in components]), closed=True)\n\n def mesh_intersecting_faces(self, m):\n sgn_dists = self.signed_distance(m.v)\n which_fs = np.abs(np.sign(sgn_dists)[m.f].sum(axis=1)) != 3\n return m.f[which_fs]\n\n def mesh_xsections(self, m, neighborhood=None):\n '''\n Takes a cross section of planar point cloud with a Mesh object.\n Ignore those points which intersect at a vertex - the probability of\n this event is small, and accounting for it complicates the algorithm.\n\n If 'neighborhood' is provided, use a KDTree to constrain the\n cross section to the closest connected component to 'neighborhood'.\n\n Params:\n - m:\n Mesh object\n - neigbhorhood:\n M x 3 np.array\n\n Returns a list of Polylines.\n '''\n from blmath.geometry import Polyline\n\n # 1: Select those faces that intersect the plane, fs\n fs = self.mesh_intersecting_faces(m)\n if len(fs) == 0:\n return [] # Nothing intersects\n # and edges of those faces\n es = np.vstack((fs[:, (0, 1)], fs[:, (1, 2)], fs[:, (2, 0)]))\n\n # 2: Find the edges where each of those faces actually cross the plane\n class EdgeMap(object):\n # A quick two level dictionary where the two keys are interchangeable (i.e. a symmetric graph)\n def __init__(self):\n self.d = {} # store indicies into self.values here, to make it easier to get inds or values\n self.values = []\n def _order(self, u, v):\n if u < v:\n return u, v\n else:\n return v, u\n def add(self, u, v, val):\n low, high = self._order(u, v)\n if low not in self.d:\n self.d[low] = {}\n self.values.append(val)\n self.d[low][high] = len(self.values) - 1\n def contains(self, u, v):\n low, high = self._order(u, v)\n if low in self.d and high in self.d[low]:\n return True\n return False\n def index(self, u, v):\n low, high = self._order(u, v)\n try:\n return self.d[low][high]\n except KeyError:\n return None\n def get(self, u, v):\n ii = self.index(u, v)\n if ii is not None:\n return self.values[ii]\n else:\n return None\n\n intersection_map = EdgeMap()\n\n pts, pt_is_valid = self.line_segment_xsections(m.v[es[:, 0]], m.v[es[:, 1]])\n valid_pts = pts[pt_is_valid]\n valid_es = es[pt_is_valid]\n for val, e in zip(valid_pts, valid_es):\n if not intersection_map.contains(e[0], e[1]):\n intersection_map.add(e[0], e[1], val)\n verts = np.array(intersection_map.values)\n\n class Graph(object):\n # A little utility class to build a symmetric graph and calculate Euler Paths\n def __init__(self, size):\n self.size = size\n self.d = {}\n def __len__(self):\n return len(self.d)\n def add_edges(self, edges):\n for u, v in edges:\n self.add_edge(u, v)\n def add_edge(self, u, v):\n assert u >= 0 and u < self.size\n assert v >= 0 and v < self.size\n if u not in self.d:\n self.d[u] = set()\n if v not in self.d:\n self.d[v] = set()\n self.d[u].add(v)\n self.d[v].add(u)\n def remove_edge(self, u, v):\n if u in self.d and v in self.d[u]:\n self.d[u].remove(v)\n if v in self.d and u in self.d[v]:\n self.d[v].remove(u)\n if v in self.d and len(self.d[v]) == 0:\n del self.d[v]\n if u in self.d and len(self.d[u]) == 0:\n del self.d[u]\n def pop_euler_path(self, allow_multiple_connected_components=True):\n # Based on code from Przemek Drochomirecki, Krakow, 5 Nov 2006\n # http://code.activestate.com/recipes/498243-finding-eulerian-path-in-undirected-graph/\n # Under PSF License\n # NB: MUTATES d\n\n # counting the number of vertices with odd degree\n odd = [x for x in self.d if len(self.d[x])&1]\n odd.append(self.d.keys()[0])\n if not allow_multiple_connected_components and len(odd) > 3:\n return None\n stack = [odd[0]]\n path = []\n # main algorithm\n while stack:\n v = stack[-1]\n if v in self.d:\n u = self.d[v].pop()\n stack.append(u)\n self.remove_edge(u, v)\n else:\n path.append(stack.pop())\n return path\n\n # 4: Build the edge adjacency graph\n G = Graph(verts.shape[0])\n for f in fs:\n # Since we're dealing with a triangle that intersects the plane, exactly two of the edges\n # will intersect (note that the only other sorts of \"intersections\" are one edge in\n # plane or all three edges in plane, which won't be picked up by mesh_intersecting_faces).\n e0 = intersection_map.index(f[0], f[1])\n e1 = intersection_map.index(f[0], f[2])\n e2 = intersection_map.index(f[1], f[2])\n if e0 is None:\n G.add_edge(e1, e2)\n elif e1 is None:\n G.add_edge(e0, e2)\n else:\n G.add_edge(e0, e1)\n\n # 5: Find the paths for each component\n components = []\n components_closed = []\n while len(G) > 0:\n path = G.pop_euler_path()\n if path is None:\n raise ValueError(\"mesh slice has too many odd degree edges; can't find a path along the edge\")\n component_verts = verts[path]\n\n if np.all(component_verts[0] == component_verts[-1]):\n # Because the closed polyline will make that last link:\n component_verts = np.delete(component_verts, 0, axis=0)\n components_closed.append(True)\n else:\n components_closed.append(False)\n components.append(component_verts)\n\n if neighborhood is None or len(components) == 1:\n return [Polyline(v, closed=closed) for v, closed in zip(components, components_closed)]\n\n # 6 (optional - only if 'neighborhood' is provided): Use a KDTree to select the component with minimal distance to 'neighborhood'\n from scipy.spatial import cKDTree # First thought this warning was caused by a pythonpath problem, but it seems more likely that the warning is caused by scipy import hackery. pylint: disable=no-name-in-module\n\n kdtree = cKDTree(neighborhood)\n\n # number of components will not be large in practice, so this loop won't hurt\n means = [np.mean(kdtree.query(component)[0]) for component in components]\n return [Polyline(components[np.argmin(means)], closed=True)]\n\n\ndef main():\n import argparse\n from lace.mesh import Mesh\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-p', '--path', help='filepath to mesh', required=True)\n parser.add_argument('-c', '--cloud', help='display point cloud', required=False, default=False, action='store_true')\n parser.add_argument('-d', '--direction', help='direction of connected component',\n choices=['N', 'S', 'E', 'W'], default=None, required=False)\n args = parser.parse_args()\n\n path_to_mesh = args.path\n mesh = Mesh(filename=path_to_mesh, vc='SteelBlue')\n\n point_on_plane = np.array([0., 1., 0.])\n\n n1 = np.array([0., 1., 0.])\n p1 = Plane(point_on_plane, n1)\n\n n2 = np.array([1., 0., 0.])\n p2 = Plane(point_on_plane, n2)\n\n n3 = np.array([1., 1., 0.])\n n3 /= np.linalg.norm(n3)\n p3 = Plane(point_on_plane, n3)\n\n n4 = np.array([-1., 1., 0.])\n n4 /= np.linalg.norm(n4)\n p4 = Plane(point_on_plane, n4)\n\n dirmap = {\n 'N': [0., +100., 0.],\n 'S': [0., -100., 0.],\n 'E': [+100., 0., 0.],\n 'W': [-100., 0., 0.],\n None: None,\n }\n\n neighborhood = dirmap[args.direction]\n if neighborhood != None:\n neighborhood = np.array([neighborhood])\n\n xs1 = p1.mesh_xsection(mesh, neighborhood=neighborhood)\n xs2 = p2.mesh_xsection(mesh, neighborhood=neighborhood)\n xs3 = p3.mesh_xsection(mesh, neighborhood=neighborhood)\n xs4 = p4.mesh_xsection(mesh, neighborhood=neighborhood)\n\n lines = [\n polyline.as_lines()\n for polyline in (xs1, xs2, xs3, xs4)\n ]\n\n if args.cloud:\n mesh.f = []\n\n from lace.meshviewer import MeshViewer\n mv = MeshViewer(keepalive=True)\n mv.set_dynamic_meshes([mesh], blocking=True)\n mv.set_dynamic_lines(lines)\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"numpy.array",
"numpy.linalg.norm",
"numpy.dot",
"numpy.asarray",
"scipy.spatial.cKDTree",
"numpy.cov",
"numpy.delete",
"numpy.argmin",
"numpy.logical_and",
"numpy.greater_equal",
"numpy.less_equal",
"numpy.sign",
"numpy.abs",
"numpy.argsort",
"numpy.all",
"numpy.cross",
"numpy.vstack",
"numpy.flatnonzero"
]
] |
myracheng/pronear
|
[
"a92e97cd860900f3c535a72a1b867d8f5ad096ab"
] |
[
"near_code/dsl/library_functions.py"
] |
[
"import torch\nimport torch.nn as nn\n\nfrom .neural_functions import init_neural_function\n\n\n# TODO allow user to choose device\nif torch.cuda.is_available():\n device = 'cuda:0'\nelse:\n device = 'cpu'\n\nclass LibraryFunction:\n\n def __init__(self, submodules, input_type, output_type, input_size, output_size, num_units, name=\"\", has_params=False):\n self.submodules = submodules\n self.input_type = input_type\n self.output_type = output_type\n self.input_size = input_size\n self.output_size = output_size\n self.num_units = num_units\n self.name = name\n self.has_params = has_params\n\n if self.has_params:\n assert \"init_params\" in dir(self)\n self.init_params()\n\n def get_submodules(self):\n return self.submodules\n\n def set_submodules(self, new_submodules):\n self.submodules = new_submodules\n\n def get_typesignature(self):\n return self.input_type, self.output_type\n\nclass StartFunction(LibraryFunction):\n\n def __init__(self, input_type, output_type, input_size, output_size, num_units):\n self.program = init_neural_function(input_type, output_type, input_size, output_size, num_units)\n submodules = { 'program' : self.program }\n super().__init__(submodules, input_type, output_type, input_size, output_size, num_units, name=\"Start\")\n\n def execute_on_batch(self, batch, batch_lens=None, batch_output=None, is_sequential=False):\n return self.submodules[\"program\"].execute_on_batch(batch, batch_lens)\n \nclass FoldFunction(LibraryFunction):\n\n def __init__(self, input_size, output_size, num_units, fold_function=None):\n #TODO: will this accumulator require a grad?\n self.accumulator = torch.zeros(output_size)\n if fold_function is None:\n fold_function = init_neural_function(\"atom\", \"atom\", input_size+output_size, output_size, num_units)\n submodules = { \"foldfunction\" : fold_function }\n super().__init__(submodules, \"list\", \"atom\", input_size, output_size, num_units, name=\"Fold\")\n\n def execute_on_batch(self, batch, batch_lens=None, is_sequential=False):\n assert len(batch.size()) == 3\n batch_size, seq_len, feature_dim = batch.size()\n batch = batch.transpose(0,1) # (seq_len, batch_size, feature_dim)\n\n fold_out = []\n folded_val = self.accumulator.clone().detach().requires_grad_(True)\n folded_val = folded_val.unsqueeze(0).repeat(batch_size,1).to(device)\n for t in range(seq_len):\n features = batch[t]\n out_val = self.submodules[\"foldfunction\"].execute_on_batch(torch.cat([features, folded_val], dim=1))\n fold_out.append(out_val.unsqueeze(1))\n folded_val = out_val\n fold_out = torch.cat(fold_out, dim=1)\n \n if not is_sequential:\n idx = torch.tensor(batch_lens).to(device) - 1\n idx = idx.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, fold_out.size(-1))\n fold_out = fold_out.gather(1, idx).squeeze(1)\n\n return fold_out\n\nclass MapFunction(LibraryFunction):\n\n def __init__(self, input_size, output_size, num_units, map_function=None):\n if map_function is None:\n map_function = init_neural_function(\"atom\", \"atom\", input_size, output_size, num_units)\n submodules = { \"mapfunction\" : map_function }\n super().__init__(submodules, \"list\", \"list\", input_size, output_size, num_units, name=\"Map\")\n\n def execute_on_batch(self, batch, batch_lens=None):\n assert len(batch.size()) == 3\n batch_size, seq_len, feature_dim = batch.size()\n map_input = batch.view(-1, feature_dim)\n map_output = self.submodules[\"mapfunction\"].execute_on_batch(map_input)\n return map_output.view(batch_size, seq_len, -1)\n\nclass MapPrefixesFunction(LibraryFunction):\n\n def __init__(self, input_size, output_size, num_units, map_function=None):\n if map_function is None:\n map_function = init_neural_function(\"list\", \"atom\", input_size, output_size, num_units)\n submodules = { \"mapfunction\" : map_function }\n super().__init__(submodules, \"list\", \"list\", input_size, output_size, num_units, name=\"MapPrefixes\")\n\n def execute_on_batch(self, batch, batch_lens):\n assert len(batch.size()) == 3\n map_output = self.submodules[\"mapfunction\"].execute_on_batch(batch, batch_lens, is_sequential=True)\n assert len(map_output.size()) == 3\n return map_output\n\nclass ITE(LibraryFunction):\n \"\"\"(Smoothed) If-The-Else.\"\"\"\n\n def __init__(self, input_type, output_type, input_size, output_size, num_units, eval_function=None, function1=None, function2=None, beta=1.0, name=\"ITE\", simple=False):\n if eval_function is None:\n if simple:\n eval_function = init_neural_function(input_type, \"atom\", input_size, 1, num_units)\n else:\n eval_function = init_neural_function(input_type, \"atom\", input_size, output_size, num_units)\n if function1 is None:\n function1 = init_neural_function(input_type, output_type, input_size, output_size, num_units)\n if function2 is None:\n function2 = init_neural_function(input_type, output_type, input_size, output_size, num_units)\n submodules = { \"evalfunction\" : eval_function, \"function1\" : function1, \"function2\" : function2 }\n self.bsmooth = nn.Sigmoid()\n self.beta = beta\n self.simple = simple # the simple version of ITE evaluates the same function for all dimensions of the output\n super().__init__(submodules, input_type, output_type, input_size, output_size, num_units, name=name)\n\n def execute_on_batch(self, batch, batch_lens=None, is_sequential=False):\n if self.input_type == 'list':\n assert len(batch.size()) == 3\n assert batch_lens is not None\n else:\n assert len(batch.size()) == 2\n if is_sequential:\n predicted_eval = self.submodules[\"evalfunction\"].execute_on_batch(batch, batch_lens, is_sequential=False)\n predicted_function1 = self.submodules[\"function1\"].execute_on_batch(batch, batch_lens, is_sequential=is_sequential)\n predicted_function2 = self.submodules[\"function2\"].execute_on_batch(batch, batch_lens, is_sequential=is_sequential)\n else:\n predicted_eval = self.submodules[\"evalfunction\"].execute_on_batch(batch, batch_lens)\n predicted_function1 = self.submodules[\"function1\"].execute_on_batch(batch, batch_lens)\n predicted_function2 = self.submodules[\"function2\"].execute_on_batch(batch, batch_lens)\n\n gate = self.bsmooth(predicted_eval*self.beta)\n if self.simple:\n gate = gate.repeat(1, self.output_size)\n \n if self.get_typesignature() == ('list', 'list'):\n gate = gate.unsqueeze(1).repeat(1, batch.size(1), 1)\n elif self.get_typesignature() == ('list', 'atom') and is_sequential:\n gate = gate.unsqueeze(1).repeat(1, batch.size(1), 1)\n\n assert gate.size() == predicted_function2.size() == predicted_function1.size()\n ite_result = gate*predicted_function1 + (1.0 - gate)*predicted_function2\n\n return ite_result\n\nclass SimpleITE(ITE): #this is the base one?\n \"\"\"The simple version of ITE evaluates one function for all dimensions of the output.\"\"\"\n\n def __init__(self, input_type, output_type, input_size, output_size, num_units, eval_function=None, function1=None, function2=None, beta=1.0):\n super().__init__(input_type, output_type, input_size, output_size, num_units, \n eval_function=eval_function, function1=function1, function2=function2, beta=beta, name=\"SimpleITE\", simple=True)\n \nclass MultiplyFunction(LibraryFunction):\n\n def __init__(self, input_size, output_size, num_units, function1=None, function2=None):\n if function1 is None:\n function1 = init_neural_function(\"atom\", \"atom\", input_size, output_size, num_units)\n if function2 is None:\n function2 = init_neural_function(\"atom\", \"atom\", input_size, output_size, num_units)\n submodules = { \"function1\" : function1, \"function2\" : function2 }\n super().__init__(submodules, \"atom\", \"atom\", input_size, output_size, num_units, name=\"Multiply\")\n\n def execute_on_batch(self, batch, batch_lens=None):\n assert len(batch.size()) == 2\n predicted_function1 = self.submodules[\"function1\"].execute_on_batch(batch)\n predicted_function2 = self.submodules[\"function2\"].execute_on_batch(batch)\n return predicted_function1 * predicted_function2\n\nclass AddFunction(LibraryFunction):\n\n def __init__(self, input_size, output_size, num_units, function1=None, function2=None):\n if function1 is None:\n function1 = init_neural_function(\"atom\", \"atom\", input_size, output_size, num_units)\n if function2 is None:\n function2 = init_neural_function(\"atom\", \"atom\", input_size, output_size, num_units)\n submodules = { \"function1\": function1, \"function2\": function2 }\n super().__init__(submodules, \"atom\", \"atom\", input_size, output_size, num_units, name=\"Add\")\n\n def execute_on_batch(self, batch, batch_lens=None):\n assert len(batch.size()) == 2\n predicted_function1 = self.submodules[\"function1\"].execute_on_batch(batch)\n predicted_function2 = self.submodules[\"function2\"].execute_on_batch(batch)\n return predicted_function1 + predicted_function2\n\nclass ContinueFunction(LibraryFunction):\n\n def __init__(self, input_size, output_size, num_units, fxn=None):\n if fxn is None:\n fxn = init_neural_function(\"atom\", \"atom\", input_size, output_size, num_units)\n submodules = { \"fxn\" : fxn }\n super().__init__(submodules, \"atom\", \"atom\", input_size, output_size, num_units, name=\"\")\n\n def execute_on_batch(self, batch, batch_lens=None):\n assert len(batch.size()) == 2\n fxn_out = self.submodules[\"fxn\"].execute_on_batch(batch)\n return fxn_out\n\nclass LearnedConstantFunction(LibraryFunction):\n\n def __init__(self, input_size, output_size, num_units):\n super().__init__({}, \"atom\", \"atom\", input_size, output_size, num_units, name=\"LearnedConstant\", has_params=True)\n\n def init_params(self):\n self.parameters = { \"constant\" : torch.rand(self.output_size, requires_grad=True, device=device) }\n\n def execute_on_batch(self, batch, batch_lens=None):\n return self.parameters[\"constant\"].unsqueeze(0).repeat(batch.size(0), 1)\n \nclass AffineFunction(LibraryFunction):\n\n def __init__(self, raw_input_size, selected_input_size, output_size, num_units, name=\"Affine\"):\n self.selected_input_size = selected_input_size\n super().__init__({}, \"atom\", \"atom\", raw_input_size, output_size, num_units, name=name, has_params=True)\n\n def init_params(self):\n self.linear_layer = nn.Linear(self.selected_input_size, self.output_size, bias=True).to(device)\n self.parameters = {\n \"weights\" : self.linear_layer.weight,\n \"bias\" : self.linear_layer.bias\n }\n\n def execute_on_batch(self, batch, batch_lens=None):\n assert len(batch.size()) == 2\n return self.linear_layer(batch)\n\nclass AffineFeatureSelectionFunction(AffineFunction):\n\n def __init__(self, input_size, output_size, num_units, name=\"AffineFeatureSelection\"):\n assert hasattr(self, \"full_feature_dim\")\n assert input_size >= self.full_feature_dim\n if self.full_feature_dim == 0:\n self.is_full = True\n self.full_feature_dim = input_size\n else:\n self.is_full = False\n additional_inputs = input_size - self.full_feature_dim\n\n assert hasattr(self, \"feature_tensor\")\n assert len(self.feature_tensor) <= input_size\n self.feature_tensor = self.feature_tensor.to(device)\n super().__init__(raw_input_size=input_size, selected_input_size=self.feature_tensor.size()[-1]+additional_inputs, \n output_size=output_size, num_units=num_units, name=name)\n\n def init_params(self):\n self.raw_input_size = self.input_size\n if self.is_full:\n self.full_feature_dim = self.input_size\n self.feature_tensor = torch.arange(self.input_size).to(device)\n\n additional_inputs = self.raw_input_size - self.full_feature_dim\n self.selected_input_size = self.feature_tensor.size()[-1] + additional_inputs\n self.linear_layer = nn.Linear(self.selected_input_size, self.output_size, bias=True).to(device)\n self.parameters = {\n \"weights\" : self.linear_layer.weight,\n \"bias\" : self.linear_layer.bias\n }\n\n def execute_on_batch(self, batch, batch_lens=None):\n assert len(batch.size()) == 2\n features = torch.index_select(batch, 1, self.feature_tensor)\n remaining_features = batch[:,self.full_feature_dim:]\n return self.linear_layer(torch.cat([features, remaining_features], dim=-1))\n\nclass FullInputAffineFunction(AffineFeatureSelectionFunction):\n\n def __init__(self, input_size, output_size, num_units):\n self.full_feature_dim = 0 # this will indicate additional_inputs = 0 in FeatureSelectionFunction\n self.feature_tensor = torch.arange(input_size) # selects all features by default\n super().__init__(input_size, output_size, num_units, name=\"FullFeatureSelect\")\n"
] |
[
[
"torch.zeros",
"torch.rand",
"torch.cat",
"torch.nn.Linear",
"torch.arange",
"torch.nn.Sigmoid",
"torch.cuda.is_available",
"torch.tensor",
"torch.index_select"
]
] |
tarepan/HiPPO
|
[
"bc23e2dba13da6c307cb5a4ae248c2d2c56d465f"
] |
[
"datasets/utils.py"
] |
[
"import math\nimport numpy as np\n\nimport torch\n\n\ndef bitreversal_po2(n):\n m = int(math.log(n)/math.log(2))\n perm = np.arange(n).reshape(n,1)\n for i in range(m):\n n1 = perm.shape[0]//2\n perm = np.hstack((perm[:n1],perm[n1:]))\n return perm.squeeze(0)\n\ndef bitreversal_permutation(n):\n m = int(math.ceil(math.log(n)/math.log(2)))\n N = 1 << m\n perm = bitreversal_po2(N)\n return np.extract(perm < n, perm)\n\n\n# For language modeling\n# Adapted from https://github.com/salesforce/awd-lstm-lm/blob/master/utils.py\n\ndef repackage_hidden(h):\n \"\"\"Wraps hidden states in new Tensors,\n to detach them from their history.\"\"\"\n if isinstance(h, torch.Tensor):\n return h.detach()\n else:\n return tuple(repackage_hidden(v) for v in h)\n\n\ndef batchify(data, bsz):\n # Work out how cleanly we can divide the dataset into bsz parts.\n nbatch = data.size(0) // bsz\n # Trim off any extra elements that wouldn't cleanly fit (remainders).\n data = data.narrow(0, 0, nbatch * bsz)\n # Evenly divide the data across the bsz batches.\n data = data.view(bsz, -1).t().contiguous()\n return data\n\n\ndef get_batch(source, i, seq_len):\n seq_len = min(seq_len, len(source) - 1 - i)\n data = source[i:i+seq_len].t()\n target = source[i+1:i+1+seq_len].t().reshape(-1)\n return data, target\n"
] |
[
[
"numpy.extract",
"numpy.arange",
"numpy.hstack"
]
] |
ryoyop/seldon-core
|
[
"83717e88717a4030d7f76f87c3a3b713cd73d276"
] |
[
"python/seldon_core/seldon_methods.py"
] |
[
"import logging\nimport os\nfrom typing import Any, Dict, List, Tuple, Union\n\nimport numpy as np\nimport yaml\nfrom google.protobuf import json_format\n\nfrom seldon_core.flask_utils import SeldonMicroserviceException\nfrom seldon_core.metadata import SeldonInvalidMetadataError, validate_model_metadata\nfrom seldon_core.metrics import (\n AGGREGATE_METRIC_METHOD_TAG,\n FEEDBACK_METRIC_METHOD_TAG,\n HEALTH_METRIC_METHOD_TAG,\n INPUT_TRANSFORM_METRIC_METHOD_TAG,\n OUTPUT_TRANSFORM_METRIC_METHOD_TAG,\n PREDICT_METRIC_METHOD_TAG,\n ROUTER_METRIC_METHOD_TAG,\n SeldonMetrics,\n)\nfrom seldon_core.proto import prediction_pb2\nfrom seldon_core.user_model import (\n INCLUDE_METRICS_IN_CLIENT_RESPONSE,\n SeldonNotImplementedError,\n SeldonResponse,\n client_aggregate,\n client_custom_metrics,\n client_health_status,\n client_predict,\n client_route,\n client_send_feedback,\n client_transform_input,\n client_transform_output,\n)\nfrom seldon_core.utils import (\n construct_response,\n construct_response_json,\n extract_feedback_request_parts,\n extract_request_parts,\n extract_request_parts_json,\n getenv_as_bool,\n json_to_seldon_message,\n seldon_message_to_json,\n)\n\nlogger = logging.getLogger(__name__)\n\n\ndef handle_raw_custom_metrics(\n msg: Union[prediction_pb2.SeldonMessage, Dict],\n seldon_metrics: SeldonMetrics,\n is_proto: bool,\n method: str,\n):\n \"\"\"\n Update SeldonMetrics object with custom metrics from raw methods.\n If INCLUDE_METRICS_IN_CLIENT_RESPONSE environmental variable is set to \"true\"\n metrics will be dropped from msg.\n \"\"\"\n metrics = []\n if is_proto:\n metrics = seldon_message_to_json(msg.meta).get(\"metrics\", [])\n if metrics and not INCLUDE_METRICS_IN_CLIENT_RESPONSE:\n del msg.meta.metrics[:]\n elif isinstance(msg, dict):\n metrics = msg.get(\"meta\", {}).get(\"metrics\", [])\n if metrics and not INCLUDE_METRICS_IN_CLIENT_RESPONSE:\n del msg[\"meta\"][\"metrics\"]\n seldon_metrics.update(metrics, method)\n\n\ndef predict(\n user_model: Any,\n request: Union[prediction_pb2.SeldonMessage, List, Dict, bytes],\n seldon_metrics: SeldonMetrics,\n) -> Union[prediction_pb2.SeldonMessage, List, Dict, bytes]:\n \"\"\"\n Call the user model to get a prediction and package the response\n\n Parameters\n ----------\n user_model\n User defined class instance\n request\n The incoming request\n\n Returns\n -------\n The prediction\n \"\"\"\n # TODO: Find a way to choose predict_rest or predict_grpc when payload is\n # not decoded\n is_proto = isinstance(request, prediction_pb2.SeldonMessage)\n\n if hasattr(user_model, \"predict_rest\") and not is_proto:\n logger.warning(\"predict_rest is deprecated. Please use predict_raw\")\n return user_model.predict_rest(request)\n elif hasattr(user_model, \"predict_grpc\") and is_proto:\n logger.warning(\"predict_grpc is deprecated. Please use predict_raw\")\n return user_model.predict_grpc(request)\n else:\n if hasattr(user_model, \"predict_raw\"):\n try:\n response = user_model.predict_raw(request)\n handle_raw_custom_metrics(\n response, seldon_metrics, is_proto, PREDICT_METRIC_METHOD_TAG\n )\n return response\n except SeldonNotImplementedError:\n pass\n\n if is_proto:\n (features, meta, datadef, data_type) = extract_request_parts(request)\n\n client_response = client_predict(\n user_model, features, datadef.names, meta=meta\n )\n\n metrics = client_custom_metrics(\n user_model,\n seldon_metrics,\n PREDICT_METRIC_METHOD_TAG,\n client_response.metrics,\n )\n\n return construct_response(\n user_model,\n False,\n request,\n client_response.data,\n meta,\n metrics,\n client_response.tags,\n )\n else:\n (features, meta, datadef, data_type) = extract_request_parts_json(request)\n class_names = datadef[\"names\"] if datadef and \"names\" in datadef else []\n\n client_response = client_predict(\n user_model, features, class_names, meta=meta\n )\n\n metrics = client_custom_metrics(\n user_model,\n seldon_metrics,\n PREDICT_METRIC_METHOD_TAG,\n client_response.metrics,\n )\n\n return construct_response_json(\n user_model,\n False,\n request,\n client_response.data,\n meta,\n metrics,\n client_response.tags,\n )\n\n\ndef send_feedback(\n user_model: Any,\n request: prediction_pb2.Feedback,\n predictive_unit_id: str,\n seldon_metrics: SeldonMetrics,\n) -> prediction_pb2.SeldonMessage:\n \"\"\"\n\n Parameters\n ----------\n user_model\n A Seldon user model\n request\n SeldonMesage proto\n predictive_unit_id\n The ID of the enclosing container predictive unit. Will be taken from environment.\n\n Returns\n -------\n\n \"\"\"\n seldon_metrics.update_reward(request.reward)\n\n if hasattr(user_model, \"send_feedback_rest\"):\n logger.warning(\"send_feedback_rest is deprecated. Please use send_feedback_raw\")\n request_json = json_format.MessageToJson(request)\n response_json = user_model.send_feedback_rest(request_json)\n return json_to_seldon_message(response_json)\n elif hasattr(user_model, \"send_feedback_grpc\"):\n logger.warning(\"send_feedback_grpc is deprecated. Please use send_feedback_raw\")\n response_json = user_model.send_feedback_grpc(request)\n return json_to_seldon_message(response_json)\n else:\n if hasattr(user_model, \"send_feedback_raw\"):\n try:\n response = user_model.send_feedback_raw(request)\n handle_raw_custom_metrics(\n response, seldon_metrics, True, FEEDBACK_METRIC_METHOD_TAG\n )\n return response\n except SeldonNotImplementedError:\n pass\n\n (datadef_request, features, truth, reward) = extract_feedback_request_parts(\n request\n )\n routing = request.response.meta.routing.get(predictive_unit_id)\n\n client_response = client_send_feedback(\n user_model, features, datadef_request.names, reward, truth, routing\n )\n\n metrics = client_custom_metrics(\n user_model,\n seldon_metrics,\n FEEDBACK_METRIC_METHOD_TAG,\n client_response.metrics,\n )\n\n if client_response.data is None:\n client_response.data = np.array([])\n\n return construct_response(\n user_model,\n False,\n request.request,\n client_response.data,\n None,\n metrics,\n client_response.tags,\n )\n\n\ndef transform_input(\n user_model: Any,\n request: Union[prediction_pb2.SeldonMessage, List, Dict],\n seldon_metrics: SeldonMetrics,\n) -> Union[prediction_pb2.SeldonMessage, List, Dict]:\n \"\"\"\n\n Parameters\n ----------\n user_model\n User defined class to handle transform input\n request\n The incoming request\n\n Returns\n -------\n The transformed request\n\n \"\"\"\n is_proto = isinstance(request, prediction_pb2.SeldonMessage)\n\n if hasattr(user_model, \"transform_input_rest\"):\n logger.warning(\n \"transform_input_rest is deprecated. Please use transform_input_raw\"\n )\n return user_model.transform_input_rest(request)\n elif hasattr(user_model, \"transform_input_grpc\"):\n logger.warning(\n \"transform_input_grpc is deprecated. Please use transform_input_raw\"\n )\n return user_model.transform_input_grpc(request)\n else:\n if hasattr(user_model, \"transform_input_raw\"):\n try:\n response = user_model.transform_input_raw(request)\n handle_raw_custom_metrics(\n response,\n seldon_metrics,\n is_proto,\n INPUT_TRANSFORM_METRIC_METHOD_TAG,\n )\n return response\n except SeldonNotImplementedError:\n pass\n\n if is_proto:\n (features, meta, datadef, data_type) = extract_request_parts(request)\n\n client_response = client_transform_input(\n user_model, features, datadef.names, meta=meta\n )\n\n metrics = client_custom_metrics(\n user_model,\n seldon_metrics,\n INPUT_TRANSFORM_METRIC_METHOD_TAG,\n client_response.metrics,\n )\n\n return construct_response(\n user_model,\n False,\n request,\n client_response.data,\n meta,\n metrics,\n client_response.tags,\n )\n else:\n (features, meta, datadef, data_type) = extract_request_parts_json(request)\n class_names = datadef[\"names\"] if datadef and \"names\" in datadef else []\n\n client_response = client_transform_input(\n user_model, features, class_names, meta=meta\n )\n\n metrics = client_custom_metrics(\n user_model,\n seldon_metrics,\n INPUT_TRANSFORM_METRIC_METHOD_TAG,\n client_response.metrics,\n )\n\n return construct_response_json(\n user_model,\n False,\n request,\n client_response.data,\n meta,\n metrics,\n client_response.tags,\n )\n\n\ndef transform_output(\n user_model: Any,\n request: Union[prediction_pb2.SeldonMessage, List, Dict],\n seldon_metrics: SeldonMetrics,\n) -> Union[prediction_pb2.SeldonMessage, List, Dict]:\n \"\"\"\n\n Parameters\n ----------\n user_model\n User defined class to handle transform input\n request\n The incoming request\n\n Returns\n -------\n The transformed request\n\n \"\"\"\n is_proto = isinstance(request, prediction_pb2.SeldonMessage)\n\n if hasattr(user_model, \"transform_output_rest\"):\n logger.warning(\n \"transform_input_rest is deprecated. Please use transform_input_raw\"\n )\n return user_model.transform_output_rest(request)\n elif hasattr(user_model, \"transform_output_grpc\"):\n logger.warning(\n \"transform_input_grpc is deprecated. Please use transform_input_raw\"\n )\n return user_model.transform_output_grpc(request)\n else:\n if hasattr(user_model, \"transform_output_raw\"):\n try:\n response = user_model.transform_output_raw(request)\n handle_raw_custom_metrics(\n response,\n seldon_metrics,\n is_proto,\n OUTPUT_TRANSFORM_METRIC_METHOD_TAG,\n )\n return response\n except SeldonNotImplementedError:\n pass\n\n if is_proto:\n (features, meta, datadef, data_type) = extract_request_parts(request)\n\n client_response = client_transform_output(\n user_model, features, datadef.names, meta=meta\n )\n\n metrics = client_custom_metrics(\n user_model,\n seldon_metrics,\n OUTPUT_TRANSFORM_METRIC_METHOD_TAG,\n client_response.metrics,\n )\n\n return construct_response(\n user_model,\n False,\n request,\n client_response.data,\n meta,\n metrics,\n client_response.tags,\n )\n else:\n (features, meta, datadef, data_type) = extract_request_parts_json(request)\n class_names = datadef[\"names\"] if datadef and \"names\" in datadef else []\n\n client_response = client_transform_output(\n user_model, features, class_names, meta=meta\n )\n\n metrics = client_custom_metrics(\n user_model,\n seldon_metrics,\n OUTPUT_TRANSFORM_METRIC_METHOD_TAG,\n client_response.metrics,\n )\n\n return construct_response_json(\n user_model,\n False,\n request,\n client_response.data,\n meta,\n metrics,\n client_response.tags,\n )\n\n\ndef route(\n user_model: Any,\n request: Union[prediction_pb2.SeldonMessage, List, Dict],\n seldon_metrics: SeldonMetrics,\n) -> Union[prediction_pb2.SeldonMessage, List, Dict]:\n \"\"\"\n Parameters\n ----------\n user_model\n A Seldon user model\n request\n A SelodonMessage proto\n seldon_metrics\n A SeldonMetrics instance\n Returns\n -------\n \"\"\"\n is_proto = isinstance(request, prediction_pb2.SeldonMessage)\n\n if hasattr(user_model, \"route_rest\"):\n logger.warning(\"route_rest is deprecated. Please use route_raw\")\n return user_model.route_rest(request)\n elif hasattr(user_model, \"route_grpc\"):\n logger.warning(\"route_grpc is deprecated. Please use route_raw\")\n return user_model.route_grpc(request)\n else:\n if hasattr(user_model, \"route_raw\"):\n try:\n response = user_model.route_raw(request)\n handle_raw_custom_metrics(\n response, seldon_metrics, is_proto, ROUTER_METRIC_METHOD_TAG\n )\n return response\n except SeldonNotImplementedError:\n pass\n\n if is_proto:\n (features, meta, datadef, data_type) = extract_request_parts(request)\n client_response = client_route(\n user_model, features, datadef.names, meta=meta\n )\n if not isinstance(client_response.data, int):\n raise SeldonMicroserviceException(\n \"Routing response must be int but got \" + str(client_response.data)\n )\n client_response_arr = np.array([[client_response.data]])\n\n metrics = client_custom_metrics(\n user_model,\n seldon_metrics,\n ROUTER_METRIC_METHOD_TAG,\n client_response.metrics,\n )\n\n return construct_response(\n user_model,\n False,\n request,\n client_response_arr,\n None,\n metrics,\n client_response.tags,\n )\n else:\n (features, meta, datadef, data_type) = extract_request_parts_json(request)\n class_names = datadef[\"names\"] if datadef and \"names\" in datadef else []\n client_response = client_route(user_model, features, class_names, meta=meta)\n if not isinstance(client_response.data, int):\n raise SeldonMicroserviceException(\n \"Routing response must be int but got \" + str(client_response.data)\n )\n client_response_arr = np.array([[client_response.data]])\n\n metrics = client_custom_metrics(\n user_model,\n seldon_metrics,\n ROUTER_METRIC_METHOD_TAG,\n client_response.metrics,\n )\n\n return construct_response_json(\n user_model,\n False,\n request,\n client_response_arr,\n None,\n metrics,\n client_response.tags,\n )\n\n\ndef aggregate(\n user_model: Any,\n request: Union[prediction_pb2.SeldonMessageList, List, Dict],\n seldon_metrics: SeldonMetrics,\n) -> Union[prediction_pb2.SeldonMessage, List, Dict]:\n \"\"\"\n Aggregate a list of payloads\n\n Parameters\n ----------\n user_model\n A Seldon user model\n request\n SeldonMessage proto\n seldon_metrics\n A SeldonMetrics instance\n\n Returns\n -------\n Aggregated SeldonMessage proto\n\n \"\"\"\n\n def merge_meta(meta_list):\n tags = {}\n for meta in meta_list:\n if meta:\n tags.update(meta.get(\"tags\", {}))\n return {\"tags\": tags}\n\n def merge_metrics(meta_list, custom_metrics):\n metrics = []\n for meta in meta_list:\n if meta:\n metrics.extend(meta.get(\"metrics\", []))\n metrics.extend(custom_metrics)\n return metrics\n\n is_proto = isinstance(request, prediction_pb2.SeldonMessageList)\n\n if hasattr(user_model, \"aggregate_rest\"):\n logger.warning(\"aggregate_rest is deprecated. Please use aggregate_raw\")\n return user_model.aggregate_rest(request)\n elif hasattr(user_model, \"aggregate_grpc\"):\n logger.warning(\"aggregate_grpc is deprecated. Please use aggregate_raw\")\n return user_model.aggregate_grpc(request)\n else:\n if hasattr(user_model, \"aggregate_raw\"):\n try:\n response = user_model.aggregate_raw(request)\n handle_raw_custom_metrics(\n response, seldon_metrics, is_proto, AGGREGATE_METRIC_METHOD_TAG\n )\n return response\n except SeldonNotImplementedError:\n pass\n\n if is_proto:\n features_list = []\n names_list = []\n meta_list = []\n\n for msg in request.seldonMessages:\n (features, meta, datadef, data_type) = extract_request_parts(msg)\n features_list.append(features)\n names_list.append(datadef.names)\n meta_list.append(meta)\n\n client_response = client_aggregate(user_model, features_list, names_list)\n\n metrics = client_custom_metrics(\n user_model,\n seldon_metrics,\n AGGREGATE_METRIC_METHOD_TAG,\n client_response.metrics,\n )\n\n return construct_response(\n user_model,\n False,\n request.seldonMessages[0],\n client_response.data,\n merge_meta(meta_list),\n merge_metrics(meta_list, metrics),\n client_response.tags,\n )\n else:\n features_list = []\n names_list = []\n\n if isinstance(request, list):\n msgs = request\n elif \"seldonMessages\" in request and isinstance(\n request[\"seldonMessages\"], list\n ):\n msgs = request[\"seldonMessages\"]\n else:\n raise SeldonMicroserviceException(\n f\"Invalid request data type: {request}\"\n )\n\n meta_list = []\n for msg in msgs:\n (features, meta, datadef, data_type) = extract_request_parts_json(msg)\n class_names = datadef[\"names\"] if datadef and \"names\" in datadef else []\n features_list.append(features)\n names_list.append(class_names)\n meta_list.append(meta)\n\n client_response = client_aggregate(user_model, features_list, names_list)\n\n metrics = client_custom_metrics(\n user_model,\n seldon_metrics,\n AGGREGATE_METRIC_METHOD_TAG,\n client_response.metrics,\n )\n\n return construct_response_json(\n user_model,\n False,\n msgs[0],\n client_response.data,\n merge_meta(meta_list),\n merge_metrics(meta_list, metrics),\n client_response.tags,\n )\n\n\ndef health_status(\n user_model: Any, seldon_metrics: SeldonMetrics\n) -> Union[prediction_pb2.SeldonMessage, List, Dict]:\n \"\"\"\n Call the user model to check the health of the model\n\n Parameters\n ----------\n user_model\n User defined class instance\n seldon_metrics\n A SeldonMetrics instance\n\n Returns\n -------\n Health check output\n \"\"\"\n\n if hasattr(user_model, \"health_status_raw\"):\n try:\n return user_model.health_status_raw()\n except SeldonNotImplementedError:\n pass\n\n client_response = client_health_status(user_model)\n metrics = client_custom_metrics(\n user_model, seldon_metrics, HEALTH_METRIC_METHOD_TAG\n )\n\n return construct_response_json(\n user_model, False, {}, client_response, None, metrics\n )\n\n\ndef init_metadata(user_model: Any) -> Dict:\n \"\"\"\n Call the user model to get the model init_metadata\n\n Parameters\n ----------\n user_model\n User defined class instance\n\n Returns\n -------\n Validated model metadata\n \"\"\"\n # meta_user: load metadata defined in the user_model instance\n if hasattr(user_model, \"init_metadata\"):\n try:\n meta_user = user_model.init_metadata()\n except SeldonNotImplementedError:\n meta_user = {}\n pass\n else:\n meta_user = {}\n\n if not isinstance(meta_user, dict):\n logger.error(\"init_metadata must return dict\")\n meta_user = {}\n\n # meta_env: load metadata from environmental variable\n try:\n meta_env = yaml.safe_load(os.environ.get(\"MODEL_METADATA\", \"{}\"))\n except yaml.YAMLError as e:\n logger.error(f\"Reading metadata from MODEL_METADATA env variable failed: {e}\")\n meta_env = {}\n\n meta = {**meta_user, **meta_env}\n\n try:\n return validate_model_metadata(meta)\n except SeldonInvalidMetadataError as e:\n logger.error(f\"Metadata validation error\\n{e}\")\n logger.error(f\"Failed to validate metadata {meta}\")\n return None\n"
] |
[
[
"numpy.array"
]
] |
RaulAstudillo06/BOCF
|
[
"68d19984385cdb27c9f6c5002c67fc9467bbe705"
] |
[
"GPyOpt/optimization/acquisition_optimizer.py"
] |
[
"# Copyright (c) 2016, the GPyOpt Authors\n# Licensed under the BSD 3-clause license (see LICENSE.txt)\n\nfrom .optimizer import OptLbfgs, OptSGD, OptDirect, OptCma, apply_optimizer, choose_optimizer, apply_optimizer_inner\nfrom .anchor_points_generator import ObjectiveAnchorPointsGenerator, ThompsonSamplingAnchorPointsGenerator\nfrom ..core.task.space import Design_space\nfrom GPyOpt.experiment_design import initial_design\nimport multiprocessing\nfrom pathos.multiprocessing import ProcessingPool as Pool\nimport numpy as np\nimport time\n\n\nmax_objective_anchor_points_logic = \"max_objective\"\nthompson_sampling_anchor_points_logic = \"thompsom_sampling\"\nsobol_design_type = \"sobol\"\nrandom_design_type = \"random\"\nlatin_design_type = \"latin\"\n\n\nclass AcquisitionOptimizer(object):\n \"\"\"\n General class for acquisition optimizers defined in domains with mix of discrete, continuous, bandit variables\n\n :param space: design space class from GPyOpt.\n :param optimizer: optimizer to use. Can be selected among:\n - 'lbfgs': L-BFGS.\n - 'DIRECT': Dividing Rectangles.\n - 'CMA': covariance matrix adaptation.\n \"\"\"\n\n def __init__(self, space, optimizer='lbfgs', inner_optimizer='lbfgs2', n_starting=400, n_anchor=16, **kwargs):\n\n self.space = space\n self.optimizer_name = optimizer\n self.inner_optimizer_name = inner_optimizer\n self.n_starting = n_starting\n self.n_anchor = n_anchor\n self.kwargs = kwargs\n\n ## -- save extra options than can be passed to the optimizer\n if 'model' in self.kwargs:\n self.model = self.kwargs['model']\n\n if 'anchor_points_logic' in self.kwargs:\n self.type_anchor_points_logic = self.kwargs['type_anchor_points_logic']\n else:\n self.type_anchor_points_logic = max_objective_anchor_points_logic\n\n ## -- Context handler: takes\n self.context_manager = ContextManager(space)\n ## -- Set optimizer and inner optimizer (WARNING: this won't update context)\n self.optimizer = choose_optimizer(self.optimizer_name, self.context_manager.noncontext_bounds)\n self.inner_optimizer = choose_optimizer(self.inner_optimizer_name, self.context_manager.noncontext_bounds)\n \n \n def optimize2(self, f=None, df=None, f_df=None, duplicate_manager=None):\n \"\"\"\n Optimizes the input function.\n\n :param f: function to optimize.\n :param df: gradient of the function to optimize.\n :param f_df: returns both the function to optimize and its gradient.\n\n \"\"\"\n self.f = f\n self.df = df\n self.f_df = f_df\n \n\n ## --- Update the optimizer, in case context has beee passed.\n self.optimizer = choose_optimizer(self.optimizer_name, self.context_manager.noncontext_bounds)\n\n ## --- Selecting the anchor points and removing duplicates\n if self.type_anchor_points_logic == max_objective_anchor_points_logic:\n anchor_points_generator = ObjectiveAnchorPointsGenerator(self.space, latin_design_type, f)\n elif self.type_anchor_points_logic == thompson_sampling_anchor_points_logic:\n anchor_points_generator = ThompsonSamplingAnchorPointsGenerator(self.space, sobol_design_type, self.model)\n \n ## -- Select the anchor points (with context)\n anchor_points = anchor_points_generator.get(duplicate_manager=duplicate_manager, context_manager=self.context_manager)\n print('anchor_points ready')\n print(anchor_points)\n pool = Pool(4)\n optimized_points = pool.map(self._parallel_optimization_wrapper, anchor_points)\n print('parallel')\n print(optimized_points)\n optimized_points2 = [apply_optimizer(self.optimizer, a, f=f, df=None, f_df=f_df, duplicate_manager=duplicate_manager, context_manager=self.context_manager, space = self.space) for a in anchor_points] \n print('sequential')\n print(optimized_points2)\n x_min, fx_min = min(optimized_points, key=lambda t:t[1])\n return x_min, fx_min\n \n \n def optimize(self, f=None, df=None, f_df=None, duplicate_manager=None, x_baseline=None):\n \"\"\"\n Optimizes the input function.\n\n :param f: function to optimize.\n :param df: gradient of the function to optimize.\n :param f_df: returns both the function to optimize and its gradient.\n\n \"\"\"\n self.f = f\n self.df = df\n self.f_df = f_df\n \n\n ## --- Update the optimizer, in case context has beee passed.\n self.optimizer = choose_optimizer(self.optimizer_name, self.context_manager.noncontext_bounds)\n\n ## --- Selecting the anchor points and removing duplicates\n if self.type_anchor_points_logic == max_objective_anchor_points_logic:\n anchor_points_generator = ObjectiveAnchorPointsGenerator(self.space, random_design_type, f, self.n_starting)\n elif self.type_anchor_points_logic == thompson_sampling_anchor_points_logic:\n anchor_points_generator = ThompsonSamplingAnchorPointsGenerator(self.space, sobol_design_type, self.model)\n \n ## -- Select the anchor points (with context)\n anchor_points, anchor_points_values = anchor_points_generator.get(num_anchor=self.n_anchor, duplicate_manager=duplicate_manager, context_manager=self.context_manager, get_scores=True)\n\n if x_baseline is not None:\n f_baseline = f(x_baseline)[:, 0]\n anchor_points = np.vstack((anchor_points, x_baseline))\n anchor_points_values = np.concatenate((anchor_points_values, f_baseline))\n #print(anchor_points.shape)\n #print(anchor_points_values.shape)\n print('anchor points')\n print(anchor_points)\n print(anchor_points_values)\n parallel = True\n if parallel:\n pool = Pool(4)\n optimized_points = pool.map(self._parallel_optimization_wrapper, anchor_points)\n else:\n #pass\n optimized_points = [apply_optimizer(self.optimizer, a, f=f, df=None, f_df=f_df, duplicate_manager=duplicate_manager, context_manager=self.context_manager, space = self.space) for a in anchor_points] \n \n print('optimized points')\n print(optimized_points) \n x_min, fx_min = min(optimized_points, key=lambda t:t[1])\n if x_baseline is not None:\n for i in range(x_baseline.shape[0]):\n val = f_baseline[i]\n if val < fx_min:\n print('baseline was best found')\n print(val)\n x_min = np.atleast_2d(x_baseline[i, :])\n fx_min = val\n #if np.asscalar(anchor_points_values[0]) < np.asscalar(fx_min):\n #print('anchor_point was best found')\n #fx_min = np.atleast_2d(anchor_points_values[0])\n #x_min = np.atleast_2d(anchor_points[0])\n\n return x_min, fx_min\n\n def optimize_comparison(self, f=None, df=None, f_df=None, duplicate_manager=None):\n \"\"\"\n Optimizes the input function.\n\n :param f: function to optimize.\n :param df: gradient of the function to optimize.\n :param f_df: returns both the function to optimize and its gradient.\n\n \"\"\"\n self.f = f\n self.df = df\n self.f_df = f_df\n\n ## --- Update the optimizer, in case context has beee passed.\n self.optimizer = choose_optimizer(self.optimizer_name, self.context_manager.noncontext_bounds)\n\n ## --- Selecting the anchor points and removing duplicates\n if self.type_anchor_points_logic == max_objective_anchor_points_logic:\n anchor_points_generator = ObjectiveAnchorPointsGenerator(self.space, random_design_type, f, self.n_starting)\n elif self.type_anchor_points_logic == thompson_sampling_anchor_points_logic:\n anchor_points_generator = ThompsonSamplingAnchorPointsGenerator(self.space, sobol_design_type, self.model)\n\n ## -- Select the anchor points (with context)\n anchor_points, anchor_points_values = anchor_points_generator.get(num_anchor=self.n_anchor,\n duplicate_manager=duplicate_manager,\n context_manager=self.context_manager,\n get_scores=True)\n print('anchor points')\n print(anchor_points)\n print(anchor_points_values)\n parallel = True\n if parallel:\n pool = Pool(4)\n optimized_points = pool.map(self._parallel_optimization_wrapper, anchor_points)\n print('optimized points')\n print(optimized_points)\n else:\n # pass\n optimized_points = [\n apply_optimizer(self.optimizer, a, f=f, df=None, f_df=f_df, duplicate_manager=duplicate_manager,\n context_manager=self.context_manager, space=self.space) for a in anchor_points]\n\n x_min, fx_min = min(optimized_points, key=lambda t: t[1])\n if np.asscalar(anchor_points_values[0]) < np.asscalar(fx_min):\n print('anchor_point was best found')\n fx_min = np.atleast_2d(anchor_points_values[0])\n x_min = np.atleast_2d(anchor_points[0])\n\n # Comparison\n print('sgd results')\n\n ## --- Update the optimizer, in case context has beee passed.\n self.optimizer = choose_optimizer('sgd', self.context_manager.noncontext_bounds)\n parallel = True\n if parallel:\n pool = Pool(4)\n optimized_points = pool.map(self._parallel_optimization_wrapper, anchor_points)\n print('optimized points')\n print(optimized_points)\n else:\n optimized_points = [\n apply_optimizer(self.optimizer, a, f=f, df=None, f_df=f_df, duplicate_manager=duplicate_manager,\n context_manager=self.context_manager, space=self.space) for a in anchor_points]\n\n x_min, fx_min = min(optimized_points, key=lambda t: t[1])\n if np.asscalar(anchor_points_values[0]) < np.asscalar(fx_min):\n print('anchor_point was best found')\n fx_min = np.atleast_2d(anchor_points_values[0])\n x_min = np.atleast_2d(anchor_points[0])\n\n return x_min, fx_min\n\n\n def optimize1(self, f=None, df=None, f_df=None, duplicate_manager=None):\n \"\"\"\n Optimizes the input function.\n\n :param f: function to optimize.\n :param df: gradient of the function to optimize.\n :param f_df: returns both the function to optimize and its gradient.\n\n \"\"\"\n self.f = f\n self.df = df\n self.f_df = f_df\n\n ## --- Update the optimizer, in case context has beee passed.\n self.optimizer = choose_optimizer(self.optimizer_name, self.context_manager.noncontext_bounds)\n\n ## --- Selecting the anchor points and removing duplicates\n if self.type_anchor_points_logic == max_objective_anchor_points_logic:\n anchor_points_generator = ObjectiveAnchorPointsGenerator(self.space, random_design_type, f)\n elif self.type_anchor_points_logic == thompson_sampling_anchor_points_logic:\n anchor_points_generator = ThompsonSamplingAnchorPointsGenerator(self.space, sobol_design_type, self.model)\n \n ## -- Select the anchor points (with context)\n anchor_points, anchor_points_values = anchor_points_generator.get(duplicate_manager=duplicate_manager, context_manager=self.context_manager)\n \n ## --- Applying local optimizers at the anchor points and update bounds of the optimizer (according to the context)\n optimized_points = [apply_optimizer(self.optimizer, a, f=f, df=None, f_df=f_df, duplicate_manager=duplicate_manager, context_manager=self.context_manager, space = self.space) for a in anchor_points] \n x_min, fx_min = min(optimized_points, key=lambda t:t[1])\n\n #x_min, fx_min = min([apply_optimizer(self.optimizer, a, f=f, df=None, f_df=f_df, duplicate_manager=duplicate_manager, context_manager=self.context_manager, space = self.space) for a in anchor_points], key=lambda t:t[1]) \n return x_min, fx_min\n \n \n def optimize_inner_func(self, f=None, df=None, f_df=None, duplicate_manager=None, n_starting=64, n_anchor=8):\n \"\"\"\n Optimizes the input function.\n\n :param f: function to optimize.\n :param df: gradient of the function to optimize.\n :param f_df: returns both the function to optimize and its gradient.\n\n \"\"\"\n self.f = f\n self.df = df\n self.f_df = f_df\n\n ## --- Update the optimizer, in case context has beee passed.\n self.inner_optimizer = choose_optimizer(self.inner_optimizer_name, self.context_manager.noncontext_bounds)\n\n ## --- Selecting the anchor points and removing duplicates\n if self.type_anchor_points_logic == max_objective_anchor_points_logic:\n anchor_points_generator = ObjectiveAnchorPointsGenerator(self.space, latin_design_type, f, n_starting)\n elif self.type_anchor_points_logic == thompson_sampling_anchor_points_logic:\n anchor_points_generator = ThompsonSamplingAnchorPointsGenerator(self.space, sobol_design_type, self.model)\n \n ## -- Select the anchor points (with context)\n anchor_points, anchor_points_values = anchor_points_generator.get(num_anchor=n_anchor, duplicate_manager=duplicate_manager, context_manager=self.context_manager, get_scores=True)\n #print(anchor_points)\n \n ## --- Applying local optimizers at the anchor points and update bounds of the optimizer (according to the context)\n optimized_points = [apply_optimizer_inner(self.inner_optimizer, a, f=f, df=None, f_df=f_df, duplicate_manager=duplicate_manager, context_manager=self.context_manager, space = self.space) for a in anchor_points]\n #print('inner optimized points')\n #print(optimized_points)\n x_min, fx_min = min(optimized_points, key=lambda t:t[1])\n #x_min = np.atleast_2d(anchor_points[0])\n #fx_min = np.atleast_2d(anchor_points_values[0]) \n return x_min, fx_min\n\n\n def optimize_inner_func2(self, f=None, df=None, f_df=None, duplicate_manager=None, n_starting=64, n_anchor=32):\n \"\"\"\n Optimizes the input function.\n\n :param f: function to optimize.\n :param df: gradient of the function to optimize.\n :param f_df: returns both the function to optimize and its gradient.\n\n \"\"\"\n self.f = f\n self.df = df\n self.f_df = f_df\n\n ## --- Update the optimizer, in case context has beee passed.\n self.inner_optimizer = choose_optimizer(self.inner_optimizer_name, self.context_manager.noncontext_bounds)\n\n ## --- Selecting the anchor points and removing duplicates\n if self.type_anchor_points_logic == max_objective_anchor_points_logic:\n anchor_points_generator = ObjectiveAnchorPointsGenerator(self.space, latin_design_type, f, n_starting)\n elif self.type_anchor_points_logic == thompson_sampling_anchor_points_logic:\n anchor_points_generator = ThompsonSamplingAnchorPointsGenerator(self.space, sobol_design_type, self.model)\n\n ## -- Select the anchor points (with context)\n anchor_points, anchor_points_values = anchor_points_generator.get(num_anchor=n_anchor,\n duplicate_manager=duplicate_manager,\n context_manager=self.context_manager,\n get_scores=True)\n\n ## --- Applying local optimizers at the anchor points and update bounds of the optimizer (according to the context)\n optimized_points = [\n apply_optimizer_inner(self.inner_optimizer, a, f=f, df=None, f_df=f_df, duplicate_manager=duplicate_manager,\n context_manager=self.context_manager, space=self.space) for a in anchor_points]\n\n x_min, fx_min = min(optimized_points, key=lambda t: t[1])\n print('test begins')\n optimized_points2 = optimized_points[0:2]\n x_min2, fx_min2 = min(optimized_points2, key=lambda t: t[1])\n print(fx_min2-fx_min)\n time.sleep(1)\n #for i in range(len(optimized_points)):\n #if np.array_equal(optimized_points[i][0], x_min):\n #print('optimal point was found at anchor point: {}'.format(i))\n #break\n # x_min = np.atleast_2d(anchor_points[0])\n # fx_min = np.atleast_2d(anchor_points_values[0])\n return x_min, fx_min\n \n def _parallel_optimization_wrapper(self, x0):\n #print(x0)\n return apply_optimizer(self.optimizer, x0, self.f, None, self.f_df)\n\n\nclass ContextManager(object):\n \"\"\"\n class to handle the context variable in the optimizer\n :param space: design space class from GPyOpt.\n :param context: dictionary of variables and their contex values\n \"\"\"\n\n def __init__ (self, space, context = None):\n self.space = space\n self.all_index = list(range(space.model_dimensionality))\n self.all_index_obj = list(range(len(self.space.config_space_expanded)))\n self.context_index = []\n self.context_value = []\n self.context_index_obj = []\n self.nocontext_index_obj= self.all_index_obj\n self.noncontext_bounds = self.space.get_bounds()[:]\n self.noncontext_index = self.all_index[:]\n\n if context is not None:\n #print('context')\n\n ## -- Update new context\n for context_variable in context.keys():\n variable = self.space.find_variable(context_variable)\n self.context_index += variable.index_in_model\n self.context_index_obj += variable.index_in_objective\n self.context_value += variable.objective_to_model(context[context_variable])\n\n ## --- Get bounds and index for non context\n self.noncontext_index = [idx for idx in self.all_index if idx not in self.context_index]\n self.noncontext_bounds = [self.noncontext_bounds[idx] for idx in self.noncontext_index]\n\n ## update non context index in objective\n self.nocontext_index_obj = [idx for idx in self.all_index_obj if idx not in self.context_index_obj]\n\n\n\n def _expand_vector(self,x):\n '''\n Takes a value x in the subspace of not fixed dimensions and expands it with the values of the fixed ones.\n :param x: input vector to be expanded by adding the context values\n '''\n x = np.atleast_2d(x)\n x_expanded = np.zeros((x.shape[0],self.space.model_dimensionality))\n x_expanded[:,np.array(self.noncontext_index).astype(int)] = x\n x_expanded[:,np.array(self.context_index).astype(int)] = self.context_value\n return x_expanded\n"
] |
[
[
"numpy.concatenate",
"numpy.array",
"numpy.zeros",
"numpy.asscalar",
"numpy.vstack",
"numpy.atleast_2d"
]
] |
shishaochen/kfac
|
[
"3ee1bec8dcd851d50618cd542a8d1aff92512f7c"
] |
[
"kfac/python/ops/layer_collection.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\"\"\"Registry for layers and their parameters/variables.\n\nThis represents the collection of all layers in the approximate Fisher\ninformation matrix to which a particular FisherBlock may belong. That is, we\nmight have several layer collections for one TF graph (if we have multiple K-FAC\noptimizers being used, for example.)\n\nThe model and loss function are registered using the register_XXX() methods.\nA subset of the layer types can be handled with the auto_register_layers()\nmethod.\n\nNote that the data formats in the docstrings for the register_XXX() methods\nmust be strictly adhered to. So for example, if a method asks for a Tensor of\nshape [batch_size, ...], then the first dimension must be the batch size and\nnothing else. And the tensors must contain actual data, not a mixture of real\nand fake data / zeros generated by mini-batch padding, for example. (Padding\nis only fine if it's treated as regular data by both your model and loss\nfunction. e.g. adding \"blank tokens\" at the end of a sequence which the model\nis still expected to predict.) If a method asks for the parameters of a layer\nthen they must be the actual variable object(s) for said parameters, not a\ntensor formed by reshaping, re-casting, or tranposing its value.\n\nIf the internal data format used by your model isn't natively supported by\nthis system, you shouldn't try to crow-bar the arguments of the registration\nmethods until they seem to fit. Although the K-FAC code tries to protect\nagainst some common mistakes, it may often seem to run fine with incorrect\nregistrations, generating no exceptions or errors. But this will almost\ncertainly lead to (potentially severe) underperformance of the method.\n\nIf you have model code that doesn't represent tensors in the format expected\nby K-FAC, one thing you can try is introducing transformations that perform the\nconversion back and forth. But make sure the format that you convert to is\nactually valid according to the strict specifications of the registration\nfunction docstrings (e.g. that batch_size really is the mini-batch size, etc).\n\nSo if \"x\" is some data needed in the registration function that isn't of the\ncorrect format, you can try something like the following:\n\nx_transformed = transform(x)\nlc.register_XXX(x_transformed)\nx = untransform(x_transformed)\n...use x in rest of model...\n\nNote that without \"x = untransform(x_transformed)\" this often won't work since\nx_transformed won't be part of the model's forward graph, which is something\nK-FAC needs (especially for the \"output\" arguments of layers).\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom collections import defaultdict\nfrom collections import OrderedDict\nfrom contextlib import contextmanager\nfrom functools import partial\nimport math\n\n# Dependency imports\nimport six\nimport tensorflow.compat.v1 as tf\n\nfrom tensorflow.python.util import nest\nfrom kfac.python.ops import fisher_blocks as fb\nfrom kfac.python.ops import loss_functions as lf\nfrom kfac.python.ops import utils\nfrom kfac.python.ops.tensormatch import graph_search\n\n# Names for various approximations that can be requested for Fisher blocks.\nAPPROX_KRONECKER_NAME = \"kron\"\nAPPROX_KRONECKER_IN_DIAG_NAME = \"kron_in_diag\"\nAPPROX_KRONECKER_OUT_DIAG_NAME = \"kron_out_diag\"\nAPPROX_KRONECKER_BOTH_DIAG_NAME = \"kron_both_diag\"\nAPPROX_DIAGONAL_NAME = \"diagonal\"\nAPPROX_FULL_NAME = \"full\"\n\nAPPROX_KRONECKER_INDEP_NAME = \"kron_indep\"\nAPPROX_KRONECKER_INDEP_IN_DIAG_NAME = \"kron_indep_in_diag\"\nAPPROX_KRONECKER_INDEP_OUT_DIAG_NAME = \"kron_indep_out_diag\"\nAPPROX_KRONECKER_INDEP_BOTH_DIAG_NAME = \"kron_indep_both_diag\"\nAPPROX_KRONECKER_SERIES_1_NAME = \"kron_series_1\"\nAPPROX_KRONECKER_SERIES_2_NAME = \"kron_series_2\"\nAPPROX_KRONECKER_SUA_NAME = \"kron_sua\"\n\n\n# Possible value for 'reuse' keyword argument. Sets 'reuse' to\n# tf.get_variable_scope().reuse.\nVARIABLE_SCOPE = \"VARIABLE_SCOPE\"\n\n_DEFAULT_LAYER_COLLECTION = None\n\n\ndef get_default_layer_collection():\n \"\"\"Get default LayerCollection.\"\"\"\n if _DEFAULT_LAYER_COLLECTION is None:\n raise ValueError(\n \"Attempted to retrieve default LayerCollection when none is set. Use \"\n \"LayerCollection.as_default().\")\n\n return _DEFAULT_LAYER_COLLECTION\n\n\ndef set_default_layer_collection(layer_collection):\n global _DEFAULT_LAYER_COLLECTION\n\n if _DEFAULT_LAYER_COLLECTION is not None and layer_collection is not None:\n raise ValueError(\"Default LayerCollection is already set.\")\n\n _DEFAULT_LAYER_COLLECTION = layer_collection\n\n\nclass LayerParametersDict(OrderedDict):\n \"\"\"An OrderedDict where keys are Tensors or tuples of Tensors.\n\n Ensures that no Tensor is associated with two different keys.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n self._tensors = set()\n super(LayerParametersDict, self).__init__(*args, **kwargs)\n\n def __setitem__(self, key, value):\n key = self._canonicalize_key(key)\n tensors = key if isinstance(key, (tuple, list)) else (key,)\n key_collisions = self._tensors.intersection(tensors)\n if key_collisions:\n raise ValueError(\"Key(s) already present: {}\".format(key_collisions))\n self._tensors.update(tensors)\n super(LayerParametersDict, self).__setitem__(key, value)\n\n def __delitem__(self, key):\n key = self._canonicalize_key(key)\n self._tensors.remove(key)\n super(LayerParametersDict, self).__delitem__(key)\n\n def __getitem__(self, key):\n key = self._canonicalize_key(key)\n return super(LayerParametersDict, self).__getitem__(key)\n\n def __contains__(self, key):\n key = self._canonicalize_key(key)\n return super(LayerParametersDict, self).__contains__(key)\n\n def _canonicalize_key(self, key):\n if isinstance(key, (list, tuple)):\n return tuple(key)\n return key\n\n\n# TODO(b/68034464): add capability for LayerCollection to be \"finalized\"\n# and do this when it gets used by FisherEstimator / KfacOptimizer.\n\n\nclass LayerCollection(object):\n \"\"\"Registry of information about layers and losses.\n\n Note that you need to create a new one of these for each FisherEstimator or\n KfacOptimizer, as they can't be used more than once.\n\n The methods that you should interact with directly are:\n - register_XXX()\n - auto_register_layers()\n\n Additional control over the automatic registration process can be exerted by\n using the methods/properties:\n - set_default_XXX() and default_XXX\n - define_linked_parameters() and linked_parameters\n\n\n Attributes:\n fisher_blocks: a LayersParamsDict (subclass of OrderedDict) mapping layer\n parameters (Tensors or tuples of Tensors) to FisherBlock instances.\n fisher_factors: an OrderedDict mapping tuples to FisherFactor instances.\n losses: a list of LossFunction objects. The loss to be optimized is their\n sum.\n loss_colocation_ops: ops to colocate loss function evaluations with. These\n will typically be the inputs to the losses.\n \"\"\"\n\n def __init__(self,\n graph=None,\n name=\"LayerCollection\"):\n self.fisher_blocks = LayerParametersDict()\n self.fisher_factors = OrderedDict()\n self._linked_parameters = dict(\n ) # dict mapping sets of variables to optionally specified approximations.\n self._graph = graph or tf.get_default_graph()\n self._loss_dict = OrderedDict() # {str: LossFunction}\n self._subgraph = None\n self._default_generic_approximation = APPROX_DIAGONAL_NAME\n self._default_fully_connected_approximation = APPROX_KRONECKER_NAME\n self._default_conv2d_approximation = APPROX_KRONECKER_NAME\n self._default_fully_connected_multi_approximation = (\n APPROX_KRONECKER_INDEP_NAME)\n self._default_conv2d_multi_approximation = (\n APPROX_KRONECKER_INDEP_NAME)\n self._default_scale_and_shift_approximation = APPROX_FULL_NAME\n self.loss_colocation_ops = {}\n self.loss_coeffs = {}\n self._vars_to_uses = defaultdict(lambda: 0)\n\n self._finalized = False\n\n with tf.variable_scope(None, default_name=name) as scope:\n self._var_scope = scope.name\n\n self._generic_approx_to_block_types = {\n APPROX_FULL_NAME: fb.NaiveFullFB,\n APPROX_DIAGONAL_NAME: fb.NaiveDiagonalFB,\n }\n\n self._fully_connected_approx_to_block_types = {\n APPROX_KRONECKER_NAME: fb.FullyConnectedKFACBasicFB,\n APPROX_KRONECKER_IN_DIAG_NAME:\n partial(fb.FullyConnectedKFACBasicFB,\n diagonal_approx_for_input=True),\n APPROX_KRONECKER_OUT_DIAG_NAME:\n partial(fb.FullyConnectedKFACBasicFB,\n diagonal_approx_for_output=True),\n APPROX_KRONECKER_BOTH_DIAG_NAME:\n partial(fb.FullyConnectedKFACBasicFB,\n diagonal_approx_for_input=True,\n diagonal_approx_for_output=True),\n APPROX_DIAGONAL_NAME: fb.FullyConnectedDiagonalFB,\n }\n\n self._conv2d_approx_to_block_types = {\n APPROX_KRONECKER_NAME: fb.ConvKFCBasicFB,\n APPROX_DIAGONAL_NAME: fb.ConvDiagonalFB,\n APPROX_KRONECKER_SUA_NAME: fb.ConvKFCBasicFB,\n }\n\n self._fully_connected_multi_approx_to_block_types = {\n APPROX_KRONECKER_INDEP_NAME:\n fb.FullyConnectedMultiIndepFB,\n APPROX_KRONECKER_INDEP_IN_DIAG_NAME:\n partial(fb.FullyConnectedMultiIndepFB,\n diagonal_approx_for_input=True),\n APPROX_KRONECKER_INDEP_OUT_DIAG_NAME:\n partial(fb.FullyConnectedMultiIndepFB,\n diagonal_approx_for_output=True),\n APPROX_KRONECKER_INDEP_BOTH_DIAG_NAME:\n partial(fb.FullyConnectedMultiIndepFB,\n diagonal_approx_for_input=True,\n diagonal_approx_for_output=True),\n APPROX_KRONECKER_SERIES_1_NAME:\n partial(fb.FullyConnectedSeriesFB, option=1),\n APPROX_KRONECKER_SERIES_2_NAME:\n partial(fb.FullyConnectedSeriesFB, option=2)\n }\n\n self._conv2d_multi_approx_to_block_types = {\n APPROX_KRONECKER_INDEP_NAME: fb.ConvKFCBasicMultiIndepFB\n }\n\n self._scale_and_shift_approx_to_block_types = {\n APPROX_FULL_NAME: fb.ScaleAndShiftFullFB,\n APPROX_DIAGONAL_NAME: fb.ScaleAndShiftDiagonalFB\n }\n\n @property\n def losses(self):\n \"\"\"Tuple of LossFunction objects registered with this LayerCollection.\"\"\"\n return nest.flatten(self.towers_by_loss)\n\n @property\n def towers_by_loss(self):\n \"\"\"Tuple across losses of LossFunction objects registered to each tower.\"\"\"\n return tuple(tuple(lst) for lst in self._loss_dict.values())\n\n @property\n def registered_variables(self):\n \"\"\"A tuple of all of the variables currently registered.\"\"\"\n tuple_of_tuples = (utils.ensure_sequence(key) for key, block\n in six.iteritems(self.fisher_blocks))\n flat_tuple = tuple(item for tuple_ in tuple_of_tuples for item in tuple_)\n return flat_tuple\n\n @property\n def linked_parameters(self):\n \"\"\"Groups of parameters with an optionally specified approximation.\n\n Linked parameters can be added using `define_linked_parameters`.\n If an approximation is specified, then this approximation will be used\n when registering a layer with exactly these parameters, unless an\n approximation is specified when calling the registration function.\n\n Returns:\n A `dict` mapping tuples of parameters to an optional string.\n \"\"\"\n return self._linked_parameters\n\n @property\n def default_generic_approximation(self):\n return self._default_generic_approximation\n\n def set_default_generic_approximation(self, value):\n if value not in self._generic_approx_to_block_types:\n raise ValueError(\n \"{} is not a valid approximation for generic variables.\".format(\n value))\n self._default_generic_approximation = value\n\n @property\n def default_fully_connected_approximation(self):\n return self._default_fully_connected_approximation\n\n def set_default_fully_connected_approximation(self, value):\n if value not in self._fully_connected_approx_to_block_types:\n raise ValueError(\n \"{} is not a valid approximation for fully connected layers.\".format(\n value))\n self._default_fully_connected_approximation = value\n\n @property\n def default_conv2d_approximation(self):\n return self._default_conv2d_approximation\n\n def set_default_conv2d_approximation(self, value):\n if value not in self._conv2d_approx_to_block_types:\n raise ValueError(\n \"{} is not a valid approximation for 2d convolutional layers.\".format(\n value))\n self._default_conv2d_approximation = value\n\n @property\n def default_fully_connected_multi_approximation(self):\n return self._default_fully_connected_multi_approximation\n\n def set_default_fully_connected_multi_approximation(self, value):\n if value not in self._fully_connected_multi_approx_to_block_types:\n raise ValueError(\"{} is not a valid approximation for a fully-connected \"\n \"multi layer.\".format(value))\n self._default_fully_connected_multi_approximation = value\n\n @property\n def default_conv2d_multi_approximation(self):\n return self._default_conv2d_multi_approximation\n\n def set_default_conv2d_multi_approximation(self, value):\n if value not in self._conv2d_multi_approx_to_block_types:\n raise ValueError(\"{} is not a valid approximation for a conv2d \"\n \"multi layer.\".format(value))\n self._default_conv2d_multi_approximation = value\n\n @property\n def default_scale_and_shift_approximation(self):\n return self._default_scale_and_shift_approximation\n\n def set_default_scale_and_shift_approximation(self, value):\n if value not in self._scale_and_shift_approx_to_block_types:\n raise ValueError(\"{} is not a valid approximation for a scale & shift \"\n \"layer.\".format(value))\n self._default_scale_and_shift_approximation = value\n\n def auto_register_layers(self, var_list=None, batch_size=None):\n \"\"\"Registers remaining unregistered layers automatically using a scanner.\n\n Requires all function / distribution registrations to be performed\n (manually) first.\n\n Registrations will be performed using the default approximation mode for\n each type, as if the scanner were calling the user-level registration\n functions in this LayerCollection object (which it will be). These\n defaults can be overridden using the set_default_XXX_approximation methods\n for types of layers, or using the define_linked_parameters method for\n specific parameters.\n\n This function should only be called after any desired manual registrations\n are performed. For example, if you have a layer which isn't recognized\n properly by the scanner, or a layer which you want to register differently.\n\n Note that this function is an experimental convenience feature which won't\n work for every possible model architecture. Any layers/parameters that\n whose structure is not recognized will be registered as \"generic\", which\n is the worst curvature matrix approximation available in the system, and\n should be avoided if possible.\n\n See the docstring for register_layers in graph_search.py for more details.\n\n Args:\n var_list: A list of variables that the automatic registration should\n consider. If you have some trainable variables (i.e. those included in\n tf.trainable_variables()) that you don't want included you need to pass\n in this list. (Default: tf.trainable_variables()).\n batch_size: A `int` representing the batch size. Needs to specified if\n registering generic variables that don't match any layer patterns or\n if time/uses is folded. If the time/uses dimension is merged with\n batch then this is used to infer number of uses/time-steps. NOTE: In the\n replicated context this must be the per-replica batch size, and not\n the total batch size.\n \"\"\"\n if var_list is None:\n var_list = tf.trainable_variables()\n graph_search.register_layers(self, var_list, batch_size=batch_size)\n\n def finalize(self):\n if not self._finalized:\n self._create_subgraph()\n self._finalized = True\n else:\n raise ValueError(\"LayerCollection was finalized a second time, which \"\n \"indicates an error. Perhaps you used the same \"\n \"LayerCollection object in multiple \"\n \"optimizers/estimators, which is not allowed.\")\n\n def _register_block(self, layer_key, fisher_block, reuse=VARIABLE_SCOPE):\n \"\"\"Validates and registers the layer_key associated with the fisher_block.\n\n Args:\n layer_key: A variable or tuple of variables. The key to check for in\n existing registrations and to register if valid.\n fisher_block: The associated `FisherBlock`.\n reuse: Method to use for inserting new `FisherBlock`s. One of True, False,\n or 'VARIABLE_SCOPE'.\n\n Raises:\n ValueError: If `layer_key` was already registered and reuse is `False`,\n if `layer_key` was registered with a different block type, or if\n `layer_key` shares any variables with but is not equal to a previously\n registered key.\n KeyError: If `reuse` is `True` but `layer_key` was not previously\n registered.\n\n Returns:\n The `FisherBlock` registered under `layer_key`. If `layer_key` was already\n registered, this will be the previously registered `FisherBlock`.\n \"\"\"\n if self._finalized:\n raise ValueError(\"You cannot register additional losses or layers after \"\n \"LayerCollection is finalized. Finalization happens \"\n \"after the estimator or optimizer object first uses \"\n \"the data in the LayerCollection. For example, when \"\n \"the minimize() method is called in \"\n \"PeriodicInvCovUpdateKfacOpt.\")\n\n if reuse is VARIABLE_SCOPE:\n reuse = tf.get_variable_scope().reuse\n\n if reuse is True or (reuse is tf.AUTO_REUSE and\n layer_key in self.fisher_blocks):\n\n if layer_key not in self.fisher_blocks:\n raise ValueError(\n \"reuse was True for attempted registration involving variables {}, \"\n \"but no previously registered layer was found for these. Perhaps \"\n \"reuse was set to True by mistake. One way this can happen is if \"\n \"reuse is set to True in the surrounding variable scope.\"\n \"\".format(layer_key))\n\n result = self.fisher_blocks[layer_key]\n\n if type(result) != type(fisher_block): # pylint: disable=unidiomatic-typecheck\n raise ValueError(\n \"Attempted to register FisherBlock of type %s when existing \"\n \"FisherBlock has type %s.\" % (type(fisher_block), type(result)))\n return result\n if reuse is False and layer_key in self.fisher_blocks:\n raise ValueError(\"FisherBlock for %s is already in LayerCollection.\" %\n (layer_key,))\n\n # Insert fisher_block into self.fisher_blocks.\n if layer_key in self.fisher_blocks:\n raise ValueError(\"Duplicate registration: {}\".format(layer_key))\n # Raise an error if any variable in layer_key has been registered in any\n # other blocks.\n variable_to_block = {\n var: (params, block)\n for (params, block) in self.fisher_blocks.items()\n for var in utils.ensure_sequence(params)\n }\n for variable in utils.ensure_sequence(layer_key):\n if variable in variable_to_block:\n prev_key, prev_block = variable_to_block[variable]\n raise ValueError(\n \"Attempted to register layer_key {} with block {}, but variable {}\"\n \" was already registered in key {} with block {}.\".format(\n layer_key, fisher_block, variable, prev_key, prev_block))\n self.fisher_blocks[layer_key] = fisher_block\n return fisher_block\n\n def _register_loss_function(self,\n loss,\n colocation_op,\n base_name,\n name=None,\n coeff=1.0,\n reuse=VARIABLE_SCOPE):\n \"\"\"Registers a LossFunction object.\n\n Args:\n loss: The LossFunction object.\n colocation_op: The op to colocate the loss function's computations with.\n base_name: The name to derive a new unique name from is the name argument\n is None.\n name: (OPTIONAL) str or None. Unique name for this loss function. If None,\n a new name is generated. (Default: None)\n coeff: (OPTIONAL) a scalar. coefficient on the loss function\n (Default: 1.0)\n reuse: (OPTIONAL) bool or str. If True, adds 'loss' as an additional\n tower for the existing loss function.\n\n Raises:\n ValueError: If reuse == True and name == None.\n ValueError: If reuse == True and seed != None.\n KeyError: If reuse == True and no existing LossFunction with 'name' found.\n KeyError: If reuse == False and existing LossFunction with 'name' found.\n \"\"\"\n\n if self._finalized:\n raise ValueError(\"You cannot register additional losses or layers after \"\n \"LayerCollection is finalized. Finalization happens \"\n \"after the estimator or optimizer object first uses \"\n \"the data in the LayerCollection. For example, when \"\n \"the minimize() method is called in \"\n \"PeriodicInvCovUpdateKfacOpt.\")\n\n name = name or self._graph.unique_name(base_name)\n\n if reuse == VARIABLE_SCOPE:\n reuse = tf.get_variable_scope().reuse\n\n if reuse:\n if name is None:\n raise ValueError(\n \"If reuse is enabled, loss function's name must be set.\")\n\n loss_list = self._loss_dict.get(name, None)\n\n if loss_list is None:\n raise KeyError(\n \"Unable to find loss function named {}. Register a new loss \"\n \"function with reuse=False.\".format(name))\n\n if self.loss_coeffs[loss_list[0]] != coeff:\n raise ValueError(\n \"Reused loss function's coeff didn't match previous supplied \"\n \"value.\")\n\n else:\n if name in self._loss_dict:\n raise KeyError(\n \"Loss function named {} already exists. Set reuse=True to append \"\n \"another tower.\".format(name))\n\n loss_list = []\n self._loss_dict[name] = loss_list\n\n loss_list.append(loss)\n self.loss_colocation_ops[loss] = colocation_op\n self.loss_coeffs[loss] = coeff\n\n def _get_use_count_map(self):\n \"\"\"Returns a dict mapping variables to their number of registrations.\"\"\"\n return self._vars_to_uses\n\n def _add_uses(self, params, uses):\n \"\"\"Register additional uses by params in the graph.\n\n Args:\n params: Variable or tuple of Variables. Parameters for a layer.\n uses: int or float. Number of additional uses for these parameters.\n \"\"\"\n params = params if isinstance(params, (tuple, list)) else (params,)\n for var in params:\n self._vars_to_uses[var] += uses\n\n def check_registration(self, variables):\n \"\"\"Checks that all variable uses have been registered properly.\n\n Args:\n variables: List of variables.\n\n Raises:\n ValueError: If any registered variables are not included in the list.\n ValueError: If any variable in the list is not registered.\n ValueError: If any variable in the list is registered with the wrong\n number of \"uses\" in the subgraph recorded (vs the number of times that\n variable is actually used in the subgraph).\n \"\"\"\n # Note that overlapping parameters (i.e. those that share variables) will\n # be caught by layer_collection.LayerParametersDict during registration.\n\n reg_use_map = self._get_use_count_map()\n\n error_messages = []\n\n for var in variables:\n total_uses = self.subgraph.variable_uses(var)\n reg_uses = reg_use_map[var]\n\n if reg_uses == 0:\n error_messages.append(\"Variable {} not registered.\".format(var))\n elif (not math.isinf(reg_uses)) and reg_uses != total_uses:\n error_messages.append(\n \"Variable {} registered with wrong number of uses ({} uses \"\n \"registered vs {} uses found in sub-graph generated from \"\n \"registered losses).\".format(var, reg_uses, total_uses))\n\n num_get_vars = len(reg_use_map)\n\n if num_get_vars > len(variables):\n error_messages.append(\"{} registered variables were not included in list.\"\n .format(num_get_vars - len(variables)))\n\n if error_messages:\n error_string = \"\\n\\t\".join([\n \"Found the following errors with variable registration:\"\n ] + error_messages)\n raise ValueError(error_string)\n\n def get_blocks(self):\n return tuple(self.fisher_blocks.values())\n\n def get_factors(self):\n return tuple(self.fisher_factors.values())\n\n @property\n def graph(self):\n return self._graph\n\n @property\n def subgraph(self):\n return self._subgraph\n\n def define_linked_parameters(self, params, approximation=None):\n \"\"\"Identify a set of parameters that should be grouped together.\n\n Also allows the approximation type string to be set for the given\n parameter grouping.\n\n During automatic graph scanning (as done by the auto_register_layers method)\n any matches containing variables that have been identified as part of a\n linked group will be filtered out unless the match parameters are exactly\n equal to the ones specified in the linked group.\n\n Args:\n params: A variable, or a tuple or list of variables. The variables\n to be linked.\n approximation: Optional string specifying the type of approximation to use\n for these variables. If unspecified, this layer collection's default\n approximation for the layer type will be used.\n\n Raises:\n ValueError: If the parameters were already registered in a layer or\n identified as part of an incompatible group.\n \"\"\"\n params = frozenset(utils.ensure_sequence(params))\n\n # Check if any of the variables in 'params' is already in\n # 'self.fisher_blocks.keys()'.\n for registered_params, fisher_block in self.fisher_blocks.items():\n registered_params_set = set(utils.ensure_sequence(registered_params))\n for variable in params:\n if (variable in registered_params_set and\n params != registered_params_set):\n raise ValueError(\n \"Can't link parameters {}, variable {} was already registered in \"\n \"group {} with layer {}\".format(params, variable,\n registered_params, fisher_block))\n\n # Check if any of the variables in 'params' is already in\n # 'self.linked_parameters'.\n for variable in params:\n for other_linked_params in self.linked_parameters:\n if variable in other_linked_params:\n raise ValueError(\"Can't link parameters {}, variable {} was already \"\n \"linked in group {}.\".format(params, variable,\n other_linked_params))\n self._linked_parameters[params] = approximation\n\n def _create_subgraph(self):\n if not self.losses:\n raise ValueError(\"Must have at least one registered loss.\")\n inputs_to_losses = nest.flatten(tuple(loss.inputs for loss in self.losses))\n self._subgraph = utils.SubGraph(inputs_to_losses)\n\n def eval_losses(self, target_mode=\"data\", coeff_mode=\"regular\"):\n \"\"\"Returns evaluated losses (colocated with inputs to losses).\"\"\"\n evals = []\n for loss in self.losses:\n with tf.colocate_with(self.loss_colocation_ops[loss]):\n if target_mode == \"data\":\n loss_value = loss.evaluate()\n elif target_mode == \"sample\":\n loss_value = loss.evaluate_on_sample()\n else:\n raise ValueError(\"target_mode must be in ['data', 'sample']\")\n\n if coeff_mode == \"regular\":\n multiplier = self.loss_coeffs[loss]\n elif coeff_mode == \"sqrt\":\n multiplier = tf.sqrt(self.loss_coeffs[loss])\n elif coeff_mode == \"off\":\n multiplier = 1.0\n else:\n raise ValueError(\"coeff_mode must be in ['regular', 'sqrt', 'off']\")\n multiplier = tf.cast(multiplier, dtype=loss_value.dtype)\n evals.append(multiplier * loss_value)\n return evals\n\n def total_loss(self, coeff_mode=\"regular\"):\n return tf.add_n(self.eval_losses(target_mode=\"data\",\n coeff_mode=coeff_mode))\n\n def total_sampled_loss(self, coeff_mode=\"regular\"):\n return tf.add_n(self.eval_losses(target_mode=\"sample\",\n coeff_mode=coeff_mode))\n\n def _get_linked_approx(self, params):\n \"\"\"If params were linked, return their specified approximation.\"\"\"\n params_set = frozenset(utils.ensure_sequence(params))\n if params_set in self.linked_parameters:\n return self.linked_parameters[params_set]\n else:\n return None\n\n def _get_block_type(self, params, approx, default, approx_to_type):\n if approx is None:\n approx = self._get_linked_approx(params)\n if approx is None:\n approx = default\n\n if approx not in approx_to_type:\n raise ValueError(\"Bad value {} for approx.\".format(approx))\n\n return approx_to_type[approx], approx\n\n def register_fully_connected(self,\n params,\n inputs,\n outputs,\n approx=None,\n dense_inputs=True,\n reuse=VARIABLE_SCOPE):\n \"\"\"Registers a fully connected layer.\n\n Args:\n params: Variable or 2-tuple of variables corresponding to weight and\n bias parameters of this layer. Weight matrix should have shape\n [input_size, output_size]. Bias should have shape [output_size].\n inputs: Tensor. Two formats are accepted. In most cases the Tensor is\n dense inputs, with shape [batch_size, input_size]. In some cases\n the Tensor is sparse inputs, with shape [batch_size]. A typical example\n of sparse inputs is the vocab indices into an embedding matrix. Sparse\n inputs will be converted to the dense format within KFAC. For sparse\n inputs, dense_inputs should be set to False.\n outputs: Tensor of shape [batch_size, output_size]. Outputs\n produced by layer.\n approx: str or None. If not None must be one of \"kron\", \"kron_in_diag\"\n (diagonal approximation for the input kronecker factor), \"kron_out_diag\"\n (diagonal approximation for the output kronecker factor),\n \"kron_both_diag\" or \"diagonal\". The Fisher approximation to use. If\n None the default value is used. (Default: None)\n dense_inputs: bool. True if inputs are dense inputs. (Default: True)\n reuse: bool or str. If True, this adds 'inputs' and 'outputs' as an\n additional mini-batch/tower of data to use when estimating the Fisher\n block for this layer (which must have already been registered). If\n \"VARIABLE_SCOPE\", use tf.get_variable_scope().reuse.\n (Default: \"VARIABLE_SCOPE\")\n\n Raises:\n ValueError: For improper value to 'approx'.\n KeyError: If reuse == True but no FisherBlock found for 'params'.\n ValueError: If reuse == True and FisherBlock found but of the wrong type.\n \"\"\"\n\n block_type, approx = self._get_block_type(\n params, approx, self.default_fully_connected_approximation,\n self._fully_connected_approx_to_block_types)\n\n has_bias = isinstance(params, (tuple, list))\n block = self._register_block(\n params, block_type(self, has_bias=has_bias), reuse=reuse)\n\n if not dense_inputs:\n inputs.one_hot_depth = int(params.shape[0])\n block.register_additional_tower(inputs, outputs)\n\n self._add_uses(params, 1)\n\n def register_conv1d(self,\n params,\n strides,\n padding,\n inputs,\n outputs,\n dilations=None,\n approx=None,\n reuse=VARIABLE_SCOPE,\n sub_sample_inputs=None,\n sub_sample_patches=None):\n \"\"\"Registers a call to tf.nn.conv1d().\n\n Args:\n params: Variablle or 2-tuple of variables corresponding to weight and\n bias parameters this layer. Weight matrix should have shape\n [kernel_width, in_channels, out_channels]. Bias should have shape\n [out_channels].\n strides: List of 3 ints. Strides for convolution kernel.\n padding: string. see tf.nn.conv2d for valid values.\n inputs: Tensor of shape [batch_size, width, in_channels]. Inputs\n to layer.\n outputs: Tensor of shape [batch_size, width, out_channels].\n Output produced by layer.\n dilations: List of 3 ints. Dilations along each dimension.\n approx: str or None. If not None, must be \"kron\". The Fisher approximation\n to use. If None, the default value is used. (Default: None)\n reuse: bool or str. If True, this adds 'inputs' and 'outputs' as an\n additional mini-batch/tower of data to use when estimating the Fisher\n block for this layer (which must have already been registered). If\n \"VARIABLE_SCOPE\", use tf.get_variable_scope().reuse.\n (Default: \"VARIABLE_SCOPE\")\n sub_sample_inputs: `bool`. If True, then subsample the inputs from which\n the image patches are extracted. (Default: None)\n sub_sample_patches: `bool`, If `True` then subsample the extracted\n patches. (Default: None)\n\n Raises:\n KeyError: If reuse == True but no FisherBlock found for 'params'.\n ValueError: If reuse == True and FisherBlock found but of the wrong type.\n \"\"\"\n assert approx is None or approx == APPROX_KRONECKER_NAME\n\n block = self._register_block(\n params,\n fb.ConvKFCBasicFB(\n layer_collection=self,\n params=params,\n padding=padding,\n strides=strides,\n data_format=\"NWC\",\n dilation_rate=dilations,\n extract_patches_fn=\"extract_convolution_patches\",\n sub_sample_inputs=sub_sample_inputs,\n sub_sample_patches=sub_sample_patches,\n use_sua_approx_for_input_factor=False),\n reuse=reuse)\n block.register_additional_tower(inputs, outputs)\n\n self._add_uses(params, 1)\n\n def register_conv2d(self,\n params,\n strides,\n padding,\n inputs,\n outputs,\n data_format=None,\n dilations=None,\n approx=None,\n reuse=VARIABLE_SCOPE,\n sub_sample_inputs=None,\n sub_sample_patches=None,\n patch_mask=None):\n \"\"\"Registers a call to tf.nn.conv2d().\n\n Args:\n params: Variable or 2-tuple of variables corresponding to weight and\n bias parameters of this layer. Weight matrix should have shape\n [kernel_height, kernel_width, in_channels, out_channels]. Bias should\n have shape [out_channels].\n strides: List of 4 ints. Strides for convolution kernel.\n padding: string. see tf.nn.conv2d for valid values.\n inputs: Tensor of shape [batch_size, height, width, in_channels]. Inputs\n to layer.\n outputs: Tensor of shape [batch_size, height, width, out_channels].\n Output produced by layer.\n data_format: str or None. Format of data. If None, this should default\n to 'NWHC'. (Default: None)\n dilations: List of 4 ints. Dilations along each dimension.\n approx: str or None. If not None must be one of \"kron\" or \"diagonal\".\n The Fisher approximation to use. If None the default value is used.\n (Default: None)\n reuse: bool or str. If True, this adds 'inputs' and 'outputs' as an\n additional mini-batch/tower of data to use when estimating the Fisher\n block for this layer (which must have already been registered). If\n \"VARIABLE_SCOPE\", use tf.get_variable_scope().reuse.\n (Default: \"VARIABLE_SCOPE\")\n sub_sample_inputs: `bool`. If True, then subsample the inputs from which\n the image patches are extracted. (Default: None)\n sub_sample_patches: `bool`, If `True` then subsample the extracted\n patches. (Default: None)\n patch_mask: Tensor of shape [kernel_height, kernel_width, in_channels]\n or None. If not None this is multiplied against the extracted patches\n Tensor (broadcasting along the batch dimension) before statistics are\n computed. This can (and probably should) be used if the filter bank\n matrix is masked in a way that is homogenous across the output channels.\n (Other masking patterns have no direct support.) Currently only works\n with the approx=\"kron\" or \"diagonal\". (Default: None)\n Raises:\n ValueError: For improper value to 'approx'.\n KeyError: If reuse == True but no FisherBlock found for 'params'.\n ValueError: If reuse == True and FisherBlock found but of the wrong type.\n \"\"\"\n assert data_format in [None, \"NHWC\"] # We don't support NCHW right now\n\n block_type, approx = self._get_block_type(\n params, approx, self.default_conv2d_approximation,\n self._conv2d_approx_to_block_types)\n\n # It feels bad to pass in configuration that has to do with the internal\n # implementation. And then we can't use the same constructor for both\n # anymore and are thus forced to use this ugly if-statement.\n # TODO(b/74793309): Clean this up?\n if approx == APPROX_KRONECKER_NAME:\n block = self._register_block(\n params,\n block_type(\n layer_collection=self,\n params=params,\n padding=padding,\n strides=strides,\n data_format=data_format,\n dilation_rate=dilations,\n extract_patches_fn=\"extract_image_patches\",\n sub_sample_inputs=sub_sample_inputs,\n sub_sample_patches=sub_sample_patches,\n use_sua_approx_for_input_factor=False,\n patch_mask=patch_mask),\n reuse=reuse)\n elif approx == APPROX_DIAGONAL_NAME:\n assert strides[0] == strides[-1] == 1\n block = self._register_block(\n params,\n block_type(\n layer_collection=self,\n params=params,\n padding=padding,\n strides=strides,\n dilations=dilations,\n data_format=data_format,\n patch_mask=patch_mask),\n reuse=reuse)\n elif approx == APPROX_KRONECKER_SUA_NAME:\n block = self._register_block(\n params,\n block_type(\n layer_collection=self,\n params=params,\n padding=padding,\n use_sua_approx_for_input_factor=True),\n reuse=reuse)\n\n else:\n raise NotImplementedError(approx)\n\n block.register_additional_tower(inputs, outputs)\n\n self._add_uses(params, 1)\n\n def register_convolution(self,\n params,\n inputs,\n outputs,\n padding,\n strides=None,\n dilation_rate=None,\n data_format=None,\n approx=None,\n reuse=VARIABLE_SCOPE):\n \"\"\"Register a call to tf.nn.convolution().\n\n Unless you know what you are doing you should be using register_conv2d\n instead.\n\n Args:\n params: Variable or 2-tuple of variables corresponding to weight and\n bias parameters of this layer. Weight matrix should have shape\n [..filter_spatial_size.., in_channels, out_channels]. Bias should have\n shape [out_channels].\n inputs: Tensor of shape [batch_size, ..input_spatial_size.., in_channels].\n Inputs to layer.\n outputs: Tensor of shape [batch_size, ..output_spatial_size..,\n out_channels]. Output produced by layer.\n padding: string. see tf.nn.conv2d for valid values.\n strides: List of ints of length len(..input_spatial_size..). Strides for\n convolution kernel in spatial dimensions.\n dilation_rate: List of ints of length len(..input_spatial_size..).\n Dilations along spatial dimension.\n data_format: str or None. Format of data.\n approx: str or None. If not None, must be \"kron\". The Fisher approximation\n to use. If None, the default value is used. (Default: None)\n reuse: bool or str. If True, this adds 'inputs' and 'outputs' as an\n additional mini-batch/tower of data to use when estimating the Fisher\n block for this layer (which must have already been registered). If\n \"VARIABLE_SCOPE\", use tf.get_variable_scope().reuse.\n (Default: \"VARIABLE_SCOPE\")\n\n Raises:\n ValueError: For improper value to 'approx'.\n KeyError: If reuse == True but no FisherBlock found for 'params'.\n ValueError: If reuse == True and FisherBlock found but of the wrong type.\n \"\"\"\n # TODO(b/74793309): Have this use _get_block_type like the other\n # registration functions?\n assert approx is None or approx == APPROX_KRONECKER_NAME\n\n block = self._register_block(\n params,\n fb.ConvKFCBasicFB(\n layer_collection=self,\n params=params,\n padding=padding,\n strides=strides,\n dilation_rate=dilation_rate,\n data_format=data_format),\n reuse=reuse)\n block.register_additional_tower(inputs, outputs)\n\n self._add_uses(params, 1)\n\n def register_depthwise_conv2d(self,\n params,\n inputs,\n outputs,\n strides,\n padding,\n rate=None,\n data_format=None,\n approx=None,\n reuse=VARIABLE_SCOPE):\n \"\"\"Register a call to tf.nn.depthwise_conv2d().\n\n Note that this is an experimental feature that hasn't been experimentally\n validated or published on.\n\n Args:\n params: 4-D variable of shape [filter_height, filter_width, in_channels,\n channel_multiplier]. Convolutional filter.\n inputs: Tensor of shape [batch_size, input_height, input_width,\n in_channels]. Inputs to layer.\n outputs: Tensor of shape [batch_size, output_height, output_width,\n in_channels * channel_multiplier]. Output produced by depthwise conv2d.\n strides: List of ints of length 4. Strides along all dimensions.\n padding: string. see tf.nn.conv2d for valid values.\n rate: None or List of ints of length 2. Dilation rates in spatial\n dimensions.\n data_format: str or None. Format of data.\n approx: str or None. If not None must \"diagonal\". The Fisher\n approximation to use. If None the default value is used. (Default: None)\n reuse: bool or str. If True, this adds 'inputs' and 'outputs' as an\n additional mini-batch/tower of data to use when estimating the Fisher\n block for this layer (which must have already been registered). If\n \"VARIABLE_SCOPE\", use tf.get_variable_scope().reuse.\n (Default: \"VARIABLE_SCOPE\")\n\n Raises:\n ValueError: For improper value to 'approx'.\n KeyError: If reuse == True but no FisherBlock found for 'params'.\n ValueError: If reuse == True and FisherBlock found but of the wrong type.\n \"\"\"\n # TODO(b/74793309): Have this use _get_block_type like the other\n # registration functions?\n assert approx is None or approx == APPROX_DIAGONAL_NAME\n assert data_format in [None, \"NHWC\"]\n\n block = self._register_block(\n params,\n fb.DepthwiseConvDiagonalFB(\n layer_collection=self,\n params=params,\n strides=strides,\n padding=padding,\n rate=rate,\n data_format=data_format),\n reuse=reuse)\n block.register_additional_tower(inputs, outputs)\n\n self._add_uses(params, 1)\n\n def register_separable_conv2d(self,\n depthwise_params,\n pointwise_params,\n inputs,\n depthwise_outputs,\n pointwise_outputs,\n strides,\n padding,\n rate=None,\n data_format=None,\n approx=None,\n reuse=VARIABLE_SCOPE):\n \"\"\"Register a call to tf.nn.separable_conv2d().\n\n Note: This requires access to intermediate outputs between depthwise and\n pointwise convolutions.\n\n Note that this is an experimental feature that hasn't been experimentally\n validated or published on.\n\n Args:\n depthwise_params: 4-D variable of shape [filter_height, filter_width,\n in_channels, channel_multiplier]. Filter for depthwise conv2d.\n pointwise_params: 4-D variable of shape [1, 1, in_channels *\n channel_multiplier, out_channels]. Filter for pointwise conv2d.\n inputs: Tensor of shape [batch_size, input_height, input_width,\n in_channels]. Inputs to layer.\n depthwise_outputs: Tensor of shape [batch_size, output_height,\n output_width, in_channels * channel_multiplier]. Output produced by\n depthwise conv2d.\n pointwise_outputs: Tensor of shape [batch_size, output_height,\n output_width, out_channels]. Output produced by pointwise conv2d.\n strides: List of ints of length 4. Strides for depthwise conv2d kernel in\n all dimensions.\n padding: string. see tf.nn.conv2d for valid values.\n rate: None or List of ints of length 2. Dilation rate of depthwise conv2d\n kernel in spatial dimensions.\n data_format: str or None. Format of data.\n approx: str or None. If not None must be one of \"kron\" or \"diagonal\".\n The Fisher approximation to use. If None the default value is used.\n (Default: None)\n reuse: bool or str. If True, this adds 'inputs' and 'outputs' as an\n additional mini-batch/tower of data to use when estimating the Fisher\n block for this layer (which must have already been registered). If\n \"VARIABLE_SCOPE\", use tf.get_variable_scope().reuse.\n (Default: \"VARIABLE_SCOPE\")\n\n Raises:\n ValueError: For improper value to 'approx'.\n KeyError: If reuse == True but no FisherBlock found for 'params'.\n ValueError: If reuse == True and FisherBlock found but of the wrong type.\n \"\"\"\n self.register_depthwise_conv2d(\n params=depthwise_params,\n inputs=inputs,\n outputs=depthwise_outputs,\n strides=strides,\n padding=padding,\n rate=rate,\n data_format=data_format,\n approx=APPROX_DIAGONAL_NAME,\n reuse=reuse)\n\n self.register_conv2d(\n params=pointwise_params,\n inputs=depthwise_outputs,\n outputs=pointwise_outputs,\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n data_format=data_format,\n approx=approx,\n reuse=reuse)\n\n def register_generic(self,\n params,\n batch_size,\n approx=None,\n reuse=VARIABLE_SCOPE):\n \"\"\"Registers parameters without assuming any structure.\n\n Note that this is an approximation of last resort and should be avoided if\n anything else will work.\n\n Args:\n params: Variable or tuple of variables corresponding to the parameters.\n If using \"diagonal\" approximation this must be a single variable.\n batch_size: 0-D Tensor. Size of the minibatch (for this tower).\n approx: str or None. It not None, must be one of \"full\" or \"diagonal\".\n The Fisher approximation to use. If None the default value is used.\n (Default: None)\n reuse: bool or str. If True, this adds 'batch_size' to the total\n mini-batch size use when estimating the Fisher block for this layer\n (which must have already been registered). If \"VARIABLE_SCOPE\", use\n tf.get_variable_scope().reuse. (Default: \"VARIABLE_SCOPE\")\n\n Raises:\n ValueError: For improper value to 'approx'.\n KeyError: If reuse == True but no FisherBlock found for 'params'.\n ValueError: If reuse == True and FisherBlock found but of the wrong type.\n ValueError: If approx == \"diagonal\" and params is a tuple.\n \"\"\"\n block_type, approx = self._get_block_type(\n params, approx, self.default_generic_approximation,\n self._generic_approx_to_block_types)\n\n if approx == APPROX_DIAGONAL_NAME and isinstance(params, (tuple, list)):\n raise ValueError(\"Params must be a Variable if using the diagonal \"\n \"approximation.\")\n\n block = self._register_block(params, block_type(self, params), reuse=reuse)\n block.register_additional_tower(batch_size)\n\n self._add_uses(params, float(\"inf\"))\n\n def register_fully_connected_multi(self, params, inputs, outputs,\n num_uses=None, approx=None,\n dense_inputs=True, reuse=VARIABLE_SCOPE):\n \"\"\"Register fully connected layers with shared parameters.\n\n This can handle general fully-connected layers with shared parameters, but\n has specialized approximations to deal with the case where there is a\n meaningful linear order to the share instances (such as in an RNN).\n\n Note that padding is *not* supported. The arguments to this method cannot\n be zero-padded or anything of that sort.\n\n Args:\n params: Variable or 2-tuple of variables corresponding to weight and\n bias of this layer. Weight matrix should have shape [input_size,\n output_size]. Bias should have shape [output_size].\n inputs: A list of Tensors or a single Tensor. Inputs to this layer. If a\n list of Tensors, the list indexes each use in the model (which might\n correspond to a \"time-step\" in an RNN). Each Tensor in the list has\n leading dimension batch_size. If a single Tensor, the leading dimension\n would be num_uses * batch_size, which is a reshaped version of the list\n of Tensors. Similar to register_fully_connected(), two formats of\n tensors are accepted: dense inputs and sparse inputs. In most cases\n the Tensors are dense inputs, with shape [batch_size, input_size] (if a\n list) or [num_uses * batch_size , input_size] (if a single Tensor).\n In some cases the Tensors are sparse inputs, with shape [batch_size] (if\n a list) or [num_uses * batch_size] (if a single Tensor). A typical\n example of sparse inputs is the vocab indices into an embedding matrix.\n Sparse inputs will be converted to the dense format within KFAC. For\n sparse inputs, dense_inputs should be set to False.\n outputs: A list of Tensors, the same length as 'inputs', each of shape\n [batch_size, output_size]. Outputs produced by layer. The list indexes\n each use in the model (which might correspond to a \"time-step\" in an\n RNN). Needs to correspond with the order used in 'inputs'. OR, can be\n a single Tensor of shape [num_uses * batch_size, output_size], which is\n a reshaped version of a Tensor of shape [num_uses, batch_size,\n output_size].\n num_uses: int or None. The number uses/time-steps in the model where the\n layer appears. Only needed if both inputs and outputs are given in the\n single Tensor format. (Default: None)\n approx: str or None. If not None, must be one of \"kron_indep\",\n \"kron_indep_in_diag\" (diagonal approximation for the input kronecker\n factor), \"kron_indep_out_diag\" (diagonal approximation for the output\n kronecker factor), \"kron_indep_both_diag\", \"kron_series_1\" or\n \"kron_series_2\". The Fisher approximation to use. If None the default\n value is used (which starts out as \"kron_indep\"). (Default: None)\n dense_inputs: bool. True if inputs are dense inputs. (Default: True)\n reuse: bool or str. If True, this adds inputs and outputs as an\n additional mini-batch/tower of data to use when estimating the Fisher\n block for this layer (which must have already been registered). If\n \"VARIABLE_SCOPE\", use tf.get_variable_scope().reuse. (Note that the\n word 'use' here has a completely different meaning to \"use in the model\"\n as it pertains to the 'inputs', 'outputs', and 'num_uses' arguments.)\n (Default: \"VARIABLE_SCOPE\")\n\n Raises:\n ValueError: For improper value to 'approx'.\n \"\"\"\n block_type, approx = self._get_block_type(\n params, approx, self.default_fully_connected_multi_approximation,\n self._fully_connected_multi_approx_to_block_types)\n\n # TODO(b/70283649): something along the lines of find_canonical_output\n # should be added back in here (and for the other block types, arguably).\n has_bias = isinstance(params, (tuple, list))\n block = self._register_block(\n params,\n block_type(self, has_bias=has_bias, num_uses=num_uses),\n reuse=reuse)\n\n if isinstance(inputs, (tuple, list)):\n inputs = tuple(inputs)\n if isinstance(outputs, (tuple, list)):\n outputs = tuple(outputs)\n\n if not dense_inputs:\n if isinstance(inputs, (tuple, list)):\n for input in inputs:\n input.one_hot_depth = int(params.shape[0])\n else:\n inputs.one_hot_depth = int(params.shape[0])\n\n block.register_additional_tower(inputs, outputs)\n if isinstance(inputs, (tuple, list)):\n assert len(inputs) == len(outputs)\n self._add_uses(params, len(inputs))\n else:\n self._add_uses(params, 1)\n\n def register_conv2d_multi(self,\n params,\n strides,\n padding,\n inputs,\n outputs,\n num_uses=None,\n data_format=None,\n dilations=None,\n approx=None,\n reuse=VARIABLE_SCOPE):\n \"\"\"Registers convolutional layers with shared parameters.\n\n Note that padding is *not* supported. The arguments to this method cannot\n be zero-padded or anything of that sort.\n\n Args:\n params: Variable or 2-tuple of variables corresponding to weight and\n bias of this layer. Weight matrix should have shape [kernel_height,\n kernel_width, in_channels, out_channels]. Bias should have shape\n [out_channels].\n strides: 1-D Tensor of length 4. Strides for convolution kernel.\n padding: string. see tf.nn.conv2d for valid values.\n inputs: A list of Tensors, each of shape [batch_size, height, width,\n in_channels]. Inputs to layer. The list indexes each use in the model\n (which might correspond to a \"time-step\" in an RNN). OR, can be single\n Tensor, of shape [num_uses * batch_size, height, width, in_channels],\n which is a reshaped version of a Tensor of shape [num_uses, batch_size,\n height, width, in_channels].\n outputs: A list of Tensors, each of shape [batch_size, height, width,\n out_channels]. Output produced by layer. The list indexes each use\n in the model (which might correspond to a \"time-step\" in an RNN).\n Needs to correspond with the order used in 'inputs'. OR, can be a\n single Tensor, of shape [num_uses * batch_size, height, width,\n out_channels], which is a reshaped version of a Tensor of shape\n [num_uses, batch_size, height, width, out_channels].\n num_uses: int or None. The number uses/time-steps in the model where the\n layer appears. Only needed if both inputs and outputs are given in the\n single Tensor format. (Default: None)\n data_format: str or None. Format of data.\n dilations: List of 4 ints. Dilations along each dimension.\n approx: str or None. If not None must be \"kron_indep\". The Fisher\n approximation to use. If None the default value is used (which starts\n out as \"kron_indep\"). (Default: None)\n reuse: bool or str. If True, this adds inputs and outputs as an\n additional mini-batch/tower of data to use when estimating the Fisher\n block for this layer (which must have already been registered). If\n \"VARIABLE_SCOPE\", use tf.get_variable_scope().reuse. (Note that the\n word 'use' here has a completely different meaning to \"use in the model\"\n as it pertains to the 'inputs', 'outputs', and 'num_uses' arguments.)\n (Default: \"VARIABLE_SCOPE\")\n\n Raises:\n ValueError: For improper value to 'approx'.\n KeyError: If reuse == True but no FisherBlock found for 'params'.\n ValueError: If reuse == True and FisherBlock found but of the wrong type.\n \"\"\"\n assert data_format in [None, \"NHWC\"] # We don't support NCHW right now\n\n block_type, approx = self._get_block_type(\n params, approx, self.default_conv2d_multi_approximation,\n self._conv2d_multi_approx_to_block_types)\n\n block = self._register_block(\n params,\n block_type(\n layer_collection=self,\n params=params,\n padding=padding,\n strides=strides,\n data_format=data_format,\n dilation_rate=dilations,\n extract_patches_fn=\"extract_image_patches\",\n num_uses=num_uses),\n reuse=reuse)\n\n if isinstance(inputs, (tuple, list)):\n inputs = tuple(inputs)\n if isinstance(outputs, (tuple, list)):\n outputs = tuple(outputs)\n\n block.register_additional_tower(inputs, outputs)\n if isinstance(inputs, (tuple, list)):\n assert len(inputs) == len(outputs)\n self._add_uses(params, len(inputs))\n else:\n self._add_uses(params, 1)\n\n def register_scale_and_shift(self,\n params,\n inputs,\n outputs,\n approx=None,\n reuse=VARIABLE_SCOPE):\n \"\"\"Registers a scale and shift operation.\n\n A scale and shift operation is a parameterized operation of the form\n\n outputs = scale * inputs + shift ,\n\n where scale and shift are variables that broadcast to the shape of inputs.\n\n outputs and inputs must have batch dimension. scale and shift can have\n a corresponding dimension (although they don't need to), but it must\n be 1.\n\n These kinds of operations appear frequently in various \"normalization\"\n layers like Layer Normalization. Batch Normalization layers should still\n be registered as \"generic\".\n\n Note that this is an experimental feature that hasn't been experimentally\n validated or published on.\n\n Args:\n params: Variable or 2-tuple of Variables corresponding to the scale\n and possibly shift parameters (scale must be first). Note that if\n these have a dimension corresponding to the batch dimension of 'inputs'\n and 'outputs', that dimension must be 1.\n inputs: Tensor of shape [batch_size, ...]. Input tensor that is multiplied\n by the scale the scale tensor.\n outputs: Tensor of shape [batch_size, ...]. Final output produced by the\n scale and shift. Must have the same shape as 'inputs'.\n approx: str or None. If not None must be one of \"full\" or \"diagonal\".\n The Fisher approximation to use. If None the default value is used.\n (Default: None)\n reuse: bool or str. If True, this adds 'inputs' and 'outputs' as an\n additional mini-batch/tower of data to use when estimating the Fisher\n block for this layer (which must have already been registered). If\n \"VARIABLE_SCOPE\", use tf.get_variable_scope().reuse.\n (Default: \"VARIABLE_SCOPE\")\n\n Raises:\n ValueError: For improper value to 'approx'.\n KeyError: If reuse == True but no FisherBlock found for 'params'.\n ValueError: If reuse == True and FisherBlock found but of the wrong type.\n \"\"\"\n # TODO(jamesmartens): Consider replacing some of the logic below with calls\n # to tf.broadcast_static_shape.\n if isinstance(params, (tuple, list)):\n scale = params[0]\n shift = params[1]\n\n has_shift = True\n\n start_dim = len(outputs.shape) - len(shift.shape)\n if start_dim < 0:\n raise ValueError(\"Rank of shift cannot exceed that of outputs.\")\n if start_dim == 0 and shift.shape[0] != 1:\n raise ValueError(\"If shift has a batch dimension its value must be 1.\")\n broadcast_dims_shift = list(range(1, start_dim))\n for i in range(max(start_dim, 1), len(outputs.shape)):\n if shift.shape[i - start_dim] < outputs.shape[i]:\n if shift.shape[i - start_dim] == 1:\n broadcast_dims_shift.append(i)\n else:\n raise ValueError(\"It appears that shift param and output have \"\n \"incompatible shapes. This is probably due to \"\n \"misspecified arguments.\")\n elif shift.shape[i - start_dim] > outputs.shape[i]:\n raise ValueError(\"It appears that shift param and output have \"\n \"incompatible shapes. This is probably due to \"\n \"misspecified arguments.\")\n broadcast_dims_shift = tuple(broadcast_dims_shift)\n else:\n has_shift = False\n scale = params\n broadcast_dims_shift = None\n\n start_dim = len(inputs.shape) - len(scale.shape)\n if start_dim < 0:\n raise ValueError(\"Rank of scale cannot exceed that of inputs.\")\n if start_dim == 0 and scale.shape[0] != 1:\n raise ValueError(\"If scale has a batch dimension its value must be 1.\")\n broadcast_dims_scale = list(range(1, start_dim))\n for i in range(max(start_dim, 1), len(inputs.shape)):\n if scale.shape[i - start_dim] < inputs.shape[i]:\n if scale.shape[i - start_dim] == 1:\n broadcast_dims_scale.append(i)\n else:\n raise ValueError(\"It appears that scale param and input have \"\n \"incompatible shapes. This is probably due to \"\n \"misspecified arguments.\")\n broadcast_dims_scale = tuple(broadcast_dims_scale)\n\n block_type, approx = self._get_block_type(\n params, approx, self.default_scale_and_shift_approximation,\n self._scale_and_shift_approx_to_block_types)\n\n block = self._register_block(params, block_type(\n self,\n broadcast_dims_scale,\n broadcast_dims_shift=broadcast_dims_shift,\n has_shift=has_shift),\n reuse=reuse)\n block.register_additional_tower(inputs, outputs)\n\n self._add_uses(params, 1)\n\n def register_categorical_predictive_distribution(self,\n logits,\n seed=None,\n targets=None,\n name=None,\n coeff=1.0,\n reuse=VARIABLE_SCOPE):\n \"\"\"Registers a categorical predictive distribution.\n\n Corresponds to losses computed using\n tf.nn.sparse_softmax_cross_entropy_with_logits.\n\n Note that this is distinct from\n register_multi_bernoulli_predictive_distribution and should not be confused\n with it.\n\n Args:\n logits: The logits of the distribution (i.e. its parameters). The first\n dimension must be the batch size.\n seed: The seed for the RNG (for debugging) (Default: None)\n targets: (OPTIONAL) The targets for the loss function. Only required if\n one wants to use the \"empirical Fisher\" instead of the true Fisher\n (which is controlled by the 'estimation_mode' to the optimizer).\n (Default: None)\n name: (OPTIONAL) str or None. Unique name for this loss function. If None,\n a new name is generated. (Default: None)\n coeff: (OPTIONAL) a float or TF scalar. A coefficient to multiply the\n log prob loss associated with this distribution. The Fisher will be\n multiplied by the corresponding factor. This is NOT equivalent to\n changing the temperature of the distribution since we don't renormalize\n the log prob in the objective function. (Default: 1.0)\n reuse: (OPTIONAL) bool or str. If True, this adds 'logits' as an\n additional mini-batch/tower of inputs to the loss-function/predictive\n distribution (which must have already been registered). If\n \"VARIABLE_SCOPE\", use tf.get_variable_scope().reuse.\n (Default: \"VARIABLE_SCOPE\")\n \"\"\"\n loss = lf.CategoricalLogitsNegativeLogProbLoss(logits, targets=targets,\n seed=seed)\n self._register_loss_function(loss, logits,\n \"categorical_predictive_distribution\",\n name=name, coeff=coeff, reuse=reuse)\n\n def register_softmax_cross_entropy_loss(self,\n logits,\n seed=None,\n targets=None,\n name=None,\n coeff=1.0,\n reuse=VARIABLE_SCOPE):\n \"\"\"Registers a softmax cross-entropy loss function.\n\n Corresponds to losses computed using\n tf.nn.sparse_softmax_cross_entropy_with_logits.\n\n Note that this is distinct from register_sigmoid_cross_entropy_loss and\n should not be confused with it. It is similar to\n register_categorical_predictive_distribution but without the explicit\n probabilistic interpretation. It behaves identically for now.\n\n Args:\n logits: The logits of the distribution (i.e. its parameters). The first\n dimension must be the batch size.\n seed: The seed for the RNG (for debugging) (Default: None)\n targets: (OPTIONAL) The targets for the loss function. Only required if\n one wants to use the \"empirical Fisher\" instead of the true Fisher\n (which is controlled by the 'estimation_mode' to the optimizer).\n (Default: None)\n name: (OPTIONAL) str or None. Unique name for this loss function. If None,\n a new name is generated. (Default: None)\n coeff: (OPTIONAL) a float or TF scalar. A coefficient to multiply the\n loss function by. (Default: 1.0)\n reuse: (OPTIONAL) bool or str. If True, this adds 'logits' as an\n additional mini-batch/tower of inputs to the loss-function/predictive\n distribution (which must have already been registered). If\n \"VARIABLE_SCOPE\", use tf.get_variable_scope().reuse.\n (Default: \"VARIABLE_SCOPE\")\n \"\"\"\n loss = lf.CategoricalLogitsNegativeLogProbLoss(logits, targets=targets,\n seed=seed)\n self._register_loss_function(loss, logits,\n \"sparse_softmax_cross_entropy_loss\",\n name=name, coeff=coeff, reuse=reuse)\n\n def register_normal_predictive_distribution(self,\n mean,\n var=0.5,\n seed=None,\n targets=None,\n name=None,\n coeff=1.0,\n reuse=VARIABLE_SCOPE):\n \"\"\"Registers a normal predictive distribution.\n\n This corresponds to a squared error loss of the form\n coeff/(2*var) * ||target - mean||^2\n\n Args:\n mean: A tensor defining the mean vector of the distribution. The first\n dimension must be the batch size.\n var: float. The variance of the distribution. Note that the default value\n of 0.5 corresponds to a standard squared error loss coeff*||target -\n prediction||^2. If you want your squared error loss to be of the form\n 0.5*coeff*||target - prediction||^2 you should use var=1.0.\n (Default: 0.5)\n seed: The seed for the RNG (for debugging) (Default: None)\n targets: (OPTIONAL) The targets for the loss function. Only required if\n one wants to use the \"empirical Fisher\" instead of the true Fisher\n (which is controlled by the 'estimation_mode' to the optimizer).\n (Default: None)\n name: (OPTIONAL) str or None. Unique name for this loss function. If None,\n a new name is generated. (Default: None)\n coeff: (OPTIONAL) a float or TF scalar. A coefficient to multiply the\n log prob loss associated with this distribution. The Fisher will be\n multiplied by the corresponding factor. In general this is NOT\n equivalent to changing the temperature of the distribution, but in the\n case of normal distributions it may be. (Default: 1.0)\n reuse: (OPTIONAL) bool or str. If True, this adds 'mean' and 'var' as an\n additional mini-batch/tower of inputs to the loss-function/predictive\n distribution (which must have already been registered). If\n \"VARIABLE_SCOPE\", use tf.get_variable_scope().reuse.\n (Default: \"VARIABLE_SCOPE\")\n \"\"\"\n loss = lf.NormalMeanNegativeLogProbLoss(mean, var, targets=targets,\n seed=seed)\n self._register_loss_function(loss, mean,\n \"normal_predictive_distribution\",\n name=name, coeff=coeff, reuse=reuse)\n\n def register_squared_error_loss(self,\n prediction,\n seed=None,\n targets=None,\n name=None,\n coeff=1.0,\n reuse=VARIABLE_SCOPE):\n \"\"\"Registers a squared error loss function.\n\n This assumes the squared error loss of the form ||target - prediction||^2,\n averaged across the mini-batch. If your loss uses a coefficient of 0.5\n (tf.nn.l2_loss does this, for example) you need to set the \"coeff\" argument\n to reflect this.\n\n Args:\n prediction: The prediction made by the network (i.e. its output). The\n first dimension must be the batch size.\n seed: The seed for the RNG (for debugging) (Default: None)\n targets: (OPTIONAL) The targets for the loss function. Only required if\n one wants to use the \"empirical Fisher\" instead of the true Fisher\n (which is controlled by the 'estimation_mode' to the optimizer).\n (Default: None)\n name: (OPTIONAL) str or None. Unique name for this loss function. If None,\n a new name is generated. (Default: None)\n coeff: (OPTIONAL) a float or TF scalar. A coefficient to multiply the\n loss function by. (Default: 1.0)\n reuse: (OPTIONAL) bool or str. If True, this adds 'prediction' as an\n additional mini-batch/tower of inputs to the loss-function/predictive\n distribution (which must have already been registered). If\n \"VARIABLE_SCOPE\", use tf.get_variable_scope().reuse.\n (Default: \"VARIABLE_SCOPE\")\n \"\"\"\n loss = lf.NormalMeanNegativeLogProbLoss(prediction, var=0.5,\n targets=targets,\n seed=seed)\n self._register_loss_function(loss, prediction,\n \"squared_error_loss\",\n name=name, coeff=coeff, reuse=reuse)\n\n def register_multi_bernoulli_predictive_distribution(self,\n logits,\n seed=None,\n targets=None,\n name=None,\n coeff=1.0,\n reuse=VARIABLE_SCOPE):\n \"\"\"Registers a multi-Bernoulli predictive distribution.\n\n Corresponds to losses computed using\n tf.nn.sigmoid_cross_entropy_with_logits.\n\n Note that this is distinct from\n register_categorical_predictive_distribution and should not be confused\n with it.\n\n\n Args:\n logits: The logits of the distribution (i.e. its parameters). The first\n dimension must be the batch size.\n seed: The seed for the RNG (for debugging) (Default: None)\n targets: (OPTIONAL) The targets for the loss function. Only required if\n one wants to use the \"empirical Fisher\" instead of the true Fisher\n (which is controlled by the 'estimation_mode' to the optimizer).\n (Default: None)\n name: (OPTIONAL) str or None. Unique name for this loss function. If None,\n a new name is generated. (Default: None)\n coeff: (OPTIONAL) a float or TF scalar. A coefficient to multiply the\n log prob loss associated with this distribution. The Fisher will be\n multiplied by the corresponding factor. This is NOT equivalent to\n changing the temperature of the distribution since we don't renormalize\n the log prob in the objective function. (Default: 1.0)\n reuse: (OPTIONAL) bool or str. If True, this adds 'logits' as an\n additional mini-batch/tower of inputs to the loss-function/predictive\n distribution (which must have already been registered). If\n \"VARIABLE_SCOPE\", use tf.get_variable_scope().reuse.\n (Default: \"VARIABLE_SCOPE\")\n \"\"\"\n loss = lf.MultiBernoulliNegativeLogProbLoss(logits, targets=targets,\n seed=seed)\n self._register_loss_function(loss, logits,\n \"multi_bernoulli_predictive_distribution\",\n name=name, coeff=coeff, reuse=reuse)\n\n def register_sigmoid_cross_entropy_loss(self,\n logits,\n seed=None,\n targets=None,\n name=None,\n coeff=1.0,\n reuse=VARIABLE_SCOPE):\n \"\"\"Registers a sigmoid cross-entropy loss function.\n\n Corresponds to losses computed using\n tf.nn.sigmoid_cross_entropy_with_logits.\n\n Note that this is distinct from register_softmax_cross_entropy_loss and\n should not be confused with it. It is similar to\n register_multi_bernoulli_predictive_distribution but without the explicit\n probabilistic interpretation. It behaves identically for now.\n\n Args:\n logits: The logits tensor. The first dimension must be the batch size.\n seed: The seed for the RNG (for debugging) (Default: None)\n targets: (OPTIONAL) The targets for the loss function. Only required if\n one wants to use the \"empirical Fisher\" instead of the true Fisher\n (which is controlled by the 'estimation_mode' to the optimizer).\n (Default: None)\n name: (OPTIONAL) str or None. Unique name for this loss function. If None,\n a new name is generated. (Default: None)\n coeff: (OPTIONAL) a float or TF scalar. A coefficient to multiply the\n loss function by. (Default: 1.0)\n reuse: (OPTIONAL) bool or str. If True, this adds 'logits' as an\n additional mini-batch/tower of inputs to the loss-function/predictive\n distribution (which must have already been registered). If\n \"VARIABLE_SCOPE\", use tf.get_variable_scope().reuse.\n (Default: \"VARIABLE_SCOPE\")\n \"\"\"\n loss = lf.MultiBernoulliNegativeLogProbLoss(logits, targets=targets,\n seed=seed)\n self._register_loss_function(loss, logits,\n \"sigmoid_cross_entropy_loss\",\n name=name, coeff=coeff, reuse=reuse)\n\n def make_or_get_factor(self, cls, args):\n \"\"\"Insert 'cls(args)' into 'self.fisher_factors' if not already present.\n\n Wraps constructor in 'tf.variable_scope()' to ensure variables constructed\n in 'cls.__init__' are placed under this LayerCollection's scope.\n\n Args:\n cls: Class that implements FisherFactor.\n args: Tuple of arguments to pass into 'cls's constructor. Must be\n hashable.\n\n Returns:\n Instance of 'cls' found in self.fisher_factors.\n \"\"\"\n # TODO(b/123190346): Should probably change the args list to be keyworded\n # instead of positional. Note that this would require making changes in\n # each FisherBlock's call to make_or_get_factor.\n try:\n hash(args)\n except TypeError:\n raise TypeError(\n (\"Unable to use (cls, args) = ({}, {}) as a key in \"\n \"LayerCollection.fisher_factors. The pair cannot be hashed.\").format(\n cls, args))\n\n key = cls, args\n if key not in self.fisher_factors:\n with tf.variable_scope(self._var_scope):\n self.fisher_factors[key] = cls(*args)\n return self.fisher_factors[key]\n\n @contextmanager\n def as_default(self):\n \"\"\"Sets this LayerCollection as the default.\"\"\"\n set_default_layer_collection(self)\n yield\n set_default_layer_collection(None)\n"
] |
[
[
"tensorflow.compat.v1.cast",
"tensorflow.compat.v1.colocate_with",
"tensorflow.compat.v1.get_default_graph",
"tensorflow.compat.v1.variable_scope",
"tensorflow.compat.v1.get_variable_scope",
"tensorflow.compat.v1.trainable_variables",
"tensorflow.compat.v1.sqrt",
"tensorflow.python.util.nest.flatten"
]
] |
agrawalayan/R-net-1
|
[
"1748d108a8248466d99cdf3c3f284619d88bcc73"
] |
[
"src/generator_utils.py"
] |
[
"from __future__ import print_function\nimport tensorflow as tf\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import nn_ops\n\ndef add_first_word_prob_to_atten_dists(in_passage_words, phrase_starts, vocab_dist, attn_dist):\n '''\n in_passage_words: [batch_size, passage_length]\n phrase_starts: [batch_size, phrase_length]\n vocab_dist: [batch_size, vsize]\n attn_dist: [batch_size, phrase_length]\n return: [batch_size, phrase_length]\n '''\n def singel_instance(x):\n cur_passage_words = x[0] # [passage_length]\n cur_phrase_starts = x[1] # [phrase_length]\n cur_vocab_dist = x[2] # [vsize]\n cur_attn_dist = x[3] # [passage_length]\n # first: get the first word for each phrase\n first_words = tf.gather(cur_passage_words, cur_phrase_starts) # [phrase_length]\n # second: get the probs for each word\n first_word_probs = tf.gather(cur_vocab_dist, first_words) # [phrase_length]\n return cur_attn_dist + first_word_probs\n elems = (in_passage_words, phrase_starts, vocab_dist, attn_dist)\n return tf.map_fn(singel_instance, elems, dtype=tf.float32) # [batch_size, phrase_length]\n\n\nclass CovCopyAttenGen:\n def __init__(self, placeholders, options, vocab):\n self.options = options\n self.vocab = vocab\n self.cell = tf.contrib.rnn.LSTMCell(\n options.gen_hidden_size,\n initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=113),\n state_is_tuple=True)\n self.placeholders = placeholders\n\n with tf.variable_scope(\"embedding\"), tf.device('/cpu:0'):\n self.embedding = tf.get_variable('word_embedding', trainable=(options.fix_word_vec==False),\n initializer=tf.constant(self.vocab.word_vecs), dtype=tf.float32)\n\n if options.with_phrase_projection:\n self.max_phrase_size = placeholders.max_phrase_size\n if options.add_first_word_prob_for_phrase:\n self.in_passage_words = placeholders.in_passage_words\n self.phrase_starts = placeholders.phrase_starts\n else:\n self.max_phrase_size = None\n\n\n def attention(self, decoder_state, attention_vec_size, encoder_states, encoder_features, passage_mask, v, w_c=None,\n use_coverage=True, coverage=None):\n '''\n decoder_state: Tuple of [batch_size, gen_hidden_size]\n encoder_states: [batch_size, passage_len, encoder_dim]\n encoder_features: [batch_size,passage_len,attention_vec_size]\n passage_mask: [batch_size, passage_len]\n v: [1,1, attention_vec_size]\n w_c: [1,1, attention_vec_size]\n coverage: [batch_size, passage_len]\n '''\n with variable_scope.variable_scope(\"Attention\"):\n # Equation (11) in the paper\n state_features = linear(decoder_state, attention_vec_size, True) # [batch_size, attention_vec_size]\n state_features = tf.expand_dims(state_features, 1) # [batch_size, 1, attention_vec_size]\n all_features = encoder_features + state_features # [batch_size,passage_len,attention_vec_size]\n if use_coverage and coverage is not None:\n coverage_features = tf.expand_dims(coverage, axis=-1) * w_c # [batch_size, passage_len, attention_vec_size]\n all_features += coverage_features\n e = tf.reduce_sum(v * tf.tanh(all_features), axis=-1) # [batch_size, passage_len]\n attn_dist = nn_ops.softmax(e) # [batch_size, passage_len]\n attn_dist *= passage_mask\n\n if coverage is not None: # Update coverage vector\n coverage += attn_dist\n else: # first step of training\n coverage = attn_dist\n\n # Calculate the context vector from attn_dist and encoder_states\n # shape (batch_size, attn_size).\n context_vector = tf.reduce_sum(tf.expand_dims(attn_dist, axis=-1) * encoder_states, axis=1) # [batch_size, encoder_dim]\n return context_vector, attn_dist, coverage\n\n def embedding_lookup(self, inputs):\n '''\n inputs: list of [batch_size], int32\n '''\n if type(inputs) is list:\n return [tf.nn.embedding_lookup(self.embedding, x) for x in inputs]\n else:\n return tf.nn.embedding_lookup(self.embedding, inputs)\n\n def one_step_decoder(self, state_t_1, context_t_1, coverage_t_1, word_t, encoder_states, encoder_features,\n passage_word_idx, passage_mask, v, w_c, vocab):\n '''\n state_t_1: Tuple of [batch_size, gen_hidden_size]\n context_t_1: [batch_size, encoder_dim]\n coverage_t_1: [batch_size, passage_len]\n word_t: [batch_size, word_dim]\n encoder_states: [batch_size, passage_len, encoder_dim]\n encoder_features: [batch_size,attn_length,attention_vec_size]\n passage_mask: [batch_size, passage_len]\n v: [1,1, attention_vec_size]\n w_c: [1,1, attention_vec_size]\n '''\n\n options = self.options\n x = linear([word_t, context_t_1], options.attention_vec_size, True)\n\n # Run the decoder RNN cell. cell_output = decoder state\n cell_output, state_t = self.cell(x, state_t_1)\n\n context_t, attn_dist, coverage_t = self.attention(state_t, options.attention_vec_size, encoder_states,\n encoder_features, passage_mask, v, w_c=w_c,\n use_coverage=options.use_coverage, coverage=coverage_t_1)\n # Calculate p_gen, Equation (8)\n if options.pointer_gen:\n with tf.variable_scope('calculate_pgen'):\n p_gen = linear([context_t, state_t.c, state_t.h, x], 1, True) # [batch_size, 1]\n p_gen = tf.sigmoid(p_gen)\n\n # Concatenate the cell_output (= decoder state) and the context vector, and pass them through a linear layer\n # This is V[s_t, h*_t] + b in the paper\n with variable_scope.variable_scope(\"AttnOutputProjection\"):\n output_t = linear([cell_output] + [context_t], options.gen_hidden_size, True)\n\n with tf.variable_scope('output_projection'):\n w = tf.get_variable('w', [options.gen_hidden_size, vocab.vocab_size+1], dtype=tf.float32)\n b = tf.get_variable('b', [vocab.vocab_size +1], dtype=tf.float32)\n # vocab_scores is the vocabulary distribution before applying softmax.\n # Each entry on the list corresponds to one decoder step\n vocab_score_t = tf.nn.xw_plus_b(output_t, w, b) # apply the linear layer\n vocab_score_t = tf.nn.softmax(vocab_score_t)\n\n # For pointer-generator model, calc final distribution from copy distribution and vocabulary distribution\n if options.pointer_gen:\n vocab_score_t = self.merge_prob_dist_for_one_step(vocab_score_t, attn_dist, p_gen, passage_word_idx, passage_mask)\n vocab_score_t = _clip_and_normalize(vocab_score_t, 1e-6)\n\n\n return (state_t, context_t, coverage_t, attn_dist, p_gen, vocab_score_t)\n\n def train_mode(self, vocab, encoder_dim, encoder_states, encoder_features, passage_word_idx, passage_mask,\n init_state, decoder_inputs, answer_batch, loss_weights, mode_gen='ce_train'):\n '''\n encoder_dim: int-valued\n encoder_states: [batch_size, passage_len, encoder_dim].\n passage_word_idx: [batch_size, passage_len] int32\n passage_mask: [batch_size, passage_len] 0/1\n init_state: Tuple of [batch_size, gen_hidden_size]\n decoder_inputs: [batch_size, max_dec_steps].\n answer_batch: [batch_size, max_dec_steps]\n '''\n options = self.options\n\n input_shape = tf.shape(encoder_states)\n batch_size = input_shape[0]\n passage_len = input_shape[1]\n\n # map decoder inputs to word embeddings\n decoder_inputs = tf.unstack(decoder_inputs, axis=1) # max_enc_steps * [batch_size]\n answer_batch_unstack = tf.unstack(answer_batch, axis=1)\n\n # initialize all the variables\n state_t_1 = init_state\n context_t_1 = tf.zeros([batch_size, encoder_dim])\n coverage_t_1 = None\n\n # store variables from each time-step\n coverages = []\n attn_dists = []\n p_gens = []\n vocab_scores = []\n sampled_words = []\n self.encoder_features = encoder_features\n with variable_scope.variable_scope(\"attention_decoder\"):\n # Get the weight vectors v and W_c (W_c is for coverage)\n v = variable_scope.get_variable(\"v\", [options.attention_vec_size])\n v = tf.expand_dims(tf.expand_dims(v, axis=0), axis=0)\n w_c = None\n if options.use_coverage:\n with variable_scope.variable_scope(\"coverage\"):\n w_c = variable_scope.get_variable(\"w_c\", [options.attention_vec_size])\n w_c = tf.expand_dims(tf.expand_dims(w_c, axis=0), axis=0)\n\n # For each step, dec_input => lstm_output => vocab_score\n wordidx_t = decoder_inputs[0] # [batch_size] int32\n for i in range(options.max_answer_len):\n if mode_gen in ('ce_train', 'loss',): wordidx_t = decoder_inputs[i] # the wordidx_t must from decoder_inputs for phrase model\n word_t = self.embedding_lookup(wordidx_t)\n if i > 0:\n variable_scope.get_variable_scope().reuse_variables()\n\n (state_t, context_t, coverage_t, attn_dist_t, p_gen_t, output_t) = self.one_step_decoder(\n state_t_1, context_t_1, coverage_t_1, word_t, encoder_states, self.encoder_features,\n passage_word_idx, passage_mask, v, w_c, vocab)\n coverages.append(coverage_t)\n attn_dists.append(attn_dist_t)\n p_gens.append(p_gen_t)\n vocab_scores.append(output_t) # The vocabulary distributions.\n\n state_t_1 = state_t\n context_t_1 = context_t\n coverage_t_1 = coverage_t\n\n if mode_gen == 'greedy':\n wordidx_t = tf.argmax(output_t, 1) # [batch_size]\n wordidx_t = tf.reshape(wordidx_t, [-1]) # [batch_size]\n elif mode_gen == 'sample':\n log_score_t = tf.log(output_t) # [batch_size, vsize]\n wordidx_t = tf.multinomial(log_score_t, 1) # [batch_size, 1]\n wordidx_t = tf.reshape(wordidx_t, [-1]) # [batch_size]\n elif mode_gen in ('ce_train', 'loss',):\n wordidx_t = answer_batch_unstack[i]\n else:\n assert False, 'unknown generating mode %s' % mode_gen\n sampled_words.append(wordidx_t)\n\n if len(sampled_words)!=0:\n sampled_words = tf.stack(sampled_words, axis=1) # [batch_size, max_dec_steps]\n\n vocab_scores = tf.stack(vocab_scores, axis=1) # [batch_size, max_dec_steps, vocab]\n # calculating loss\n self._loss = None\n if mode_gen in ('ce_train', 'loss', ):\n xent = CE_loss(vocab_scores, answer_batch, loss_weights) # [batch_size]\n if mode_gen == 'loss': xent *= self.placeholders.reward # multiply with rewards\n self._loss = tf.reduce_mean(xent)\n # Calculate coverage loss from the attention distributions\n if options.use_coverage:\n with tf.variable_scope('coverage_loss'):\n self._coverage_loss = _coverage_loss(attn_dists, loss_weights)\n self._loss = self._loss + options.cov_loss_wt * self._coverage_loss\n\n # accuracy is calculated only under 'ce_train', where true answer is given\n if mode_gen == 'ce_train':\n accuracy = _mask_and_accuracy(vocab_scores, answer_batch, loss_weights)\n return accuracy, self._loss, sampled_words\n else:\n return None, self._loss, sampled_words\n\n def calculate_encoder_features(self, encoder_states, encoder_dim):\n options = self.options\n input_shape = tf.shape(encoder_states)\n batch_size = input_shape[0]\n passage_len = input_shape[1]\n\n with variable_scope.variable_scope(\"attention_decoder\"):\n encoder_features = tf.expand_dims(encoder_states, axis=2) # now is shape [batch_size, passage_len, 1, encoder_dim]\n W_h = variable_scope.get_variable(\"W_h\", [1, 1, encoder_dim, options.attention_vec_size])\n self.W_h = W_h\n encoder_features = nn_ops.conv2d(encoder_features, W_h, [1, 1, 1, 1], \"SAME\") # [batch_size, passage_len, 1, attention_vec_size]\n encoder_features = tf.reshape(encoder_features, [batch_size, passage_len, options.attention_vec_size])\n return encoder_features\n\n def decode_mode(self, word_vocab, beam_size, state_t_1, context_t_1, coverage_t_1, word_t,\n encoder_states, encoder_features, passage_word_idx, passage_mask):\n options = self.options\n\n with variable_scope.variable_scope(\"attention_decoder\"):\n v = variable_scope.get_variable(\"v\", [options.attention_vec_size])\n v = tf.expand_dims(tf.expand_dims(v, axis=0), axis=0)\n w_c = None\n if options.use_coverage:\n with variable_scope.variable_scope(\"coverage\"):\n w_c = variable_scope.get_variable(\"w_c\", [options.attention_vec_size])\n w_c = tf.expand_dims(tf.expand_dims(w_c, axis=0), axis=0)\n\n word_t_representation = self.embedding_lookup(word_t)\n\n (state_t, context_t, coverage_t, attn_dist_t, p_gen_t, output_t) = self.one_step_decoder(\n state_t_1, context_t_1, coverage_t_1, word_t_representation, encoder_states, encoder_features,\n passage_word_idx, passage_mask, v, w_c, word_vocab)\n vocab_scores = tf.log(output_t)\n greedy_prediction = tf.reshape(tf.argmax(output_t, 1),[-1]) # calcualte greedy\n multinomial_prediction = tf.reshape(tf.multinomial(vocab_scores, 1),[-1]) # calculate multinomial\n topk_log_probs, topk_ids = tf.nn.top_k(vocab_scores, beam_size) # calculate topK\n return (state_t, context_t, coverage_t, attn_dist_t, p_gen_t, output_t, topk_log_probs, topk_ids,\n greedy_prediction, multinomial_prediction)\n\n\n\n\n def merge_prob_dist_for_one_step(self, vocab_dist, attn_dist, p_gen, passage_word_idx, passage_mask=None):\n '''\n max_phrase_size: an input placehoder indications the maximum phrase size inside this batch\n vocab_dist: [batch_size, vsize]\n attn_dist: [batch_size, passage_length]\n p_gen: [batch_size, 1]\n passage_word_idx: [batch_size, passage_length]\n passage_mask: [batch_size, passage_length]\n '''\n input_shape = tf.shape(vocab_dist)\n batch_size = input_shape[0]\n vsize = input_shape[1]\n passage_length = tf.shape(passage_word_idx)[1]\n\n with tf.variable_scope('final_distribution'):\n vocab_dist = p_gen * vocab_dist\n attn_dist = (1.0-p_gen) * attn_dist\n\n # Concatenate some zeros to each vocabulary dist, to hold the probabilities for phrases\n extended_vsize = vsize\n if self.max_phrase_size is not None:\n extended_vsize += self.max_phrase_size\n extra_zeros = tf.zeros((batch_size, self.max_phrase_size))\n vocab_dist = tf.concat(values=[vocab_dist, extra_zeros], axis=1) # [batch_size, extended_vsize]\n if self.options.add_first_word_prob_for_phrase: # add prob of the first word to each phrase\n attn_dist = add_first_word_prob_to_atten_dists(self.in_passage_words, self.phrase_starts,\n vocab_dist, attn_dist)\n\n # match attn_dist[batch_size, passage_length] to sparse one-hot representation [batch_size, passage_length, extended_vsize]\n batch_nums = tf.range(0, limit=batch_size) # shape (batch_size)\n batch_nums = tf.expand_dims(batch_nums, axis=1) # shape (batch_size, 1)\n batch_nums = tf.tile(batch_nums, [1, passage_length]) # shape (batch_size, passage_length)\n step_nums = tf.range(0, limit=passage_length) # [passage_length]\n step_nums = tf.expand_dims(step_nums, axis=0) # shape (1, passage_length)\n step_nums = tf.tile(step_nums, [batch_size, 1]) # shape (batch_size, passage_length)\n indices = tf.stack((batch_nums, step_nums, passage_word_idx), axis=2) # shape (batch_size, passage_length, 3)\n indices = tf.reshape(indices, [-1, 3]) #[batch_size * passage_length, 3]\n indices = tf.cast(indices, tf.int64)\n\n shape = [batch_size, passage_length, extended_vsize]\n shape = tf.cast(shape, tf.int64)\n\n attn_dist = tf.reshape(attn_dist, shape=[-1]) # [batch_size*passage_length]\n one_hot_spare_rep = tf.SparseTensor(indices=indices, values=attn_dist, dense_shape=shape) # [batch_size, passage_length, extended_vsize]\n\n if passage_mask is not None:\n passage_mask = tf.expand_dims(passage_mask, axis=-1)\n one_hot_spare_rep = one_hot_spare_rep * passage_mask\n\n one_hot_spare_rep = tf.sparse_reduce_sum(one_hot_spare_rep, axis=1) # [batch_size, extended_vsize]\n vocab_dist = tf.add(vocab_dist, one_hot_spare_rep)\n\n if self.options.add_first_word_prob_for_phrase:\n vocab_dist = tf.nn.softmax(vocab_dist) # normalize\n\n return vocab_dist # [batch_size, extended_vsize]\n\ndef linear(args, output_size, bias=True, bias_start=0.0, scope=None):\n if args is None or (isinstance(args, (list, tuple)) and not args):\n raise ValueError(\"`args` must be specified\")\n if not isinstance(args, (list, tuple)):\n args = [args]\n\n # Calculate the total size of arguments on dimension 1.\n total_arg_size = 0\n shapes = [a.get_shape().as_list() for a in args]\n for shape in shapes:\n if len(shape) != 2:\n raise ValueError(\"Linear is expecting 2D arguments: %s\" % str(shapes))\n if not shape[1]:\n raise ValueError(\"Linear expects shape[1] of arguments: %s\" % str(shapes))\n else:\n total_arg_size += shape[1]\n\n # Now the computation.\n with tf.variable_scope(scope or \"Linear\"):\n matrix = tf.get_variable(\"Matrix\", [total_arg_size, output_size])\n if len(args) == 1:\n res = tf.matmul(args[0], matrix)\n else:\n res = tf.matmul(tf.concat(values=args, axis=1), matrix)\n if not bias:\n return res\n bias_term = tf.get_variable(\"Bias\", [output_size], initializer=tf.constant_initializer(bias_start))\n return res + bias_term\n\ndef _clip_and_normalize(word_probs, epsilon):\n '''\n word_probs: 1D tensor of [vsize]\n '''\n word_probs = tf.clip_by_value(word_probs, epsilon, 1.0 - epsilon)\n return word_probs / tf.reduce_sum(word_probs, axis=-1, keep_dims=True) # scale preds so that the class probas of each sample sum to 1\n\n\ndef CE_loss(word_probs, answers, loss_weights):\n '''\n word_probs: [batch_size, max_dec_steps, vocab]\n answers: [batch_size, max_dec_steps]\n loss_weigts: [batch_size, max_dec_steps]\n '''\n #word_probs = tf.nn.softmax(word_probs, dim=-1)\n input_shape = tf.shape(word_probs)\n vsize = input_shape[2]\n\n epsilon = 1.0e-6\n word_probs = _clip_and_normalize(word_probs, epsilon)\n\n one_hot_spare_rep = tf.one_hot(answers, vsize)\n\n xent = -tf.reduce_sum(one_hot_spare_rep * tf.log(word_probs), axis=-1) # [batch_size, max_dec_steps]\n if loss_weights != None:\n xent = xent * loss_weights\n xent = tf.reduce_sum(xent, axis=-1)\n return xent #[batch_size]\n\ndef _mask_and_avg(values, loss_weights):\n \"\"\"Applies mask to values then returns overall average (a scalar)\n\n Args:\n values: a list length max_dec_steps containing arrays shape (batch_size).\n loss_weights: tensor shape (batch_size, max_dec_steps) containing 1s and 0s.\n\n Returns:\n a scalar\n \"\"\"\n if loss_weights == None:\n return tf.reduce_mean(tf.stack(values, axis=0))\n\n dec_lens = tf.reduce_sum(loss_weights, axis=1) # shape batch_size. float32\n values_per_step = [v * loss_weights[:,dec_step] for dec_step,v in enumerate(values)]\n values_per_ex = sum(values_per_step)/dec_lens # shape (batch_size); normalized value for each batch member\n return tf.reduce_mean(values_per_ex) # overall average\n\n\ndef _coverage_loss(attn_dists, loss_weights):\n \"\"\"Calculates the coverage loss from the attention distributions.\n\n Args:\n attn_dists: The attention distributions for each decoder timestep.\n A list length max_dec_steps containing shape (batch_size, attn_length)\n loss_weights: shape (batch_size, max_dec_steps).\n\n Returns:\n coverage_loss: scalar\n \"\"\"\n coverage = tf.zeros_like(attn_dists[0]) # shape (batch_size, attn_length). Initial coverage is zero.\n covlosses = [] # Coverage loss per decoder timestep. Will be list length max_dec_steps containing shape (batch_size).\n for a in attn_dists:\n covloss = tf.reduce_sum(tf.minimum(a, coverage), [1]) # calculate the coverage loss for this step\n covlosses.append(covloss)\n coverage += a # update the coverage vector\n coverage_loss = _mask_and_avg(covlosses, loss_weights)\n return coverage_loss\n\n# values: [batch_size, step_size, vocab_size]\n# answers: [batch_size, step_size]\ndef _mask_and_accuracy(values, answers, loss_weights):\n values = tf.argmax(values,axis=2)\n x = tf.cast(values, dtype=tf.int32)\n y = tf.cast(answers, dtype=tf.int32)\n res = tf.equal(x, y)\n res = tf.cast(res, dtype=tf.float32)\n res = tf.multiply(res, loss_weights)\n return tf.reduce_sum(res)\n\n\n"
] |
[
[
"tensorflow.constant_initializer",
"tensorflow.python.ops.variable_scope.variable_scope",
"tensorflow.python.ops.variable_scope.get_variable",
"tensorflow.multinomial",
"tensorflow.matmul",
"tensorflow.reshape",
"tensorflow.zeros_like",
"tensorflow.clip_by_value",
"tensorflow.stack",
"tensorflow.nn.embedding_lookup",
"tensorflow.nn.softmax",
"tensorflow.tile",
"tensorflow.one_hot",
"tensorflow.tanh",
"tensorflow.cast",
"tensorflow.SparseTensor",
"tensorflow.shape",
"tensorflow.concat",
"tensorflow.sigmoid",
"tensorflow.argmax",
"tensorflow.constant",
"tensorflow.variable_scope",
"tensorflow.python.ops.nn_ops.softmax",
"tensorflow.add",
"tensorflow.sparse_reduce_sum",
"tensorflow.python.ops.variable_scope.get_variable_scope",
"tensorflow.zeros",
"tensorflow.range",
"tensorflow.minimum",
"tensorflow.expand_dims",
"tensorflow.map_fn",
"tensorflow.log",
"tensorflow.device",
"tensorflow.reduce_sum",
"tensorflow.get_variable",
"tensorflow.nn.top_k",
"tensorflow.unstack",
"tensorflow.multiply",
"tensorflow.random_uniform_initializer",
"tensorflow.equal",
"tensorflow.python.ops.nn_ops.conv2d",
"tensorflow.gather",
"tensorflow.nn.xw_plus_b",
"tensorflow.reduce_mean"
]
] |
mengkai94/training
|
[
"2a0aa29e700a33e9d3bf2645d13d89fb525e29fc"
] |
[
"object_detection/pytorch/tools/train_mlperf.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\nr\"\"\"\nBasic training script for PyTorch\n\"\"\"\n\n# Set up custom environment before nearly anything else is imported\n# NOTE: this should be the first import (no not reorder)\nfrom maskrcnn_benchmark.utils.env import setup_environment # noqa F401 isort:skip\n\nimport argparse\nimport os\nimport functools\nimport logging\nimport random\nimport datetime\nimport time\n\nimport torch\nfrom maskrcnn_benchmark.config import cfg\nfrom maskrcnn_benchmark.data import make_data_loader\nfrom maskrcnn_benchmark.solver import make_lr_scheduler\nfrom maskrcnn_benchmark.solver import make_optimizer\nfrom maskrcnn_benchmark.engine.inference import inference\nfrom maskrcnn_benchmark.engine.trainer import do_train\nfrom maskrcnn_benchmark.engine.tester import test\nfrom maskrcnn_benchmark.modeling.detector import build_detection_model\nfrom maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer\nfrom maskrcnn_benchmark.utils.collect_env import collect_env_info\nfrom maskrcnn_benchmark.utils.comm import synchronize, get_rank, is_main_process\nfrom maskrcnn_benchmark.utils.imports import import_file\nfrom maskrcnn_benchmark.utils.logger import setup_logger\nfrom maskrcnn_benchmark.utils.miscellaneous import mkdir\nfrom maskrcnn_benchmark.utils.mlperf_logger import print_mlperf, generate_seeds, broadcast_seeds\n\nfrom mlperf_compliance import mlperf_log\n\ndef test_and_exchange_map(tester, model, distributed):\n results = tester(model=model, distributed=distributed)\n\n # main process only\n if is_main_process():\n # Note: one indirection due to possibility of multiple test datasets, we only care about the first\n # tester returns (parsed results, raw results). In our case, don't care about the latter\n map_results, raw_results = results[0]\n bbox_map = map_results.results[\"bbox\"]['AP']\n segm_map = map_results.results[\"segm\"]['AP']\n else:\n bbox_map = 0.\n segm_map = 0.\n\n if distributed:\n map_tensor = torch.tensor([bbox_map, segm_map], dtype=torch.float32, device=torch.device(\"cuda\"))\n torch.distributed.broadcast(map_tensor, 0)\n bbox_map = map_tensor[0].item()\n segm_map = map_tensor[1].item()\n\n return bbox_map, segm_map\n\ndef mlperf_test_early_exit(iteration, iters_per_epoch, tester, model, distributed, min_bbox_map, min_segm_map):\n # Note: let iters / epoch == 10k, at iter 9999 we've finished epoch 0 and need to test\n if iteration > 0 and (iteration + 1)% iters_per_epoch == 0:\n epoch = iteration // iters_per_epoch\n\n print_mlperf(key=mlperf_log.EVAL_START, value=epoch)\n\n bbox_map, segm_map = test_and_exchange_map(tester, model, distributed)\n # necessary for correctness\n model.train()\n\n print_mlperf(key=mlperf_log.EVAL_TARGET, value={\"BBOX\": min_bbox_map,\n \"SEGM\": min_segm_map})\n logger = logging.getLogger('maskrcnn_benchmark.trainer')\n logger.info('bbox mAP: {}, segm mAP: {}'.format(bbox_map, segm_map))\n\n print_mlperf(key=mlperf_log.EVAL_ACCURACY, value={\"epoch\" : epoch, \"value\":{\"BBOX\" : bbox_map, \"SEGM\" : segm_map}})\n print_mlperf(key=mlperf_log.EVAL_STOP)\n\n # terminating condition\n if bbox_map >= min_bbox_map and segm_map >= min_segm_map:\n logger.info(\"Target mAP reached, exiting...\")\n print_mlperf(key=mlperf_log.RUN_STOP, value={\"success\":True})\n return True\n\n # At this point will start the next epoch, so note this in the log\n # print_mlperf(key=mlperf_log.TRAIN_EPOCH, value=epoch+1)\n return False\n\ndef mlperf_log_epoch_start(iteration, iters_per_epoch):\n # First iteration:\n # Note we've started training & tag first epoch start\n if iteration == 0:\n print_mlperf(key=mlperf_log.TRAIN_LOOP)\n print_mlperf(key=mlperf_log.TRAIN_EPOCH, value=0)\n return\n if iteration % iters_per_epoch == 0:\n epoch = iteration // iters_per_epoch\n print_mlperf(key=mlperf_log.TRAIN_EPOCH, value=epoch)\n\nfrom maskrcnn_benchmark.layers.batch_norm import FrozenBatchNorm2d\ndef cast_frozen_bn_to_half(module):\n if isinstance(module, FrozenBatchNorm2d):\n module.half()\n for child in module.children():\n cast_frozen_bn_to_half(child)\n return module\n\ndef train(cfg, local_rank, distributed):\n # Model logging\n print_mlperf(key=mlperf_log.INPUT_BATCH_SIZE, value=cfg.SOLVER.IMS_PER_BATCH)\n print_mlperf(key=mlperf_log.BATCH_SIZE_TEST, value=cfg.TEST.IMS_PER_BATCH)\n\n print_mlperf(key=mlperf_log.INPUT_MEAN_SUBTRACTION, value = cfg.INPUT.PIXEL_MEAN)\n print_mlperf(key=mlperf_log.INPUT_NORMALIZATION_STD, value=cfg.INPUT.PIXEL_STD)\n print_mlperf(key=mlperf_log.INPUT_RESIZE)\n print_mlperf(key=mlperf_log.INPUT_RESIZE_ASPECT_PRESERVING)\n print_mlperf(key=mlperf_log.MIN_IMAGE_SIZE, value=cfg.INPUT.MIN_SIZE_TRAIN)\n print_mlperf(key=mlperf_log.MAX_IMAGE_SIZE, value=cfg.INPUT.MAX_SIZE_TRAIN)\n print_mlperf(key=mlperf_log.INPUT_RANDOM_FLIP)\n print_mlperf(key=mlperf_log.RANDOM_FLIP_PROBABILITY, value=0.5)\n print_mlperf(key=mlperf_log.FG_IOU_THRESHOLD, value=cfg.MODEL.RPN.FG_IOU_THRESHOLD)\n print_mlperf(key=mlperf_log.BG_IOU_THRESHOLD, value=cfg.MODEL.RPN.BG_IOU_THRESHOLD)\n print_mlperf(key=mlperf_log.RPN_PRE_NMS_TOP_N_TRAIN, value=cfg.MODEL.RPN.PRE_NMS_TOP_N_TRAIN)\n print_mlperf(key=mlperf_log.RPN_PRE_NMS_TOP_N_TEST, value=cfg.MODEL.RPN.PRE_NMS_TOP_N_TEST)\n print_mlperf(key=mlperf_log.RPN_POST_NMS_TOP_N_TRAIN, value=cfg.MODEL.RPN.FPN_POST_NMS_TOP_N_TRAIN)\n print_mlperf(key=mlperf_log.RPN_POST_NMS_TOP_N_TEST, value=cfg.MODEL.RPN.FPN_POST_NMS_TOP_N_TEST)\n print_mlperf(key=mlperf_log.ASPECT_RATIOS, value=cfg.MODEL.RPN.ASPECT_RATIOS)\n print_mlperf(key=mlperf_log.BACKBONE, value=cfg.MODEL.BACKBONE.CONV_BODY)\n print_mlperf(key=mlperf_log.NMS_THRESHOLD, value=cfg.MODEL.RPN.NMS_THRESH)\n\n model = build_detection_model(cfg)\n device = torch.device(cfg.MODEL.DEVICE)\n model.to(device)\n\n optimizer = make_optimizer(cfg, model)\n # Optimizer logging\n print_mlperf(key=mlperf_log.OPT_NAME, value=mlperf_log.SGD_WITH_MOMENTUM)\n print_mlperf(key=mlperf_log.OPT_LR, value=cfg.SOLVER.BASE_LR)\n print_mlperf(key=mlperf_log.OPT_MOMENTUM, value=cfg.SOLVER.MOMENTUM)\n print_mlperf(key=mlperf_log.OPT_WEIGHT_DECAY, value=cfg.SOLVER.WEIGHT_DECAY)\n\n\n scheduler = make_lr_scheduler(cfg, optimizer)\n\n if distributed:\n model = torch.nn.parallel.DistributedDataParallel(\n model, device_ids=[local_rank], output_device=local_rank,\n # this should be removed if we update BatchNorm stats\n broadcast_buffers=False,\n )\n\n arguments = {}\n arguments[\"iteration\"] = 0\n\n output_dir = cfg.OUTPUT_DIR\n\n save_to_disk = get_rank() == 0\n checkpointer = DetectronCheckpointer(\n cfg, model, optimizer, scheduler, output_dir, save_to_disk\n )\n arguments[\"save_checkpoints\"] = cfg.SAVE_CHECKPOINTS\n\n extra_checkpoint_data = checkpointer.load(cfg.MODEL.WEIGHT)\n arguments.update(extra_checkpoint_data)\n\n data_loader, iters_per_epoch = make_data_loader(\n cfg,\n is_train=True,\n is_distributed=distributed,\n start_iter=arguments[\"iteration\"],\n )\n\n checkpoint_period = cfg.SOLVER.CHECKPOINT_PERIOD\n\n # set the callback function to evaluate and potentially\n # early exit each epoch\n if cfg.PER_EPOCH_EVAL:\n per_iter_callback_fn = functools.partial(\n mlperf_test_early_exit,\n iters_per_epoch=iters_per_epoch,\n tester=functools.partial(test, cfg=cfg),\n model=model,\n distributed=distributed,\n min_bbox_map=cfg.MLPERF.MIN_BBOX_MAP,\n min_segm_map=cfg.MLPERF.MIN_SEGM_MAP)\n else:\n per_iter_callback_fn = None\n\n start_train_time = time.time()\n\n do_train(\n model,\n data_loader,\n optimizer,\n scheduler,\n checkpointer,\n device,\n checkpoint_period,\n arguments,\n per_iter_start_callback_fn=functools.partial(mlperf_log_epoch_start, iters_per_epoch=iters_per_epoch),\n per_iter_end_callback_fn=per_iter_callback_fn,\n )\n\n end_train_time = time.time()\n total_training_time = end_train_time - start_train_time\n print(\n \"&&&& MLPERF METRIC THROUGHPUT per GPU={:.4f} iterations / s\".format((arguments[\"iteration\"] * 1.0) / total_training_time)\n )\n\n return model\n\n\n\ndef main():\n mlperf_log.ROOT_DIR_MASKRCNN = os.path.dirname(os.path.abspath(__file__))\n\n parser = argparse.ArgumentParser(description=\"PyTorch Object Detection Training\")\n parser.add_argument(\n \"--config-file\",\n default=\"\",\n metavar=\"FILE\",\n help=\"path to config file\",\n type=str,\n )\n parser.add_argument(\"--local_rank\", type=int, default=0)\n parser.add_argument(\n \"opts\",\n help=\"Modify config options using the command-line\",\n default=None,\n nargs=argparse.REMAINDER,\n )\n\n args = parser.parse_args()\n\n num_gpus = int(os.environ[\"WORLD_SIZE\"]) if \"WORLD_SIZE\" in os.environ else 1\n args.distributed = num_gpus > 1\n\n if is_main_process:\n # Setting logging file parameters for compliance logging\n os.environ[\"COMPLIANCE_FILE\"] = '/MASKRCNN_complVv0.5.0_' + str(datetime.datetime.now())\n mlperf_log.LOG_FILE = os.getenv(\"COMPLIANCE_FILE\")\n mlperf_log._FILE_HANDLER = logging.FileHandler(mlperf_log.LOG_FILE)\n mlperf_log._FILE_HANDLER.setLevel(logging.DEBUG)\n mlperf_log.LOGGER.addHandler(mlperf_log._FILE_HANDLER)\n\n if args.distributed:\n torch.cuda.set_device(args.local_rank)\n torch.distributed.init_process_group(\n backend=\"nccl\", init_method=\"env://\"\n )\n synchronize()\n\n print_mlperf(key=mlperf_log.RUN_START)\n\n # setting seeds - needs to be timed, so after RUN_START\n if is_main_process():\n master_seed = random.SystemRandom().randint(0, 2 ** 32 - 1)\n seed_tensor = torch.tensor(master_seed, dtype=torch.float32, device=torch.device(\"cuda\"))\n else:\n seed_tensor = torch.tensor(0, dtype=torch.float32, device=torch.device(\"cuda\"))\n\n torch.distributed.broadcast(seed_tensor, 0)\n master_seed = int(seed_tensor.item())\n else:\n print_mlperf(key=mlperf_log.RUN_START)\n # random master seed, random.SystemRandom() uses /dev/urandom on Unix\n master_seed = random.SystemRandom().randint(0, 2 ** 32 - 1)\n\n # actually use the random seed\n args.seed = master_seed\n # random number generator with seed set to master_seed\n random_number_generator = random.Random(master_seed)\n print_mlperf(key=mlperf_log.RUN_SET_RANDOM_SEED, value=master_seed)\n\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n cfg.freeze()\n\n output_dir = cfg.OUTPUT_DIR\n if output_dir:\n mkdir(output_dir)\n\n logger = setup_logger(\"maskrcnn_benchmark\", output_dir, get_rank())\n logger.info(\"Using {} GPUs\".format(num_gpus))\n logger.info(args)\n\n # generate worker seeds, one seed for every distributed worker\n worker_seeds = generate_seeds(random_number_generator, torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1)\n\n # todo sharath what if CPU\n # broadcast seeds from rank=0 to other workers\n worker_seeds = broadcast_seeds(worker_seeds, device='cuda')\n\n # Setting worker seeds\n logger.info(\"Worker {}: Setting seed {}\".format(args.local_rank, worker_seeds[args.local_rank]))\n torch.manual_seed(worker_seeds[args.local_rank])\n\n\n logger.info(\"Collecting env info (might take some time)\")\n logger.info(\"\\n\" + collect_env_info())\n\n logger.info(\"Loaded configuration file {}\".format(args.config_file))\n with open(args.config_file, \"r\") as cf:\n config_str = \"\\n\" + cf.read()\n logger.info(config_str)\n logger.info(\"Running with config:\\n{}\".format(cfg))\n\n model = train(cfg, args.local_rank, args.distributed)\n\n print_mlperf(key=mlperf_log.RUN_FINAL)\n\n\nif __name__ == \"__main__\":\n start = time.time()\n main()\n print(\"&&&& MLPERF METRIC TIME=\", time.time() - start)\n"
] |
[
[
"torch.device",
"torch.distributed.get_world_size",
"torch.distributed.init_process_group",
"torch.nn.parallel.DistributedDataParallel",
"torch.manual_seed",
"torch.cuda.set_device",
"torch.distributed.is_initialized",
"torch.distributed.broadcast"
]
] |
s-m-e/poliastro
|
[
"3589806e6b10a5256c9069c5d7efbd4d67ff483a"
] |
[
"tests/test_maneuver.py"
] |
[
"import warnings\n\nimport numpy as np\nimport pytest\nfrom astropy import units as u\nfrom astropy.tests.helper import assert_quantity_allclose\nfrom astropy.time import Time\nfrom numpy.testing import assert_allclose\n\nfrom poliastro.bodies import Earth, Mercury, Moon\nfrom poliastro.maneuver import Maneuver\nfrom poliastro.twobody import Orbit\n\n\ndef test_maneuver_constructor_raises_error_if_invalid_delta_v():\n dv1 = np.zeros(3) * u.km / u.s\n dv2 = np.ones(2) * u.km / u.s # Incorrect dv\n with pytest.raises(ValueError) as excinfo:\n with warnings.catch_warnings():\n # Different length numpy arrays generate a deprecation warning.\n warnings.simplefilter(\"ignore\", category=np.VisibleDeprecationWarning)\n Maneuver((0 * u.s, dv1), (2 * u.s, dv2))\n assert \"Delta-V must be three dimensions vectors\" in excinfo.exconly()\n\n\ndef test_maneuver_raises_error_if_units_are_wrong():\n wrong_dt = 1.0\n _v = np.zeros(3) * u.km / u.s # Unused velocity\n with pytest.raises(u.UnitsError) as excinfo:\n Maneuver([wrong_dt, _v])\n assert (\n \"Argument 'dts' to function '_initialize' must be in units convertible to 's'.\"\n in excinfo.exconly()\n )\n\n\ndef test_maneuver_raises_error_if_dvs_are_not_vectors():\n dt = 1 * u.s\n wrong_dv = 1 * u.km / u.s\n with pytest.raises(ValueError) as excinfo:\n Maneuver((dt, wrong_dv))\n assert \"Delta-V must be three dimensions vectors\" in excinfo.exconly()\n\n\ndef test_maneuver_total_time():\n dt1 = 10.0 * u.s\n dt2 = 100.0 * u.s\n _v = np.zeros(3) * u.km / u.s # Unused velocity\n expected_total_time = 110.0 * u.s\n man = Maneuver((dt1, _v), (dt2, _v))\n assert_quantity_allclose(man.get_total_time(), expected_total_time)\n\n\ndef test_maneuver_impulse():\n dv = [1, 0, 0] * u.m / u.s\n man = Maneuver.impulse(dv)\n assert man.impulses[0] == (0 * u.s, dv)\n\n\n@pytest.mark.parametrize(\"nu\", [0, -180] * u.deg)\ndef test_hohmann_maneuver(nu):\n # Data from Vallado, example 6.1\n alt_i = 191.34411 * u.km\n alt_f = 35781.34857 * u.km\n _a = 0 * u.deg\n ss_i = Orbit.from_classical(\n attractor=Earth,\n a=Earth.R + alt_i,\n ecc=0 * u.one,\n inc=_a,\n raan=_a,\n argp=_a,\n nu=nu,\n )\n\n # Expected output\n expected_dv = 3.935224 * u.km / u.s\n expected_t_pericenter = ss_i.time_to_anomaly(0 * u.deg)\n expected_t_trans = 5.256713 * u.h\n expected_total_time = expected_t_pericenter + expected_t_trans\n\n man = Maneuver.hohmann(ss_i, Earth.R + alt_f)\n assert_quantity_allclose(man.get_total_cost(), expected_dv, rtol=1e-5)\n assert_quantity_allclose(man.get_total_time(), expected_total_time, rtol=1e-5)\n\n assert_quantity_allclose(\n ss_i.apply_maneuver(man).ecc, 0 * u.one, atol=1e-14 * u.one\n )\n\n\n@pytest.mark.parametrize(\"nu\", [0, -180] * u.deg)\ndef test_bielliptic_maneuver(nu):\n # Data from Vallado, example 6.2\n alt_i = 191.34411 * u.km\n alt_b = 503873.0 * u.km\n alt_f = 376310.0 * u.km\n _a = 0 * u.deg\n ss_i = Orbit.from_classical(\n attractor=Earth,\n a=Earth.R + alt_i,\n ecc=0 * u.one,\n inc=_a,\n raan=_a,\n argp=_a,\n nu=nu,\n )\n\n # Expected output\n expected_dv = 3.904057 * u.km / u.s\n expected_t_pericenter = ss_i.time_to_anomaly(0 * u.deg)\n expected_t_trans = 593.919803 * u.h\n expected_total_time = expected_t_pericenter + expected_t_trans\n\n man = Maneuver.bielliptic(ss_i, Earth.R + alt_b, Earth.R + alt_f)\n\n assert_allclose(ss_i.apply_maneuver(man).ecc, 0 * u.one, atol=1e-12 * u.one)\n assert_quantity_allclose(man.get_total_cost(), expected_dv, rtol=1e-5)\n assert_quantity_allclose(man.get_total_time(), expected_total_time, rtol=1e-6)\n\n\ndef test_apply_maneuver_correct_dimensions():\n orb = Orbit.from_vectors(\n Moon,\n [-22681.58976181, 942.47776988, 0] * u.km,\n [-0.04578917, -0.19408599, 0.0] * u.km / u.s,\n Time(\"2023-08-30 23:14\", scale=\"tdb\"),\n )\n man = Maneuver((1 * u.s, [0.01, 0, 0] * u.km / u.s))\n\n new_orb = orb.apply_maneuver(man, intermediate=False)\n\n assert new_orb.r.ndim == 1\n assert new_orb.v.ndim == 1\n\n\ndef test_repr_maneuver():\n alt_f = 35781.34857 * u.km\n r = [-6045, -3490, 2500] * u.km\n v = [-3.457, 6.618, 2.533] * u.km / u.s\n alt_b = 503873.0 * u.km\n alt_fi = 376310.0 * u.km\n ss_i = Orbit.from_vectors(Earth, r, v)\n\n expected_hohmann_maneuver = \"Number of impulses: 2, Total cost: 3.060548 km / s\"\n expected_bielliptic_maneuver = \"Number of impulses: 3, Total cost: 3.122556 km / s\"\n\n assert repr(Maneuver.hohmann(ss_i, Earth.R + alt_f)) == expected_hohmann_maneuver\n assert (\n repr(Maneuver.bielliptic(ss_i, Earth.R + alt_b, Earth.R + alt_fi))\n == expected_bielliptic_maneuver\n )\n\n\n# Similar Example obtained from \"Fundamentals of Astrodynamics and Applications, 4th ed (2013)\" by David A. Vallado, page 895\n@pytest.mark.parametrize(\n \"attractor, max_delta_r, a, ecc, inc, expected_t, expected_v\",\n [\n (\n Earth,\n 30 * u.km,\n 6570 * u.km,\n 0.001 * u.one,\n 0.7855682278773197 * u.rad,\n 2224141.03634 * u.s,\n np.array([0, 0.0083290328315531, 0.00833186625871848]) * (u.km / u.s),\n ),\n ],\n)\ndef test_correct_pericenter(\n attractor, max_delta_r, a, ecc, inc, expected_t, expected_v\n):\n ss0 = Orbit.from_classical(\n attractor=attractor,\n a=a,\n ecc=ecc,\n inc=inc,\n raan=0 * u.deg,\n argp=0 * u.deg,\n nu=0 * u.deg,\n )\n\n maneuver = Maneuver.correct_pericenter(ss0, max_delta_r)\n assert_quantity_allclose(maneuver[0][0], expected_t)\n assert_quantity_allclose(maneuver[0][1].value.tolist(), expected_v.value.tolist())\n\n\ndef test_correct_pericenter_J2_exception():\n ss0 = Orbit.from_classical(\n attractor=Mercury,\n a=1000 * u.km,\n ecc=0 * u.one,\n inc=0 * u.deg,\n raan=0 * u.deg,\n argp=0 * u.deg,\n nu=0 * u.deg,\n )\n max_delta_r = 30 * u.km\n with pytest.raises(NotImplementedError) as excinfo:\n Maneuver.correct_pericenter(ss0, max_delta_r)\n assert excinfo.type == NotImplementedError\n assert (\n str(excinfo.value)\n == f\"The correction maneuver is not yet supported for {ss0.attractor}\"\n )\n\n\ndef test_correct_pericenter_ecc_exception():\n ss0 = Orbit.from_classical(\n attractor=Earth,\n a=1000 * u.km,\n ecc=0.5 * u.one,\n inc=0 * u.deg,\n raan=0 * u.deg,\n argp=0 * u.deg,\n nu=0 * u.deg,\n )\n max_delta_r = 30 * u.km\n with pytest.raises(NotImplementedError) as excinfo:\n Maneuver.correct_pericenter(ss0, max_delta_r)\n assert excinfo.type == NotImplementedError\n assert (\n str(excinfo.value)\n == f\"The correction maneuver is not yet supported with {ss0.ecc},it should be less than or equal to 0.001\"\n )\n"
] |
[
[
"numpy.array",
"numpy.ones",
"numpy.zeros"
]
] |
daliwang/CellMigrationGym
|
[
"5801024da812fea4bfce68c41e43f63c14c8400b"
] |
[
"DRL/main.py"
] |
[
"import matplotlib.pyplot as plt\n\n#env related package\nimport gym,pickle,time\nimport numpy as np\nimport pybullet as p\nimport Embryo\n\n#RL related package\nimport torch\n# from stable_baselines.common.vec_env import DummyVecEnv\n# from stable_baselines.deepq.policies import MlpPolicy\n# from stable_baselines import DQN\nfrom Embryo.env.Policy_network import *\n\n#Goal parameters\nAI_CELL = 'Cpaaa'\nTARGET_CELL = 'ABarpaapp'\n\nNEIGHBOR_CANDIDATE_1 = [['ABarppppa', 'ABarppapp'], ['ABarpppap', 'ABarppapp'],\n ['ABarppppa', 'ABarppapp', 'ABarpppap'], ['ABarppapp', 'ABarppapa', 'ABarppppa']]\nNEIGHBOR_CANDIDATE_2 = [['ABarpppap', 'ABarppapa'], ['ABarpppap', 'ABarppaap'], ['ABarpppaa', 'ABarppapa'], ['ABarpppaa', 'ABarppaap'], \n ['ABarpppap', 'ABarppapa', 'ABarpppaa'], ['ABarpppap', 'ABarppapa', 'ABarppaap'], \n ['ABarpppaa', 'ABarppaap', 'ABarpppap'], ['ABarpppaa', 'ABarppaap', 'ABarppapa'],\n ['ABarpppap', 'ABarppapa', 'ABarpppaa', 'ABarppaap']]\nNEIGHBOR_CANDIDATE_3 = [['ABarpppaa', 'ABarppaap']]\n\n#Hyper Parameters\nBATCH_SIZE = 64\nLR = 0.0001 # learning rate, make it larger and try\nEPSILON = 0.3 # greedy policy\nGAMMA = 0.95 # reward discount\nTARGET_REPLACE_ITER = 1000 # target update frequency\nMEMORY_CAPACITY = 8000\n\n###Pre-define parameters\nRENDER_MODE = 'direct' #render mode: direct or gui\n\n\nif torch.cuda.is_available():\n use_cuda = True\nelse:\n use_cuda = False \n\n\ndef demo_run(): \n env = gym.make(\"Embryo-v0\",method = RENDER_MODE)\n dqn = DQN()\n fig1 = plt.figure(1)\n\n plt.ion()\n episode_list = []\n reward_list = []\n reward_list_print = []\n loss_list = []\n episode_loss_list = []\n reward_draw = 0\n loss = -1\n loss_total = 0\n\n episode_action_value_list = []\n action_value_total = 0\n\n state = []\n episode_state = []\n\n epi_suc = []\n movement_types = []\n cpaaa_locations = []\n target_locations = []\n\n print('\\nCollecting experience...')\n\n for i_episode in range(1001):\n action_value_list = []\n if i_episode % 150 == 149:\n dqn.e_greedy += 0.05\n if dqn.e_greedy > 0.95:\n dqn.e_greedy = 0.95\n s = env.reset()\n ep_r = 0\n counter = 0\n\n while True:\n # env.render()\n if i_episode % 1000 == 0:\n name = 'llmodel_' + str(i_episode) + '.pkl'\n torch.save(dqn.eval_net.state_dict(), name)\n\n # state.append(s)\n a = dqn.choose_action(s)\n action_value_list.append(a)\n s_, r, done, info = env.step(a) #take action\n\n dqn.store_transition(s, a, r, s_) #store parameters\n counter += 1\n ep_r += r\n if dqn.memory_counter > MEMORY_CAPACITY:\n loss = dqn.learn() #learn\n if done:\n print('Single episode reward: %f' % r)\n print('Episode:', i_episode, 'Done in', counter, 'steps. Reward:',ep_r,'\\n')\n if r == 1000:\n epi_suc.append(i_episode)\n if i_episode > 900:\n name = 'llmodel_' + str(i_episode) + '_succ.pkl'\n torch.save(dqn.eval_net.state_dict(), name)\n\n if done:\n cpaaa_locations.append(env.ai_locations)\n target_locations.append(env.target_locations)\n episode_action_value_list.append(action_value_list)\n # episode_state.append(state)\n break\n s = s_\n\n reward_draw += ep_r\n\n if i_episode % 10 == 0 and dqn.memory_counter > MEMORY_CAPACITY+220:\n reward_list_print.append(reward_draw/10.0)\n episode_list.append(i_episode)\n\n\n with open('./cpaaa_locations.pkl', 'wb') as f:\n pickle.dump(cpaaa_locations, f)\n \n with open('./target_locations.pkl', 'wb') as f:\n pickle.dump(target_locations, f)\n \n with open('./episode_reward_list.pkl', 'wb') as f:\n pickle.dump((episode_list,reward_list_print), f)\n \n with open('./epi_suc.pkl', 'wb') as f:\n pickle.dump(epi_suc, f)\n\n with open('./episode_action_value_list.pkl', 'wb') as f:\n pickle.dump(episode_action_value_list, f)\n\n # with open('./episode_state.pkl', 'wb') as f:\n # pickle.dump(episode_state, f)\n \n\nif __name__ == '__main__':\n start = time.time()\n demo_run()\n end = time.time()\n print(\"\\nTotal training time : %f \" % (end-start))\n"
] |
[
[
"matplotlib.pyplot.ion",
"torch.cuda.is_available",
"matplotlib.pyplot.figure"
]
] |
Aearsears/mapleai
|
[
"38e067db2e90a21f941bd3c56d0a329741da9d0f"
] |
[
"detect_draw.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 10 14:57:25 2020\n\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nimport pandas as pd\nimport os\nimport csv\nimport cv2\nimport time\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom PIL import Image, ImageDraw, ImageFont\nfrom six import BytesIO\nimport threading\nfrom random import choice\n\nfrom grab_screen import grab_screen,set_window\nfrom Vision import getHP, getMP,getEXP\n\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import config_util\nfrom object_detection.utils import visualization_utils as viz_utils\nfrom object_detection.builders import model_builder\n\nimport character_functions\nimport keyboard\n\nlock = threading.Lock()\n\ndef get_keypoint_tuples(eval_config):\n \"\"\"Return a tuple list of keypoint edges from the eval config.\n \n Args:\n eval_config: an eval config containing the keypoint edges\n \n Returns:\n a list of edge tuples, each in the format (start, end)\n \"\"\"\n tuple_list = []\n kp_list = eval_config.keypoint_edge\n for edge in kp_list:\n tuple_list.append((edge.start, edge.end))\n return tuple_list\n\n\ndef capture_screen():\n \"\"\"\n Main function loop that captures the screen information\n \"\"\"\n #countdown before the function starts\n for i in list(range(4))[::-1]:\n print(i+1)\n time.sleep(1)\n last_time = time.time()\n \n #code to initialize to model. From TF2 object api tutorial!\n pipeline_config = 'path'\n model_dir = 'path'\n\n configs = config_util.get_configs_from_pipeline_file(pipeline_config)\n model_config = configs['model']\n detection_model = model_builder.build(\n model_config=model_config, is_training=False)\n\n # Restore model from the checkpoint\n ckpt = tf.compat.v2.train.Checkpoint(\n model=detection_model)\n ckpt.restore(os.path.join(model_dir, 'ckpt-0')).expect_partial()\n\n detect_fn = get_model_detection_function(detection_model)\n\n label_map_path = configs['eval_input_config'].label_map_path\n label_map = label_map_util.load_labelmap(label_map_path)\n categories = label_map_util.convert_label_map_to_categories(\n label_map,\n max_num_classes=label_map_util.get_max_label_map_index(label_map),\n use_display_name=True)\n category_index = label_map_util.create_category_index(categories)\n label_map_dict = label_map_util.get_label_map_dict(label_map, use_display_name=True)\n\n # infowindow = create_info_screen()\n \n # infowindow.update()\n # sets the maplestory window in focus and in 0,0 position on screen\n set_window(\"Maplestory\")\n\n randommovement = [keyboard.moveLeft,keyboard.moveRight,keyboard.jumpoffladder]\n randomtele = [keyboard.teleright,keyboard.teleleft]\n\n lock.acquire()\n while True:\n lock.acquire()\n choice(randomtele)()\n time.sleep(1)\n screen = grab_screen(process=\"MapleStory\")\n #screen = grab_screen(region=(3,25,803,625))\n #newscreen= screen[30:,:,:]\n #screen = grab_process(\"Maplestory\")\n\n #convert numpy array to tensor\n input_tensor = tf.convert_to_tensor(\n np.expand_dims(screen, 0), dtype=tf.float32)\n #predict it\n detections, predictions_dict, shapes = detect_fn(input_tensor)\n\n #filter out\n boxes,scores,classes,isTherePlayer = character_functions.filter(detections)\n\n #if can't find the character then skip the frame and go next\n if not isTherePlayer:\n choice(randommovement)()\n time.sleep(0.5)\n continue\n \n\n label_id_offset = 1\n image_np_with_detections = screen.copy()\n # Use keypoints if available in detections\n keypoints, keypoint_scores = None, None\n if 'detection_keypoints' in detections:\n keypoints = detections['detection_keypoints'][0].numpy()\n keypoint_scores = detections['detection_keypoint_scores'][0].numpy()\n #draw it with the filtered boxes that the computer sees\n viz_utils.visualize_boxes_and_labels_on_image_array(\n image_np_with_detections,\n boxes,\n classes,\n scores,\n category_index,\n use_normalized_coordinates=True,\n max_boxes_to_draw=10,\n min_score_thresh=0.3,\n agnostic_mode=False,\n keypoints=keypoints,\n keypoint_scores=keypoint_scores,\n keypoint_edges=get_keypoint_tuples(configs['eval_config']))\n\n print('Frame took {} seconds'.format(time.time()-last_time))\n last_time = time.time()\n\n cv2.imshow('window', image_np_with_detections)\n #automatic input into BGR, so need to convert to RGB\n \n #feed boxes and prediction into function that will move character\n character_functions.attack_mob(boxes,classes)\n #wait one seconds before getting next frame and predicting\n lock.release()\n time.sleep(3)\n\n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break\n\ndef get_model_detection_function(model):\n \"\"\"Get a tf.function for detection. From tf2 object api!\"\"\"\n\n @tf.function\n def detect_fn(image):\n \"\"\"Detect objects in image.\"\"\"\n\n image, shapes = model.preprocess(image)\n prediction_dict = model.predict(image, shapes)\n detections = model.postprocess(prediction_dict, shapes)\n\n return detections, prediction_dict, tf.reshape(shapes, [-1])\n\n return detect_fn\n\n\n\ndef load_image_into_numpy_array(path):\n \"\"\"Load an image from file into a numpy array.From tf2 object api!\n\n Puts image into numpy array to feed into tensorflow graph.\n Note that by convention we put it into a numpy array with shape\n (height, width, channels), where channels=3 for RGB.\n\n Args:\n path: the file path to the image\n\n Returns:\n uint8 numpy array with shape (img_height, img_width, 3)\n \"\"\"\n img_data = tf.io.gfile.GFile(path, 'rb').read()\n image = Image.open(BytesIO(img_data))\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n\ndef predict_oneimage():\n pipeline_config = 'path'\n model_dir = 'path'\n\n configs = config_util.get_configs_from_pipeline_file(pipeline_config)\n model_config = configs['model']\n detection_model = model_builder.build(\n model_config=model_config, is_training=False)\n\n # Restore model from the checkpoint\n ckpt = tf.compat.v2.train.Checkpoint(\n model=detection_model)\n ckpt.restore(os.path.join(model_dir, 'ckpt-0')).expect_partial()\n\n detect_fn = get_model_detection_function(detection_model)\n\n image_dir = 'ss/'\n image_path = os.path.join(image_dir, 'ss_63.jpg')\n image_np = load_image_into_numpy_array(image_path)\n # image_np = cv2.imread(image_path)\n\n label_map_path = configs['eval_input_config'].label_map_path\n label_map = label_map_util.load_labelmap(label_map_path)\n categories = label_map_util.convert_label_map_to_categories(\n label_map,\n max_num_classes=label_map_util.get_max_label_map_index(label_map),\n use_display_name=True)\n category_index = label_map_util.create_category_index(categories)\n label_map_dict = label_map_util.get_label_map_dict(label_map, use_display_name=True)\n\n # Things to try:\n # Flip horizontally\n # image_np = np.fliplr(image_np).copy()\n\n # Convert image to grayscale\n # image_np = np.tile(\n # np.mean(image_np, 2, keepdims=True), (1, 1, 3)).astype(np.uint8)\n\n input_tensor = tf.convert_to_tensor(\n np.expand_dims(image_np, 0), dtype=tf.float32)\n detections, predictions_dict, shapes = detect_fn(input_tensor)\n\n label_id_offset = 1\n image_np_with_detections = image_np.copy()\n\n # Use keypoints if available in detections\n keypoints, keypoint_scores = None, None\n if 'detection_keypoints' in detections:\n keypoints = detections['detection_keypoints'][0].numpy()\n keypoint_scores = detections['detection_keypoint_scores'][0].numpy()\n\n\n viz_utils.visualize_boxes_and_labels_on_image_array(\n image_np_with_detections,\n detections['detection_boxes'][0].numpy(),\n (detections['detection_classes'][0].numpy() + label_id_offset).astype(int),\n detections['detection_scores'][0].numpy(),\n category_index,\n use_normalized_coordinates=True,\n max_boxes_to_draw=10,\n min_score_thresh=0.3,\n agnostic_mode=False,\n keypoints=keypoints,\n keypoint_scores=keypoint_scores,\n keypoint_edges=get_keypoint_tuples(configs['eval_config']))\n\n matplotlib.image.imsave('newmodel.png',image_np_with_detections)\n # cv2.imwrite('newmodel.png',image_np_with_detections)\n\n # plt.figure(figsize=(12,16))\n # plt.imshow(image_np_with_detections)\n # plt.show()\n\n\n\ndef buffthr():\n lock.acquire()\n print(\"Buffing!\")\n keyboard.buff()\n lock.release()\n threading.Timer(65,buffthr).start()\n\ndef ccthr():\n lock.acquire()\n print(\"CC'ing!\")\n keyboard.cc()\n time.sleep(1)\n keyboard.pressg()\n lock.release()\n threading.Timer(90,ccthr).start()\n \n\n#main()\nif __name__ == \"__main__\":\n #main loop detect screen thread\n x=threading.Thread(target=capture_screen)\n x.start()\n #autocc thread\n # kill= threading.Event()\n autobuffthread = threading.Thread(target=buffthr)\n autoccthread = threading.Thread(target=ccthr)\n autobuffthread.start()\n autoccthread.start()\n\n # capture_screen()\n #predict_oneimage()"
] |
[
[
"tensorflow.io.gfile.GFile",
"tensorflow.compat.v2.train.Checkpoint",
"matplotlib.image.imsave",
"tensorflow.reshape",
"numpy.expand_dims"
]
] |
Azganoth/unisul-machine-learning
|
[
"c5c8dd65b0084521e4f5f679f53fedb03207a9a2"
] |
[
"marge_skinner.py"
] |
[
"import numpy as np\nimport tkinter as tk\nimport tkinter.ttk as ttk\nfrom pathlib import Path\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.tree import DecisionTreeClassifier\nfrom itertools import islice\nfrom tkinter.messagebox import askyesnocancel, showwarning\nfrom tkinter.filedialog import askopenfilename\nfrom typing import Callable, List, Literal, Tuple\n\nfrom PIL import Image, ImageTk\n\nfrom unisul_machine_learning.weka import load_arff, save_arff\n\n\nFeatures = Tuple[float, float, float, float]\nInstance = Tuple[float, float, float, float, Literal['Marge', 'Skinner']]\nInstances = List[Instance]\n\n# caminhos principais\nroot_path = Path(__file__).parent.resolve()\n\nmarge_samples_path = (root_path / 'samples/marge_simpson').resolve()\nskinner_samples_path = (root_path / 'samples/principal_skinner').resolve()\n\naccepted_image_types = ('jpg', 'jpeg', 'png', 'bmp')\n\n# meta dados do dataset\ndataset_file_path = (root_path / 'marge_skinner_features.arff')\ndataset_name = 'marge_skinner_features'\ndataset_attributes = (\n ('marge_hair', 'real'),\n ('marge_dress', 'real'),\n ('skinner_hair', 'real'),\n ('skinner_suit', 'real'),\n ('class', '{Marge,Skinner}'),\n)\ndataset_instances: Instances = []\n\n# algoritmos classificadores de aprendizado de máquina\nnaive_bayes_classifier = GaussianNB()\ndecision_tree_classifier = DecisionTreeClassifier()\n\n\ndef measure_features(image: Image.Image) -> Features:\n \"\"\"Avalia caracteristicas prédefinidas de uma imagem.\n\n As características avaliadas a são: o cabelo azul da Marge Simpson,\n o vestido verde da Marge Simpson, o cabelo cinza do Diretor Skinner e\n o terno azul do Diretor Skinner.\n\n Parameters\n ----------\n image : Image.Image\n A imagem.\n\n Returns\n -------\n Features\n As pontuações da imagem em cada característica avaliada.\n \"\"\"\n # Cabelo da Marge (azul)\n # rgb(36,50,237) rgb(42,56,243) rgb(53,63,174) rgb(57,73,169)\n # rgb(37,53,149) rgb(68,83,164) rgb(69,50,165) rgb(71,57,171)\n marge_hair_feature_score = 0.0\n\n # Vestido da Marge (verde)\n # rgb(147,193,85) rgb(166,206,83) rgb(103,155,10) rgb(114,167,15)\n # rgb(175,199,111) rgb(176,209,105) rgb(166,164,103) rgb(159,171,97)\n marge_dress_feature_score = 0.0\n\n # Cabelo do Skinner (cinza)\n # rgb(132,115,89) rgb(135,119,122) rgb(167,167,157) rgb(162,163,157)\n # rgb(111,96,91) rgb(116,95,90) rgb(137,134,125) rgb(140,139,137)\n skinner_hair_feature_score = 0.0\n\n # Terno do Skinner (azul)\n # rgb(56,103,129) rgb(56,106,131) rgb(48,103,142) rgb(47,106,146)\n # rgb(48,93,150) rgb(52,95,146) rgb(42,106,116) rgb(43,111,120)\n skinner_suit_feature_score = 0.0\n\n width, height = image.width, image.height\n half_height = (height - 1) / 2\n for x in range(width):\n for y in range(height):\n r, g, b = image.getpixel((x, y))\n\n # verificar cabelo da Marge\n if y < half_height and 35 <= r <= 72 and 50 <= g <= 85 and 145 <= b <= 245:\n marge_hair_feature_score += 1.0\n\n # verificar vestido da Marge\n if y >= half_height and 100 <= r <= 178 and 150 <= g <= 210 and 10 <= b <= 110:\n marge_dress_feature_score += 1.0\n\n # verificar cabelo do Skinner\n if y < half_height and 110 <= r <= 170 and 95 <= g <= 170 and 85 <= b <= 160:\n skinner_hair_feature_score += 1.0\n\n # verificar terno do Skinner\n if y >= half_height and 40 <= r <= 60 and 90 <= g <= 115 and 115 <= b <= 155:\n skinner_suit_feature_score += 1.0\n\n # normalizar a pontuação de cada característica de acordo com o número de pixels na imagem\n marge_hair_feature_score = (marge_hair_feature_score / (width * height)) * 100\n marge_dress_feature_score = (marge_dress_feature_score / (width * height)) * 100\n skinner_hair_feature_score = (skinner_hair_feature_score / (width * height)) * 100\n skinner_suit_feature_score = (skinner_suit_feature_score / (width * height)) * 100\n\n return (marge_hair_feature_score, marge_dress_feature_score,\n skinner_hair_feature_score, skinner_suit_feature_score)\n\n\ndef extract_samples_instances():\n \"\"\"Avalia as características de cada amostra e retorna uma lista de instâncias.\n\n Returns\n -------\n Instances\n A lista de instâncias contêndo a pontuação e classe de cada amostra.\n \"\"\"\n # mostrar cabeçalho das informações que serão mostradas de cada amostra\n print('classe:arquivo | marge_cabelo | marge_vestido | skinner_cabelo | skinner_terno')\n print('------------------------------------------------------------------------------')\n\n samples_instances: Instances = []\n for sample_path in [\n sample_path\n for accepted_image_type in accepted_image_types\n for samples_path in (marge_samples_path, skinner_samples_path)\n for sample_path in islice(samples_path.glob(f'*.{accepted_image_type}'), 600)]:\n sample_instance = (*measure_features(Image.open(sample_path)),\n 'Marge' if sample_path.parent == marge_samples_path else 'Skinner')\n\n # mostrar a pontuação de cada característica e a classe da amostra no console\n print(f'{sample_instance[4]}:{sample_path.stem}',\n '->',\n f'{sample_instance[0]:.{3}f}',\n f'{sample_instance[1]:.{3}f}',\n f'{sample_instance[2]:.{3}f}',\n f'{sample_instance[3]:.{3}f}')\n\n samples_instances.append(sample_instance)\n\n return samples_instances\n\n\ndef predict(image: Image.Image):\n \"\"\"Avalia caracteristicas prédefinidas de uma imagem e\n faz uma predição com base no conjunto de amostras treinados.\n\n Parameters\n ----------\n image : Image.Image\n A imagem.\n\n Returns\n -------\n tuple\n As pontuações da imagem em cada característica e a predição de cada classificador.\n \"\"\"\n features = measure_features(image)\n\n return (features,\n tuple(naive_bayes_classifier.predict_proba([features])[0]),\n tuple(decision_tree_classifier.predict_proba([features])[0]))\n\n\n# GUI\nroot = tk.Tk()\nroot.title('Aprendizado de Máquina - UNISUL')\n\nroot.resizable(False, False)\n\n\n# helpers\ndef frame(parent: tk.Misc, column: int, row: int, column_span: int = 1, row_span: int = 1,\n padx: int = 5, pady: int = 5, sticky: str = ''):\n frame_widget = ttk.Frame(parent)\n frame_widget.grid(column=column, row=row, columnspan=column_span, rowspan=row_span,\n padx=padx, pady=pady, sticky=sticky)\n return frame_widget\n\n\ndef responsive_named_frame(parent: tk.Misc, name: str, orientation: Literal[\"x\", \"y\", \"both\"] = 'x',\n padx: int = 5, pady: int = 5):\n frame_widget = ttk.LabelFrame(parent, text=name)\n frame_widget.pack(fill=orientation, padx=padx, pady=pady)\n return frame_widget\n\n\ndef responsive_text_label(parent: tk.Misc, text: str, padx: int = 5, pady: int = 5):\n label_widget = ttk.Label(parent, text=text)\n label_widget.pack(padx=padx, pady=pady)\n\n\ndef responsive_variable_label(parent: tk.Misc, variable: tk.Variable, padx: int = 5, pady: int = 5):\n label_widget = ttk.Label(parent, textvariable=variable)\n label_widget.pack(padx=padx, pady=pady)\n\n\ndef responsive_item_label(parent: tk.Misc, text: str, variable: tk.Variable,\n padx: int = 5, pady: int = 5):\n child_frame = ttk.Frame(parent)\n child_frame.pack(fill='x', padx=padx, pady=pady)\n label_widget = ttk.Label(child_frame, text=text)\n label_widget.pack(side='left')\n value_widget = ttk.Label(child_frame, textvariable=variable)\n value_widget.pack(side='right')\n\n\ndef responsive_image_label(parent: tk.Misc, padx: int = 5, pady: int = 5):\n label_widget = ttk.Label(parent)\n label_widget.pack(fill='both', padx=padx, pady=pady)\n\n def set_image_label(image: Image.Image):\n image_widget = ImageTk.PhotoImage(image)\n label_widget.configure(image=image_widget)\n label_widget.image = image_widget\n\n return set_image_label\n\n\ndef responsive_button(parent: tk.Misc, text: str, action: Callable, padx: int = 5, pady: int = 5):\n button_widget = ttk.Button(parent, text=text, command=action)\n button_widget.pack(fill='x', padx=padx, pady=pady)\n\n\n# variáveis\nfeature_var_1 = tk.StringVar(value='--')\nfeature_var_2 = tk.StringVar(value='--')\nfeature_var_3 = tk.StringVar(value='--')\nfeature_var_4 = tk.StringVar(value='--')\n\nnaive_bayes_marge_proba_var = tk.StringVar(value='--')\nnaive_bayes_skinner_proba_var = tk.StringVar(value='--')\ndecision_tree_marge_proba_var = tk.StringVar(value='--')\ndecision_tree_skinner_proba_var = tk.StringVar(value='--')\n\ninstances_status_var = tk.StringVar(value='Nenhuma instância treinada')\n\n# quadros\nroot_frame = frame(root, 0, 0, padx=0, pady=0)\nroot_frame.columnconfigure(0, minsize=200)\nroot_frame.columnconfigure(1, minsize=200)\npreview_frame = frame(root_frame, 0, 0, sticky='nsew')\nmain_frame = frame(root_frame, 1, 0, sticky='nsew')\nstatus_frame = frame(root_frame, 0, 1, 2, sticky='nsew')\nstatus_frame.configure(relief='sunken')\n\ntarget_frame = responsive_named_frame(preview_frame, 'Alvo')\nactions_frame = responsive_named_frame(main_frame, 'Ações')\nfeatures_frame = responsive_named_frame(main_frame, 'Características')\npredictions_frame = responsive_named_frame(main_frame, 'Predições')\n\n# widgets\nset_target_image = responsive_image_label(target_frame)\n\nresponsive_item_label(features_frame, 'Cabelo da Marge', feature_var_1)\nresponsive_item_label(features_frame, 'Vestido da Marge', feature_var_2)\nresponsive_item_label(features_frame, 'Cabelo do Skinner', feature_var_3)\nresponsive_item_label(features_frame, 'Terno do Skinner', feature_var_4)\n\nresponsive_text_label(predictions_frame, 'Naive Bayes', pady=10)\nresponsive_item_label(predictions_frame, 'Marge', naive_bayes_marge_proba_var)\nresponsive_item_label(predictions_frame, 'Skinner', naive_bayes_skinner_proba_var)\n\nresponsive_text_label(predictions_frame, 'Árvore de Decisão', pady=10)\nresponsive_item_label(predictions_frame, 'Marge', decision_tree_marge_proba_var)\nresponsive_item_label(predictions_frame, 'Skinner', decision_tree_skinner_proba_var)\n\nresponsive_variable_label(status_frame, instances_status_var, 2, 2)\n\n\n# comandos\ndef train():\n \"\"\"Treina os algoritmos com um conjunto de amostras.\"\"\"\n global dataset_instances\n load_dataset = False\n if dataset_file_path.is_file():\n load_dataset = askyesnocancel(\n 'Um conjunto de amostras treinadas foi encontrado',\n 'Um conjunto de amostras treinadas foi encontrado, deseja carregá-lo?'\n ' Caso não, um novo conjunto será treinado e o substituirá.')\n\n if load_dataset is None:\n return\n elif load_dataset:\n dataset_instances.clear()\n dataset_instances.extend([(float(instance[0]),\n float(instance[1]),\n float(instance[2]),\n float(instance[3]),\n str(instance[4]))\n for instance in load_arff(dataset_file_path)[2]])\n else:\n dataset_instances.clear()\n dataset_instances.extend(extract_samples_instances())\n save_arff(dataset_file_path, dataset_name, dataset_attributes, dataset_instances)\n\n instances_status_var.set(f'Instâncias treinadas: {len(dataset_instances)}')\n\n X = np.array([list(instance[:4]) for instance in dataset_instances])\n y = np.array([instance[4] for instance in dataset_instances])\n\n naive_bayes_classifier.fit(X, y)\n decision_tree_classifier.fit(X, y)\n\n\ndef classify():\n \"\"\"Classifica um imagem.\"\"\"\n if not dataset_instances:\n showwarning('Nenhuma amostra treinada',\n 'Não é possível classificar uma imagem sem amostras treinadas.'\n ' Treine um conjunto de amostras antes de classificar uma imagem.')\n return\n\n image_path = askopenfilename(title='Selecione uma imagem',\n filetypes=(\n (f'{accepted_image_type} images', f'*.{accepted_image_type}')\n for accepted_image_type in accepted_image_types),\n initialdir=root_path)\n\n if image_path:\n target_image = Image.open(image_path)\n\n set_target_image(target_image)\n\n features, naive_bayes_proba, decision_tree_proba = predict(target_image)\n\n feature_var_1.set(f'{features[0]:.{3}f}')\n feature_var_2.set(f'{features[1]:.{3}f}')\n feature_var_3.set(f'{features[2]:.{3}f}')\n feature_var_4.set(f'{features[3]:.{3}f}')\n\n naive_bayes_marge_proba_var.set(f'{naive_bayes_proba[0] * 100:.{3}f}%')\n naive_bayes_skinner_proba_var.set(f'{naive_bayes_proba[1] * 100:.{3}f}%')\n decision_tree_marge_proba_var.set(f'{decision_tree_proba[0] * 100:.{3}f}%')\n decision_tree_skinner_proba_var.set(f'{decision_tree_proba[1] * 100:.{3}f}%')\n\n\n# ações\nresponsive_button(actions_frame, 'Treinar', train)\nresponsive_button(actions_frame, 'Classificar', classify)\n\nroot.mainloop()\n"
] |
[
[
"numpy.array",
"sklearn.naive_bayes.GaussianNB",
"sklearn.tree.DecisionTreeClassifier"
]
] |
reddyprasade/Digit-Recognizer-with-Python
|
[
"75545c9f81889ef561deb7949778f748c0745794"
] |
[
"Digit-Recognizer-with Python.py"
] |
[
"# geport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nfrom sklearn.datasets import load_digits\r\n\r\n# Data Set Loading Form Scikit-Learn\r\nData = load_digits()\r\nprint(\"Description of the Data Optical recognition of handwritten digits dataset\",Data.DESCR)\r\nprint(\"Orginal Data\",Data.data)\r\nprint(\"Data Target_Names\",Data.target_names)\r\nprint(\"Data Target\",Data.target)\r\nprint(\"Images Data Loading\",Data.images)\r\nprint(\"Finding the Shape of Data\",Data.data.shape)\r\n\r\n### Data Set Loading to Pandas\r\n##Digits_DataSets = pd.DataFrame(Data,columns=Data.target_names)\r\n##print(Digits_DataSets.head())\r\n\r\n\r\n\r\n# Data Visulization\r\nimport matplotlib.pyplot as plt\r\n#plt.gray() \r\nplt.imshow(Data.images[1]) \r\nplt.show()\r\n"
] |
[
[
"matplotlib.pyplot.show",
"sklearn.datasets.load_digits",
"matplotlib.pyplot.imshow"
]
] |
ebt-hpc/cca-ebt
|
[
"4e8a515207df6f4bc1538c734077b0c01b34effe"
] |
[
"python/src/cca/ebt/make_loop_classifier.py"
] |
[
"#!/usr/bin/env python3\n\n\n'''\n A script for making loop classifiers\n\n Copyright 2013-2018 RIKEN\n Copyright 2018-2020 Chiba Institute of Technology\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__author__ = 'Masatomo Hashimoto <m.hashimoto@stair.center>'\n\nimport os\nimport csv\nimport numpy as np\n# import scipy as sp\nfrom sklearn.neighbors import KNeighborsClassifier\n# from sklearn.neighbors import RadiusNeighborsClassifier\nfrom sklearn.svm import SVC\n# from sklearn.svm import LinearSVC\n# from sklearn.svm import NuSVC\n# from sklearn.naive_bayes import GaussianNB, MultinomialNB, BernoulliNB\n# from sklearn.ensemble import RandomForestClassifier\n# from sklearn.ensemble import ExtraTreesClassifier\n# from sklearn.ensemble import AdaBoostClassifier\n# from sklearn.feature_selection import SelectKBest, SelectFromModel\n# from sklearn.feature_selection import chi2, f_classif\n# from sklearn import grid_search\n# from sklearn import model_selection\nfrom sklearn.metrics import (accuracy_score, precision_score, recall_score,\n f1_score)\nfrom sklearn import preprocessing as pp\nimport joblib\nimport logging\n\nlogger = logging.getLogger()\n\nMETA = [\n 'proj',\n 'ver',\n 'path',\n 'lnum',\n 'sub',\n 'root_file',\n 'nid',\n 'digest',\n]\n\nJUDGMENTS = ['judgment_M',\n # 'judgment_T',\n # 'judgment_X',\n ]\n\nN_JUDGMENTS = len(JUDGMENTS)\n\nMETRICS = [\n 'max_array_rank',\n 'max_loop_level',\n 'max_loop_depth',\n 'max_mergeable_arrays',\n 'max_fusible_loops',\n 'calls',\n 'branches',\n 'stmts',\n 'lines_of_code',\n 'ops',\n 'fp_ops',\n 'bf0',\n 'bf1',\n 'bf2',\n 'array_refs0',\n 'array_refs1',\n 'array_refs2',\n 'dbl_array_refs0',\n 'dbl_array_refs1',\n 'dbl_array_refs2',\n 'indirect_array_refs0',\n 'indirect_array_refs1',\n 'indirect_array_refs2',\n]\n\nSELECTED = [\n 'max_loop_level',\n 'max_loop_depth',\n 'max_mergeable_arrays',\n 'max_fusible_loops',\n 'indirect_array_refs0',\n 'calls',\n 'bf0',\n]\n\nDERIVED = [\n # 'br_rate',\n # 'ind_aref_rate0',\n # 'array_rank_rate',\n]\n\n\ndef rate(x, y):\n return float(x) / float(y)\n\n\nDERIVED_F_TBL = {\n 'br_rate': rate,\n 'ind_aref_rate0': rate,\n 'array_rank_rate': rate,\n}\nDERIVED_A_TBL = {\n 'br_rate': ('branches', 'stmts'),\n 'ind_aref_rate0': ('indirect_array_refs0', 'array_refs0'),\n 'array_rank_rate': ('max_array_rank', 7.),\n}\n\n###\n\n# SELECTED_MINAMI = [ # CA=.832,P=.837056,R=.971948,F1=.894753\n# 'max_loop_level',\n# 'max_loop_depth',\n# 'max_mergeable_arrays',\n# 'max_fusible_loops',\n# 'indirect_array_refs0',\n# 'calls',\n# 'bf0',\n# ]\nSELECTED_MINAMI = [ # CA=.85,P=.884071,R=.929341,F1=.900756\n 'max_loop_level',\n 'max_loop_depth',\n 'max_mergeable_arrays',\n 'indirect_array_refs0',\n]\nDERIVED_MINAMI = []\n\nSELECTED_TERAI = [\n 'max_array_rank',\n 'max_loop_depth',\n 'max_mergeable_arrays',\n 'max_fusible_loops',\n 'calls',\n 'branches',\n 'stmts',\n 'ops',\n 'fp_ops',\n 'array_refs0',\n 'array_refs1',\n 'dbl_array_refs0',\n 'indirect_array_refs0',\n]\nDERIVED_TERAI = ['ind_aref_rate0']\n\nSELECTED_MIX = [\n 'max_loop_level',\n 'max_loop_depth',\n 'max_mergeable_arrays',\n 'max_fusible_loops',\n 'indirect_array_refs0',\n 'calls',\n 'bf0',\n]\nDERIVED_MIX = []\n\n###\n\n\ndef fromstring(s):\n x = s\n try:\n x = int(s)\n except Exception:\n try:\n x = float(s)\n except Exception:\n pass\n return x\n\n\nclass Data(object):\n def __init__(self, X, y, meta):\n self.X = X\n self.y = y\n self.meta = meta\n\n\ndef get_derived(k, d):\n f = DERIVED_F_TBL[k]\n args = (d.get(a, a) for a in DERIVED_A_TBL[k])\n return f(*args)\n\n\ndef import_training_set(path, selected=SELECTED, derived=DERIVED):\n _Xs = [[] for _ in JUDGMENTS]\n _ys = [[] for _ in JUDGMENTS]\n metas = [[] for _ in JUDGMENTS]\n try:\n with open(path, newline='') as f:\n reader = csv.DictReader(f)\n\n count = 0\n\n for row in reader:\n count += 1\n cs = [row[j] for j in JUDGMENTS]\n d = dict((k, fromstring(row[k])) for k in METRICS)\n x = [d[k] for k in selected]\n\n for k in derived:\n x.append(get_derived(k, d))\n\n meta = dict((k, row[k]) for k in META)\n\n for i in range(N_JUDGMENTS):\n c = cs[i]\n if c != 'Ignored':\n _Xs[i].append(x)\n _ys[i].append(c)\n metas[i].append(meta)\n\n logger.info('%d rows' % count)\n\n except Exception as e:\n logger.warning(str(e))\n\n data = []\n for i in range(N_JUDGMENTS):\n X = np.array(_Xs[i])\n y = np.array(_ys[i])\n meta = metas[i]\n data.append(Data(X, y, meta))\n\n return data\n\n\ndef makeMinamiClassifier(path):\n dataset = import_training_set(path, selected=SELECTED_MINAMI,\n derived=DERIVED_MINAMI)\n data = dataset[0]\n logger.info('shape=%s |y|=%d' % (data.X.shape, len(data.y)))\n clf = SVC(C=32., kernel='rbf', gamma=8.)\n X = pp.scale(data.X)\n clf.fit(X, data.y)\n return clf\n\n\ndef makeTeraiClassifier(path):\n dataset = import_training_set(path, selected=SELECTED_TERAI,\n derived=DERIVED_TERAI)\n data = dataset[1]\n logger.info('shape=%s |y|=%d' % (data.X.shape, len(data.y)))\n clf = KNeighborsClassifier(6, weights='distance', metric='hamming')\n X = pp.scale(data.X)\n clf.fit(X, data.y)\n return clf\n\n\ndef makeMixClassifier(path):\n dataset = import_training_set(path, selected=SELECTED_MIX,\n derived=DERIVED_MIX)\n data = dataset[2]\n logger.info('shape=%s |y|=%d' % (data.X.shape, len(data.y)))\n clf = SVC(C=32., kernel='rbf', gamma=8.)\n X = pp.scale(data.X)\n clf.fit(X, data.y)\n return clf\n\n\ndef dump_classifier(clf, path):\n logger.info('dumping classifier into \"%s\"' % path)\n joblib.dump(clf, path)\n\n\ndef main():\n from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\n\n parser = ArgumentParser(description='make loop classifier',\n formatter_class=ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('-d', '--debug', dest='debug', action='store_true',\n help='enable debug printing')\n\n parser.add_argument('-m', '--model', dest='model', metavar='MODEL',\n type=str, default='minami',\n choices=['minami', 'terai', 'mix'], help='model')\n\n parser.add_argument('-o', '--outfile', dest='outfile', metavar='PATH',\n type=str, default='a.pkl',\n help='dump result into PATH')\n\n parser.add_argument('dpath', metavar='PATH', type=str,\n help='training dataset')\n\n args = parser.parse_args()\n\n mkclf = makeMinamiClassifier\n\n if args.model == 'minami':\n mkclf = makeMinamiClassifier\n elif args.model == 'terai':\n mkclf = makeTeraiClassifier\n elif args.model == 'mix':\n mkclf = makeMixClassifier\n else:\n logger.warning('\"%s\" is not supported. using default model' % args.model)\n\n clf = mkclf(os.path.abspath(args.dpath))\n\n dump_classifier(clf, os.path.abspath(args.outfile))\n\n\n# judgment_X:\n# Mean accuracy : 0.804000\n# Mean precision: 0.811063\n# Mean recall : 0.966476\n# Mean F1 : 0.875611\n\n# |\n# v\n\n# judgment_M:\n# Mean accuracy : 0.843000\n# Mean precision: 0.847833\n# Mean recall : 0.973127\n# Mean F1 : 0.901993\n\ndef test():\n dataset = import_training_set('survey-outline/training_set_k4.csv',\n selected=SELECTED_MINAMI,\n derived=DERIVED_MINAMI)\n\n # Classifiers\n\n # clf = SVC()\n # params = {\n # 'C': sp.stats.expon(scale=100),\n # 'gamma': sp.stats.expon(scale=.1),\n # 'kernel': ['rbf'],\n # 'class_weight': ['balanced', None],\n # }\n\n # clf = RandomForestClassifier(n_estimators=20)\n # params = {\n # 'max_depth': [3, None],\n # 'max_features' : sp.stats.randint(1, 11),\n # 'min_samples_split': sp.stats.randint(1, 11),\n # 'min_samples_leaf' : sp.stats.randint(1, 11),\n # 'bootstrap': [True, False],\n # 'criterion': ['gini', 'entropy'],\n # }\n\n # clf = model_selection.RandomizedSearchCV(clf, params, n_iter=20)\n\n # clf = KNeighborsClassifier(9, weights='distance', metric='hamming')\n clf = SVC(C=32., kernel='rbf', gamma=8.)\n # clf = SVC(C=2., kernel='rbf', gamma=8.)\n # clf = AdaBoostClassifier(n_estimators=15)\n # clf = SVC(C=512., kernel='rbf', gamma=0.125)\n # clf = KNeighborsClassifier(6, weights='distance', metric='hamming')\n\n T = 10\n\n np.random.seed(0)\n\n data = dataset[0] # Minami\n # data = dataset[1] # Terai\n # data = dataset[2] # Merged\n\n logger.info('shape=%s |y|=%d' % (data.X.shape, len(data.y)))\n\n X = data.X\n\n # Preprocessing\n\n X = pp.scale(X)\n\n # scaler = pp.MinMaxScaler()\n # X = scaler.fit_transform(X)\n\n # Feature Selection\n\n # X = SelectKBest(f_classif, k=2).fit_transform(X, data.y)\n\n # c = ExtraTreesClassifier()\n # c = c.fit(X, data.y)\n # model = SelectFromModel(c, prefit=True)\n # X = model.transform(X)\n\n # lsvc = LinearSVC(C=0.01, penalty=\"l1\", dual=False).fit(X, data.y)\n # model = SelectFromModel(lsvc, prefit=True)\n # X = model.transform(X)\n\n logger.info('shape=%s' % (X.shape,))\n\n # Evaluation\n\n N = 100\n\n accs = 0.\n precs = 0.\n recs = 0.\n f1s = 0.\n\n for n in range(N):\n\n indices = np.random.permutation(len(X))\n\n X_train = X[indices[:-T]]\n y_train = data.y[indices[:-T]]\n\n X_test = X[indices[-T:]]\n y_test = data.y[indices[-T:]]\n\n clf.fit(X_train, y_train)\n\n # print(clf.best_estimator_)\n\n y_pred = clf.predict(X_test)\n\n print('Predicted: %s' % y_pred)\n print('Actual : %s' % y_test)\n\n acc = accuracy_score(y_test, y_pred)\n prec = precision_score(y_test, y_pred, pos_label='Kernel')\n rec = recall_score(y_test, y_pred, pos_label='Kernel')\n f1 = f1_score(y_test, y_pred, pos_label='Kernel')\n\n accs += acc\n precs += prec\n recs += rec\n f1s += f1\n\n print('[%d]' % n)\n print(' Accuracy : %f' % acc)\n print(' Precision: %f' % prec)\n print(' Recall : %f' % rec)\n print(' F1 : %f' % f1)\n\n print\n b = float(N)\n print('Mean accuracy : %f' % (accs/b))\n print('Mean precision: %f' % (precs/b))\n print('Mean recall : %f' % (recs/b))\n print('Mean F1 : %f' % (f1s/b))\n\n\nif __name__ == '__main__':\n # test()\n main()\n"
] |
[
[
"numpy.array",
"numpy.random.seed",
"sklearn.neighbors.KNeighborsClassifier",
"sklearn.svm.SVC",
"sklearn.preprocessing.scale",
"sklearn.metrics.accuracy_score",
"sklearn.metrics.precision_score",
"sklearn.metrics.f1_score",
"sklearn.metrics.recall_score"
]
] |
int-brain-lab/analysis
|
[
"effedfd0b5997411f576b4ebcc747c8613715c24"
] |
[
"python/RT_analysis/RT_dist_plot.py"
] |
[
"# -*- coding: utf-8 -*-\n#\n# Reaction time analysis from wheel data\n#\n# Return all significant wheel velocity changes in each trial\n#\n# Plot histrograms of the reaction times relative to either goCue or stimOn times\n#\n# Author: Naoki Hiratani (N.Hiratani@gmail.com)\n#\nfrom math import *\n\nimport sys\nimport alf.io\nfrom oneibl.one import ONE\nfrom ibllib.misc import pprint\nimport numpy as np\nimport scipy.stats as scist\nfrom os import path\nimport matplotlib.pyplot as plt\n\none = ONE()\n\nclass TrialData():\n def __init__(trials, eid):\n trials.goCue_times, trials.stimOn_times, trials.feedback_times = one.load(eid, dataset_types=['trials.goCue_times', 'trials.stimOn_times', 'trials.feedback_times'])\n\n trials.total_trial_count = len(trials.goCue_times)\n #supplementing the effective feedback time\n for tridx in range( len(trials.feedback_times) ):\n if isnan(trials.feedback_times[tridx]):\n trials.feedback_times[tridx] = trials.stimOn_times[tridx] + 60.0\n \nclass WheelData():\n def __init__(wheel, eid):\n wheel.position, wheel.timestamps = one.load(eid, dataset_types=['wheel.position', 'wheel.timestamps'])\n wheel.data_error = False\n if str(type(wheel.position)) == \"<class 'pathlib.PosixPath'>\" or \\\n str(type(wheel.timestamps)) == \"<class 'pathlib.PosixPath'>\":\n wheel.data_error = True\n else:\n wheel.velocity = wheel.calc_wheel_velocity()\n \n def calc_wheel_velocity(wheel):\n wheel_velocity = []; wheel_velocity.append(0.0);\n for widx in range( len(wheel.position)-1 ):\n wheel_velocity.append( (wheel.position[widx+1] - wheel.position[widx])/(wheel.timestamps[widx+1] - wheel.timestamps[widx]) )\n return wheel_velocity\n \n def calc_trialwise_wheel(wheel, stimOn_times, feedback_times):\n #divide the wheel information into trialwise format by using the data from\n # stimOn_time - pre_duration < t < feedback_time\n #\n wheel.stimOn_pre_duration = 0.3 #[s]\n wheel.total_trial_count = len(stimOn_times)\n \n wheel.trial_position = []\n wheel.trial_timestamps = []\n wheel.trial_velocity = []\n for tridx in range( wheel.total_trial_count ):\n wheel.trial_position.append([])\n wheel.trial_timestamps.append([])\n wheel.trial_velocity.append([])\n \n tridx = 0\n for tsidx in range( len(wheel.timestamps) ):\n timestamp = wheel.timestamps[tsidx]\n while tridx < len(stimOn_times) - 1 and timestamp > stimOn_times[tridx+1] - wheel.stimOn_pre_duration:\n tridx += 1\n \n if stimOn_times[tridx] - wheel.stimOn_pre_duration <= timestamp and \\\n timestamp < feedback_times[tridx]:\n wheel.trial_position[tridx].append( wheel.position[tsidx] )\n wheel.trial_timestamps[tridx].append( wheel.timestamps[tsidx] )\n wheel.trial_velocity[tridx].append( wheel.velocity[tsidx] )\n\n def calc_movement_onset_times(wheel, stimOn_times):\n #a collection of timestamps with a significant speed (>0.5) after more than 50ms of stationary period\n speed_threshold = 0.5\n duration_threshold = 0.05 #[s]\n \n wheel.movement_onset_times = []\n wheel.first_movement_onset_times = np.zeros( (wheel.total_trial_count) ) #FMOT\n wheel.last_movement_onset_times = np.zeros( (wheel.total_trial_count) ) #LMOT\n wheel.movement_onset_counts = np.zeros( (wheel.total_trial_count) )\n \n for tridx in range(len(wheel.trial_timestamps)):\n wheel.movement_onset_times.append([])\n cm_dur = 0.0; #continous stationary duration\n for tpidx in range( len(wheel.trial_timestamps[tridx]) ):\n t = wheel.trial_timestamps[tridx][tpidx];\n if tpidx == 0:\n tprev = stimOn_times[tridx] - wheel.stimOn_pre_duration\n cm_dur += (t - tprev)\n if abs(wheel.trial_velocity[tridx][tpidx]) > speed_threshold:\n if cm_dur > duration_threshold:# and t > stimOn_times[tridx]:\n wheel.movement_onset_times[tridx].append( t )\n cm_dur = 0.0;\n tprev = t\n wheel.movement_onset_counts[tridx] = len(wheel.movement_onset_times[tridx])\n if len(wheel.movement_onset_times[tridx]) == 0: #trials with no explicit movement onset\n wheel.first_movement_onset_times[tridx] = np.NaN\n wheel.last_movement_onset_times[tridx] = np.NaN\n else:\n wheel.first_movement_onset_times[tridx] = wheel.movement_onset_times[tridx][0]\n wheel.last_movement_onset_times[tridx] = wheel.movement_onset_times[tridx][-1]\n\ndef main():\n subject_name = 'CSHL_008'\n data_ranges = ['2019-05-01', '2019-06-03']\n eids = one.search(subject=subject_name,dataset_types=['trials.goCue_times','trials.stimOn_times','trials.feedback_times','wheel.position', 'wheel.timestamps'], date_range=[data_ranges[0], data_ranges[1]])\n goCueRTs = []; stimOnRTs = []\n eid_count = 0\n for eidx in range(len(eids)):\n eid = eids[eidx]\n trials = TrialData(eid)\n wheel = WheelData(eid)\n if wheel.data_error == False:\n wheel.calc_trialwise_wheel(trials.stimOn_times, trials.feedback_times)\n wheel.calc_movement_onset_times(trials.stimOn_times)\n for rtidx in range( len(wheel.first_movement_onset_times) ):\n goCueRTs.append(wheel.first_movement_onset_times[rtidx] - trials.goCue_times[rtidx])\n stimOnRTs.append(wheel.first_movement_onset_times[rtidx] - trials.stimOn_times[rtidx])\n eid_count += 1\n\n print('number of sessions: ' + str(eid_count))\n svfg = plt.figure()\n plt.subplot(1,2,1)\n histtmps = plt.hist(stimOnRTs, range=(-0.3,0.5), bins=100)\n median_rt = np.ma.median( np.ma.masked_invalid(np.array(stimOnRTs)) )\n plt.axvline(median_rt, ls='--', lw=1.5, color='k')\n plt.ylabel('Histgram')\n plt.xlabel('Time [s]')\n plt.title('[Movement onset] - [stimOn]')\n\n plt.subplot(1,2,2)\n histtmps = plt.hist(goCueRTs, range=(-0.3,0.5), bins=100)\n median_rt = np.ma.median( np.ma.masked_invalid(np.array(goCueRTs)) )\n plt.axvline(median_rt, ls='--', lw=1.5, color='k')\n plt.xlabel('Time [s]')\n plt.title('[Movement onset] - [goCue]')\n \n plt.show()\n svfg.savefig('fig_RT_hist_all_subject_' + subject_name + '_Nsessions' + str(eid_count) + '.pdf')\n\nif __name__ == \"__main__\":\n param = sys.argv\n main()\n \n"
] |
[
[
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.axvline",
"matplotlib.pyplot.subplot"
]
] |
tomxi/guitar-set
|
[
"82cc1477758f3bc32d6c7fdaae2cdcaccd6cc2b0"
] |
[
"mirapie/utils/wav.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCopyright (c) 2015, Antoine Liutkus, Inria\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n * Neither the name of the <organization> nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\"\"\nimport numpy as np\nimport wave\nimport os\n\n\ndef wavinfo(filename):\n \"\"\"returns metadata properties of a file\"\"\"\n fileHandle = wave.open(filename, 'r')\n nChans = fileHandle.getnchannels()\n fs = fileHandle.getframerate()\n length = fileHandle.getnframes()\n sampleWidth = fileHandle.getsampwidth()\n fileHandle.close()\n return length, nChans, fs, sampleWidth\n\n\ndef wavwrite(signal, fs, destinationFile, nbytes=2,verbose=True):\n \"\"\"writes audio data into a file\"\"\"\n fileHandle = wave.open(destinationFile, 'wb')\n fileHandle.setparams(\n (signal.shape[1],\n nbytes,\n fs,\n signal.shape[0],\n 'NONE',\n 'not compressed'))\n pos = 0\n length = signal.shape[0]\n batchSize = 3000000\n\n while pos < length:\n batchSize = min(batchSize, length - pos)\n tempdata = np.minimum(np.abs(signal[pos:pos+batchSize, :].flatten()), 0.98)*np.sign(signal[pos:pos+batchSize,:].flatten())\n dataVec = (2 ** (nbytes * 8 - 1) * tempdata).astype(np.int16)\n values = dataVec.tostring()\n fileHandle.writeframes(values)\n pos += batchSize\n fileHandle._file.flush()\n os.fsync(fileHandle._file)\n fileHandle.close()\n if verbose:\n print('File written to ' + destinationFile)\n\n\ndef wavread(fileName, lmax=np.infty, offset = 0, len_in_smpl = False):\n \"\"\"reads the wave file file and returns a NDarray and the sampling frequency\"\"\"\n\n def isValid(filename):\n if not fileName:\n return False\n try:\n fileHandle = wave.open(fileName, 'r')\n fileHandle.close()\n return True\n except:\n return False\n if not isValid(fileName):\n print(\"invalid WAV file. Aborting\")\n return None\n\n # metadata properties of a file\n length, nChans, fs, sampleWidth = wavinfo(fileName)\n if not len_in_smpl:\n lmax = lmax * fs\n length = min(length - offset, lmax)\n waveform = np.zeros((length, nChans))\n\n # reading data\n fileHandle = wave.open(fileName, 'r')\n fileHandle.setpos(offset)\n batchSizeT = 3000000\n pos = 0\n while pos < length:\n batchSize = min(batchSizeT, length - pos)\n str_bytestream = fileHandle.readframes(int(batchSize*2/sampleWidth))\n tempData = np.fromstring(str_bytestream, 'h')\n tempData = tempData.astype(float)\n tempData = tempData.reshape(batchSize, nChans)\n waveform[pos:pos+batchSize, :] = tempData / float(2**(8*sampleWidth - 1))\n pos += batchSize\n fileHandle.close()\n return (waveform, fs)\n\ndef to_mono(sig):\n if (sig.shape[1] > 1):\n sig = 0.5*(sig[:,0] + sig[:,1])\n return (sig)\n"
] |
[
[
"numpy.fromstring",
"numpy.zeros"
]
] |
fermi-lat/BayesianBlocks
|
[
"83580da7938cfb7646d659974f727cc001e550cb",
"83580da7938cfb7646d659974f727cc001e550cb"
] |
[
"python/test_BB.py",
"python/BayesianBlocks_python.py"
] |
[
"\"\"\"\n@brief Comparison of C++ and pure Python implementations for the three\ndifferent modes (unbinned, binned, and point measurement). The\nreconstructions should be identical.\n\n@author J. Chiang\n\"\"\"\n#\n# $Header: /nfs/slac/g/glast/ground/cvs/ScienceTools-scons/BayesianBlocks/python/test_BB.py,v 1.1.1.1 2011/09/03 00:55:59 jchiang Exp $\n#\nimport numpy as num\nimport numpy.random as ra\nimport BayesianBlocks\nimport BayesianBlocks_python\nimport pylab_plotter as plot\nfrom distributions import Gaussian\nplot.pylab.ion()\n\nBayesianBlocks.BayesianBlocks_enableFPE()\n\n#\n# Unbinned mode\n#\ninterval0 = num.sort(ra.random(20))\ninterval1 = num.sort(ra.random(100)) + interval0[-1]\ninterval2 = num.sort(ra.random(20)) + interval1[-1]\n\nseq = num.concatenate((interval0, interval1, interval2))\ntmin = 0\ntmax = seq[-1] + num.mean(seq[1:] - seq[:-1])\n\nbb = BayesianBlocks.BayesianBlocks(seq, tmin, tmax)\nbbp = BayesianBlocks_python.BayesianBlocks(seq)\n\nxr = (0, 3)\nbins = 50\nbinsize = float(xr[1] - xr[0])/bins\nwin0 = plot.Window(0)\nplot.histogram(seq, xrange=xr, bins=bins)\n\nfor ncpPrior in range(1, 10):\n xx, yy = bb.lightCurve(ncpPrior)\n plot.curve(xx, num.array(yy)*binsize, color='r', linewidth=3)\n\n xxp, yyp = bbp.lightCurve(ncpPrior)\n plot.curve(xxp, num.array(yyp)*binsize, color='b', linewidth=1)\n\n#\n# Exposure weighting in unbinned mode\n#\nexposures = ra.random(len(seq))\nbb.setCellSizes(exposures)\n\nwin1 = plot.Window(1)\nfor ncpPrior in range(1, 10):\n xx, yy = bb.lightCurve(ncpPrior)\n plot.curve(xx, num.array(yy)*binsize, color='r', linewidth=5)\n\n#\n# Binned mode\n#\nfunc0 = Gaussian(1, 10, 3)\nclass Histogram(object):\n def __init__(self, xmin, xmax, nx):\n self.bins = num.zeros(nx, dtype=num.float)\n self.xstep = (xmax - xmin)/float(nx-1)\n self.xvals = num.linspace(xmin, xmax, nx) + self.xstep/2.\n def add(self, x, wt=1):\n i = int((x - self.xvals[0])/self.xstep)\n if i < len(self.bins):\n self.bins[i] += wt\n\nhist = Histogram(0, 20, 30)\nfor i in range(100):\n hist.add(func0.draw())\n\nbb = BayesianBlocks.BayesianBlocks(hist.xvals[0] - hist.xstep/2.,\n hist.bins, \n num.ones(len(hist.bins), dtype=num.float)*hist.xstep)\n \nbbp = BayesianBlocks_python.BayesianBlocks(hist.bins, \n num.ones(len(hist.bins))*hist.xstep,\n hist.xvals[0] - hist.xstep/2.)\nwin2 = plot.Window(2)\nplot.xyplot(hist.xvals, hist.bins/hist.xstep, yerr=num.sqrt(hist.bins))\nfor ncpPrior in range(1, 10):\n xx, yy = bb.lightCurve(ncpPrior)\n plot.curve(xx, yy, color='r', linewidth=3)\n\n print (ncpPrior)\n xxp, yyp = bbp.lightCurve(ncpPrior)\n plot.curve(xxp, yyp, color='g', linewidth=1)\n\n#\n# Point measurement mode\n#\nfunc1 = Gaussian(1, 5, 1)\nfunc2 = Gaussian(1, 10, 1)\nfunc3 = Gaussian(1, 6, 1)\n\ny = [func1.draw() for x in range(10)]\ny.extend([func2.draw() for x in range(10)])\ny.extend([func3.draw() for x in range(10)])\ndy = num.ones(len(y))\nx = range(len(y))\n\nbb = BayesianBlocks.BayesianBlocks(x, y, dy)\nbbp = BayesianBlocks_python.BayesianBlocks(x, y, dy)\n\nwin3 = plot.Window(3)\n\nplot.xyplot(x, y, yerr=dy)\nfor ncpPrior in range(1, 10):\n xx, yy = bb.lightCurve(ncpPrior)\n plot.curve(xx, yy, color='r', linewidth=5)\n\n xxp, yyp = bbp.lightCurve(ncpPrior)\n plot.curve(xxp, yyp, color='g', linewidth=3)\n",
"\"\"\"\n@brief Pure python implementation of the Bayesian Blocks algorithm\ndescribed by Jackson, Scargle et al. 2005, IEEE Signal Processing\nLetters, 12, 105. (http://arxiv.org/abs/math/0309285)\n\n@author J. Chiang <jchiang@slac.stanford.edu>\n\"\"\"\n#\n# $Id: BayesianBlocks_python.py,v 1.1.1.1 2011/09/03 00:55:59 jchiang Exp $\n#\nimport copy\nimport numpy as num\n\ndef gammln(xx):\n cof = [76.18009172947146, -86.50532032941677,\n 24.01409824083091, -1.231739572450155,\n 0.1208650973866179e-2, -0.5395239384953e-5]\n y = xx\n x = xx\n tmp = x + 5.5\n tmp -= (x + 0.5)*num.log(tmp)\n ser = 1.000000000190015\n for j in range(6):\n y += 1\n ser += cof[j]/y\n return -tmp + num.log(2.5066282746310005*ser/x)\n\nclass BayesianBlocks(object):\n \"\"\" \n Unbinned mode:\n >>> bb = BayesianBlocks(arrival_times)\n\n Binned:\n >>> bb = BayesianBlocks(bin_content, bin_sizes, start_time)\n\n Point measurements:\n >>> bb = BayesianBlocks(time, flux, errors)\n\n Obtaining the piecewise constant light curve:\n >>> time, rate = bb.globalOpt(ncp_prior=1)\n \"\"\"\n def __init__(self, *argv):\n self.point_mode = False\n self.use_ml = True\n if len(argv) == 1:\n events = list(argv[0])\n events.sort()\n events = num.array(events)\n self.cellContent = num.ones(len(argv[0]))\n self.cellSizes = self._generateCells(events)\n self.binned = False\n else:\n try:\n self._readPointData(argv)\n except TypeError:\n self.cellContent = copy.deepcopy(argv[0])\n self.cellSizes = copy.deepcopy(argv[1])\n self.tstart = argv[2]\n self.binned = True\n def _readPointData(self, argv):\n x, y, dy = (list(copy.deepcopy(argv[0])), \n list(copy.deepcopy(argv[1])),\n list(copy.deepcopy(argv[2])))\n if len(x) != len(y) or len(y) != len(dy):\n raise RuntimeError(\"Point measurement mode: \" + \n \"input array sizes do not match\")\n x.insert(0, x[0] - (x[1] - x[0]))\n x.append(x[-1] + (x[-1] - x[-2]))\n x = num.array(x)\n cell_bounds = (x[1:] + x[:-1])/2.\n self.tstart = cell_bounds[0]\n self.cellSizes = cell_bounds[1:] - cell_bounds[:-1]\n self.cellContent = y\n self.fluxes = num.array(y)\n self.errors = num.array(dy)\n self.point_mode = True\n def lightCurve(self, ncp_prior=1, use_ml=True):\n return self.globalOpt(ncp_prior, use_ml)\n def globalOpt(self, ncp_prior=1, use_ml=True):\n if self.point_mode:\n blockCost = self.blockCost_point\n else:\n blockCost = self.blockCost\n self.use_ml = use_ml\n opt, last = [], []\n opt.append(blockCost(0, 0) - ncp_prior)\n last.append(0)\n npts = len(self.cellContent)\n for nn in range(1, npts):\n max_opt = blockCost(0, nn) - ncp_prior\n jmax = 0\n for j in range(1, nn+1):\n my_opt = opt[j-1] + blockCost(j, nn) - ncp_prior\n if my_opt > max_opt:\n max_opt = my_opt\n jmax = j\n opt.append(max_opt)\n last.append(jmax)\n changePoints = []\n indx = last[-1]\n while indx > 0:\n changePoints.insert(0, indx)\n indx = last[indx-1]\n changePoints.insert(0, 0)\n changePoints.append(npts)\n return self._lightCurve(changePoints)\n def _lightCurve(self, changePoints):\n xx = []\n yy = []\n cell_sizes = self.cellSizes\n for imin, imax in zip(changePoints[:-1], changePoints[1:]):\n try:\n xx.extend([self.tstart + sum(cell_sizes[:imin]),\n self.tstart + sum(cell_sizes[:imax])])\n except IndexError:\n xx.extend([self.tstart + imin*cell_sizes,\n self.tstart + imax*cell_sizes])\n if self.point_mode:\n f, sig, weights = self._point_block_data(imin, imax-1)\n yval = sum(weights*f)\n else:\n yval = (sum(self.cellContent[imin:imax])\n /sum(cell_sizes[imin:imax]))\n yy.extend([yval, yval])\n return xx, yy\n def _point_block_data(self, imin, imax):\n f, sig = self.fluxes[imin:imax+1], self.errors[imin:imax+1]\n weights = 1./sig**2/sum(1./sig**2)\n return f, sig, weights\n def blockCost_point(self, imin, imax):\n f, sig, weights = self._point_block_data(imin, imax)\n sigx2 = sum(weights*f**2) - (sum(weights*f))**2\n return -sigx2/2*sum(1./sig**2)\n def blockCost(self, imin, imax):\n size = self.blockSize(imin, imax)\n content = self.blockContent(imin, imax)\n if content == 0:\n return 0\n my_cost = content*(num.log(content/size) - 1)\n return my_cost\n def blockSize(self, imin, imax):\n try:\n return sum(self.cellSizes[imin:imax+1])\n except IndexError:\n return self.cellSizes*(imax - imin)\n def blockContent(self, imin, imax):\n return sum(self.cellContent[imin:imax+1])\n def _generateCells(self, events):\n self.tstart = (3*events[0] - events[1])/2.\n bounds = ((events[1:] + events[:-1])/2.).tolist()\n bounds.insert(0, self.tstart)\n bounds.append((3*events[-1] - events[-2])/2.)\n bounds = num.array(bounds)\n return bounds[1:] - bounds[:-1]\n\nif __name__ == '__main__':\n# import hippoplotter as plot\n# import distributions as dist\n# nsamp = 200\n# events = dist.sample(dist.stepFunction(0.5, 0.7, amp=0.7), nsamp)\n#\n# output = open('events.dat', 'w')\n# for event in events:\n# output.write(\"%12.4e\\n\" % event)\n# output.close()\n\n class Histogram(object):\n def __init__(self, xmin, xmax, nx):\n self.xmin = xmin\n self.dx = (xmax - xmin)/float(nx)\n self.binContent = num.zeros(nx)\n self.binSizes = self.dx*num.ones(nx)\n def add(self, xx, wt=1):\n indx = int((xx - self.xmin)/self.dx)\n self.binContent[indx] += wt\n\n events = [float(x.strip()) for x in open('events.dat', 'r')]\n\n hist = Histogram(0, 1, 50)\n for event in events:\n hist.add(event)\n\n bb = BayesianBlocks(events)\n xx, yy = bb.globalOpt(ncp_prior=1)\n\n bb2 = BayesianBlocks(hist.binContent, hist.binSizes, 0)\n xx2, yy2 = bb2.globalOpt(ncp_prior=1)\n\n# plot.histogram(events)\n# plot.scatter(xx, yy, oplot=1, pointRep='Line', color='red', autoscale=1)\n# plot.scatter(xx2, yy2, oplot=1, pointRep='Line', color='blue')\n"
] |
[
[
"numpy.concatenate",
"numpy.array",
"numpy.zeros",
"numpy.mean",
"numpy.sqrt",
"numpy.random.random",
"numpy.linspace"
],
[
"numpy.array",
"numpy.ones",
"numpy.zeros",
"numpy.log"
]
] |
mattl1598/testing
|
[
"cd8124773b83a07301c507ffbb9ccaafbfe7a274",
"cd8124773b83a07301c507ffbb9ccaafbfe7a274",
"cd8124773b83a07301c507ffbb9ccaafbfe7a274",
"cd8124773b83a07301c507ffbb9ccaafbfe7a274",
"cd8124773b83a07301c507ffbb9ccaafbfe7a274"
] |
[
"editing files/Portable Python 3.2.5.1/App/Lib/site-packages/pandas/tseries/offsets.py",
"editing files/Portable Python 3.2.5.1/App/Lib/site-packages/matplotlib/tight_bbox.py",
"editing files/Portable Python 3.2.5.1/App/Lib/site-packages/IPython/extensions/rmagic.py",
"editing files/Portable Python 3.2.5.1/App/Lib/site-packages/pandas/io/tests/test_cparser.py",
"editing files/Portable Python 3.2.5.1/App/Lib/site-packages/matplotlib/dates.py"
] |
[
"from datetime import date, datetime, timedelta\n\nfrom pandas.tseries.tools import to_datetime\n\n# import after tools, dateutil check\nfrom dateutil.relativedelta import relativedelta\nimport pandas.lib as lib\nimport pandas.tslib as tslib\n\n__all__ = ['Day', 'BusinessDay', 'BDay',\n 'MonthBegin', 'BMonthBegin', 'MonthEnd', 'BMonthEnd',\n 'YearBegin', 'BYearBegin', 'YearEnd', 'BYearEnd',\n 'QuarterBegin', 'BQuarterBegin', 'QuarterEnd', 'BQuarterEnd',\n 'Week', 'WeekOfMonth',\n 'Hour', 'Minute', 'Second', 'Milli', 'Micro', 'Nano']\n\n#----------------------------------------------------------------------\n# DateOffset\n\n\nclass CacheableOffset(object):\n\n _cacheable = True\n\n\nclass DateOffset(object):\n \"\"\"\n Standard kind of date increment used for a date range.\n\n Works exactly like relativedelta in terms of the keyword args you\n pass in, use of the keyword n is discouraged-- you would be better\n off specifying n in the keywords you use, but regardless it is\n there for you. n is needed for DateOffset subclasses.\n\n DateOffets work as follows. Each offset specify a set of dates\n that conform to the DateOffset. For example, Bday defines this\n set to be the set of dates that are weekdays (M-F). To test if a\n date is in the set of a DateOffset dateOffset we can use the\n onOffset method: dateOffset.onOffset(date).\n\n If a date is not on a valid date, the rollback and rollforward\n methods can be used to roll the date to the nearest valid date\n before/after the date.\n\n DateOffsets can be created to move dates forward a given number of\n valid dates. For example, Bday(2) can be added to a date to move\n it two business days forward. If the date does not start on a\n valid date, first it is moved to a valid date. Thus psedo code\n is:\n\n def __add__(date):\n date = rollback(date) # does nothing is date is valid\n return date + <n number of periods>\n\n When a date offset is created for a negitive number of periods,\n the date is first rolled forward. The pseudo code is:\n\n def __add__(date):\n date = rollforward(date) # does nothing is date is valid\n return date + <n number of periods>\n\n Zero presents a problem. Should it roll forward or back? We\n arbitrarily have it rollforward:\n\n date + BDay(0) == BDay.rollforward(date)\n\n Since 0 is a bit weird, we suggest avoiding its use.\n \"\"\"\n _cacheable = False\n _normalize_cache = True\n\n def __init__(self, n=1, **kwds):\n self.n = int(n)\n self.kwds = kwds\n if len(kwds) > 0:\n self._offset = relativedelta(**kwds)\n else:\n self._offset = timedelta(1)\n\n def apply(self, other):\n if len(self.kwds) > 0:\n if self.n > 0:\n for i in range(self.n):\n other = other + self._offset\n else:\n for i in range(-self.n):\n other = other - self._offset\n return other\n else:\n return other + timedelta(self.n)\n\n def isAnchored(self):\n return (self.n == 1)\n\n def copy(self):\n return self.__class__(self.n, **self.kwds)\n\n def _should_cache(self):\n return self.isAnchored() and self._cacheable\n\n def _params(self):\n attrs = [(k, v) for k, v in vars(self).items()\n if k not in ['kwds', '_offset', 'name', 'normalize']]\n attrs.extend(list(self.kwds.items()))\n attrs = sorted(set(attrs))\n\n params = tuple([str(self.__class__)] + attrs)\n return params\n\n def __repr__(self):\n if hasattr(self, 'name') and len(self.name):\n return self.name\n\n className = getattr(self, '_outputName', type(self).__name__)\n exclude = set(['n', 'inc'])\n attrs = []\n for attr in self.__dict__:\n if ((attr == 'kwds' and len(self.kwds) == 0)\n or attr.startswith('_')):\n continue\n if attr not in exclude:\n attrs.append('='.join((attr, repr(getattr(self, attr)))))\n\n if abs(self.n) != 1:\n plural = 's'\n else:\n plural = ''\n\n out = '<%s ' % self.n + className + plural\n if attrs:\n out += ': ' + ', '.join(attrs)\n out += '>'\n return out\n\n def __eq__(self, other):\n if other is None:\n return False\n\n if isinstance(other, str):\n from pandas.tseries.frequencies import to_offset\n other = to_offset(other)\n\n if not isinstance(other, DateOffset):\n return False\n\n return self._params() == other._params()\n\n def __ne__(self, other):\n return not self == other\n\n def __hash__(self):\n return hash(self._params())\n\n def __call__(self, other):\n return self.apply(other)\n\n def __add__(self, other):\n return self.apply(other)\n\n def __radd__(self, other):\n return self.__add__(other)\n\n def __sub__(self, other):\n if isinstance(other, datetime):\n raise TypeError('Cannot subtract datetime from offset!')\n elif type(other) == type(self):\n return self.__class__(self.n - other.n, **self.kwds)\n else: # pragma: no cover\n raise TypeError('Cannot subtract %s from %s'\n % (type(other), type(self)))\n\n def __rsub__(self, other):\n return self.__class__(-self.n, **self.kwds) + other\n\n def __mul__(self, someInt):\n return self.__class__(n=someInt * self.n, **self.kwds)\n\n def __rmul__(self, someInt):\n return self.__mul__(someInt)\n\n def __neg__(self):\n return self.__class__(-self.n, **self.kwds)\n\n def rollback(self, dt):\n \"\"\"Roll provided date backward to next offset only if not on offset\"\"\"\n if type(dt) == date:\n dt = datetime(dt.year, dt.month, dt.day)\n\n if not self.onOffset(dt):\n dt = dt - self.__class__(1, **self.kwds)\n return dt\n\n def rollforward(self, dt):\n \"\"\"Roll provided date forward to next offset only if not on offset\"\"\"\n if type(dt) == date:\n dt = datetime(dt.year, dt.month, dt.day)\n\n if not self.onOffset(dt):\n dt = dt + self.__class__(1, **self.kwds)\n return dt\n\n def onOffset(self, dt):\n # XXX, see #1395\n if type(self) == DateOffset or isinstance(self, Tick):\n return True\n\n # Default (slow) method for determining if some date is a member of the\n # date range generated by this offset. Subclasses may have this\n # re-implemented in a nicer way.\n a = dt\n b = ((dt + self) - self)\n return a == b\n\n @property\n def rule_code(self):\n raise NotImplementedError\n\n @property\n def freqstr(self):\n try:\n code = self.rule_code\n except NotImplementedError:\n return repr(self)\n\n if self.n != 1:\n fstr = '%d%s' % (self.n, code)\n else:\n fstr = code\n\n return fstr\n\n\nclass BusinessDay(CacheableOffset, DateOffset):\n \"\"\"\n DateOffset subclass representing possibly n business days\n \"\"\"\n def __init__(self, n=1, **kwds):\n self.n = int(n)\n self.kwds = kwds\n self.offset = kwds.get('offset', timedelta(0))\n self.normalize = kwds.get('normalize', False)\n\n @property\n def rule_code(self):\n return 'B'\n\n def __repr__(self):\n if hasattr(self, 'name') and len(self.name):\n return self.name\n\n className = getattr(self, '_outputName', self.__class__.__name__)\n attrs = []\n\n if self.offset:\n attrs = ['offset=%s' % repr(self.offset)]\n\n if abs(self.n) != 1:\n plural = 's'\n else:\n plural = ''\n\n out = '<%s ' % self.n + className + plural\n if attrs:\n out += ': ' + ', '.join(attrs)\n out += '>'\n return out\n\n @property\n def freqstr(self):\n try:\n code = self.rule_code\n except NotImplementedError:\n return repr(self)\n\n if self.n != 1:\n fstr = '%d%s' % (self.n, code)\n else:\n fstr = code\n\n if self.offset:\n fstr += self._offset_str()\n\n return fstr\n\n def _offset_str(self):\n def get_str(td):\n off_str = ''\n if td.days > 0:\n off_str += str(td.days) + 'D'\n if td.seconds > 0:\n s = td.seconds\n hrs = int(s / 3600)\n if hrs != 0:\n off_str += str(hrs) + 'H'\n s -= hrs * 3600\n mts = int(s / 60)\n if mts != 0:\n off_str += str(mts) + 'Min'\n s -= mts * 60\n if s != 0:\n off_str += str(s) + 's'\n if td.microseconds > 0:\n off_str += str(td.microseconds) + 'us'\n return off_str\n\n if isinstance(self.offset, timedelta):\n zero = timedelta(0, 0, 0)\n if self.offset >= zero:\n off_str = '+' + get_str(self.offset)\n else:\n off_str = '-' + get_str(-self.offset)\n return off_str\n else:\n return '+' + repr(self.offset)\n\n def isAnchored(self):\n return (self.n == 1)\n\n def apply(self, other):\n if isinstance(other, datetime):\n n = self.n\n\n if n == 0 and other.weekday() > 4:\n n = 1\n\n result = other\n\n # avoid slowness below\n if abs(n) > 5:\n k = n // 5\n result = result + timedelta(7 * k)\n if n < 0 and result.weekday() > 4:\n n += 1\n n -= 5 * k\n\n while n != 0:\n k = n // abs(n)\n result = result + timedelta(k)\n if result.weekday() < 5:\n n -= k\n\n if self.normalize:\n result = datetime(result.year, result.month, result.day)\n\n if self.offset:\n result = result + self.offset\n\n return result\n\n elif isinstance(other, (timedelta, Tick)):\n return BDay(self.n, offset=self.offset + other,\n normalize=self.normalize)\n else:\n raise Exception('Only know how to combine business day with '\n 'datetime or timedelta!')\n\n @classmethod\n def onOffset(cls, dt):\n return dt.weekday() < 5\n\n\nclass MonthEnd(DateOffset, CacheableOffset):\n \"\"\"DateOffset of one month end\"\"\"\n\n def apply(self, other):\n other = datetime(other.year, other.month, other.day)\n\n n = self.n\n _, days_in_month = tslib.monthrange(other.year, other.month)\n if other.day != days_in_month:\n other = other + relativedelta(months=-1, day=31)\n if n <= 0:\n n = n + 1\n other = other + relativedelta(months=n, day=31)\n return other\n\n @classmethod\n def onOffset(cls, dt):\n days_in_month = tslib.monthrange(dt.year, dt.month)[1]\n return dt.day == days_in_month\n\n @property\n def rule_code(self):\n return 'M'\n\n\nclass MonthBegin(DateOffset, CacheableOffset):\n \"\"\"DateOffset of one month at beginning\"\"\"\n\n def apply(self, other):\n n = self.n\n\n if other.day > 1 and n <= 0: # then roll forward if n<=0\n n += 1\n\n other = other + relativedelta(months=n, day=1)\n return other\n\n @classmethod\n def onOffset(cls, dt):\n return dt.day == 1\n\n @property\n def rule_code(self):\n return 'MS'\n\n\nclass BusinessMonthEnd(CacheableOffset, DateOffset):\n \"\"\"DateOffset increments between business EOM dates\"\"\"\n\n def isAnchored(self):\n return (self.n == 1)\n\n def apply(self, other):\n other = datetime(other.year, other.month, other.day)\n\n n = self.n\n\n wkday, days_in_month = tslib.monthrange(other.year, other.month)\n lastBDay = days_in_month - max(((wkday + days_in_month - 1)\n % 7) - 4, 0)\n\n if n > 0 and not other.day >= lastBDay:\n n = n - 1\n elif n <= 0 and other.day > lastBDay:\n n = n + 1\n other = other + relativedelta(months=n, day=31)\n\n if other.weekday() > 4:\n other = other - BDay()\n return other\n\n @property\n def rule_code(self):\n return 'BM'\n\n\nclass BusinessMonthBegin(DateOffset, CacheableOffset):\n \"\"\"DateOffset of one business month at beginning\"\"\"\n\n def apply(self, other):\n n = self.n\n\n wkday, _ = tslib.monthrange(other.year, other.month)\n first = _get_firstbday(wkday)\n\n if other.day > first and n <= 0:\n # as if rolled forward already\n n += 1\n elif other.day < first and n > 0:\n other = other + timedelta(days=first - other.day)\n n -= 1\n\n other = other + relativedelta(months=n)\n wkday, _ = tslib.monthrange(other.year, other.month)\n first = _get_firstbday(wkday)\n result = datetime(other.year, other.month, first)\n return result\n\n @classmethod\n def onOffset(cls, dt):\n first_weekday, _ = tslib.monthrange(dt.year, dt.month)\n if first_weekday == 5:\n return dt.day == 3\n elif first_weekday == 6:\n return dt.day == 2\n else:\n return dt.day == 1\n\n @property\n def rule_code(self):\n return 'BMS'\n\n\nclass Week(DateOffset, CacheableOffset):\n \"\"\"\n Weekly offset\n\n Parameters\n ----------\n weekday : int, default None\n Always generate specific day of week. 0 for Monday\n \"\"\"\n def __init__(self, n=1, **kwds):\n self.n = n\n self.weekday = kwds.get('weekday', None)\n\n if self.weekday is not None:\n if self.weekday < 0 or self.weekday > 6:\n raise Exception('Day must be 0<=day<=6, got %d' %\n self.weekday)\n\n self._inc = timedelta(weeks=1)\n self.kwds = kwds\n\n def isAnchored(self):\n return (self.n == 1 and self.weekday is not None)\n\n def apply(self, other):\n if self.weekday is None:\n return other + self.n * self._inc\n\n if self.n > 0:\n k = self.n\n otherDay = other.weekday()\n if otherDay != self.weekday:\n other = other + timedelta((self.weekday - otherDay) % 7)\n k = k - 1\n for i in range(k):\n other = other + self._inc\n else:\n k = self.n\n otherDay = other.weekday()\n if otherDay != self.weekday:\n other = other + timedelta((self.weekday - otherDay) % 7)\n for i in range(-k):\n other = other - self._inc\n return other\n\n def onOffset(self, dt):\n return dt.weekday() == self.weekday\n\n @property\n def rule_code(self):\n suffix = ''\n if self.weekday is not None:\n suffix = '-%s' % (_weekday_dict[self.weekday])\n return 'W' + suffix\n\n_weekday_dict = {\n 0: 'MON',\n 1: 'TUE',\n 2: 'WED',\n 3: 'THU',\n 4: 'FRI',\n 5: 'SAT',\n 6: 'SUN'\n}\n\n\nclass WeekOfMonth(DateOffset, CacheableOffset):\n \"\"\"\n Describes monthly dates like \"the Tuesday of the 2nd week of each month\"\n\n Parameters\n ----------\n n : int\n week : {0, 1, 2, 3, ...}\n 0 is 1st week of month, 1 2nd week, etc.\n weekday : {0, 1, ..., 6}\n 0: Mondays\n 1: Tuesdays\n 2: Wednesdays\n 3: Thursdays\n 4: Fridays\n 5: Saturdays\n 6: Sundays\n \"\"\"\n def __init__(self, n=1, **kwds):\n self.n = n\n self.weekday = kwds['weekday']\n self.week = kwds['week']\n\n if self.n == 0:\n raise Exception('N cannot be 0')\n\n if self.weekday < 0 or self.weekday > 6:\n raise Exception('Day must be 0<=day<=6, got %d' %\n self.weekday)\n if self.week < 0 or self.week > 3:\n raise Exception('Week must be 0<=day<=3, got %d' %\n self.week)\n\n self.kwds = kwds\n\n def apply(self, other):\n offsetOfMonth = self.getOffsetOfMonth(other)\n\n if offsetOfMonth > other:\n if self.n > 0:\n months = self.n - 1\n else:\n months = self.n\n elif offsetOfMonth == other:\n months = self.n\n else:\n if self.n > 0:\n months = self.n\n else:\n months = self.n + 1\n\n return self.getOffsetOfMonth(other + relativedelta(months=months, day=1))\n\n def getOffsetOfMonth(self, dt):\n w = Week(weekday=self.weekday)\n d = datetime(dt.year, dt.month, 1)\n\n d = w.rollforward(d)\n\n for i in range(self.week):\n d = w.apply(d)\n\n return d\n\n def onOffset(self, dt):\n return dt == self.getOffsetOfMonth(dt)\n\n @property\n def rule_code(self):\n suffix = '-%d%s' % (self.week + 1, _weekday_dict.get(self.weekday, ''))\n return 'WOM' + suffix\n\n\nclass BQuarterEnd(DateOffset, CacheableOffset):\n \"\"\"DateOffset increments between business Quarter dates\n startingMonth = 1 corresponds to dates like 1/31/2007, 4/30/2007, ...\n startingMonth = 2 corresponds to dates like 2/28/2007, 5/31/2007, ...\n startingMonth = 3 corresponds to dates like 3/30/2007, 6/29/2007, ...\n \"\"\"\n _outputName = 'BusinessQuarterEnd'\n\n def __init__(self, n=1, **kwds):\n self.n = n\n self.startingMonth = kwds.get('startingMonth', 3)\n\n self.offset = BMonthEnd(3)\n self.kwds = kwds\n\n def isAnchored(self):\n return (self.n == 1 and self.startingMonth is not None)\n\n def apply(self, other):\n n = self.n\n\n wkday, days_in_month = tslib.monthrange(other.year, other.month)\n lastBDay = days_in_month - max(((wkday + days_in_month - 1)\n % 7) - 4, 0)\n\n monthsToGo = 3 - ((other.month - self.startingMonth) % 3)\n if monthsToGo == 3:\n monthsToGo = 0\n\n if n > 0 and not (other.day >= lastBDay and monthsToGo == 0):\n n = n - 1\n elif n <= 0 and other.day > lastBDay and monthsToGo == 0:\n n = n + 1\n\n other = other + relativedelta(months=monthsToGo + 3 * n, day=31)\n\n if other.weekday() > 4:\n other = other - BDay()\n\n return other\n\n def onOffset(self, dt):\n modMonth = (dt.month - self.startingMonth) % 3\n return BMonthEnd().onOffset(dt) and modMonth == 0\n\n @property\n def rule_code(self):\n suffix = '-%s' % _month_dict[self.startingMonth]\n return 'BQ' + suffix\n\n\n_month_dict = {\n 1: 'JAN',\n 2: 'FEB',\n 3: 'MAR',\n 4: 'APR',\n 5: 'MAY',\n 6: 'JUN',\n 7: 'JUL',\n 8: 'AUG',\n 9: 'SEP',\n 10: 'OCT',\n 11: 'NOV',\n 12: 'DEC'\n}\n\n\nclass BQuarterBegin(DateOffset, CacheableOffset):\n _outputName = \"BusinessQuarterBegin\"\n\n def __init__(self, n=1, **kwds):\n self.n = n\n self.startingMonth = kwds.get('startingMonth', 3)\n\n self.offset = BMonthBegin(3)\n self.kwds = kwds\n\n def isAnchored(self):\n return (self.n == 1 and self.startingMonth is not None)\n\n def apply(self, other):\n n = self.n\n\n wkday, _ = tslib.monthrange(other.year, other.month)\n\n first = _get_firstbday(wkday)\n\n monthsSince = (other.month - self.startingMonth) % 3\n\n if n <= 0 and monthsSince != 0: # make sure to roll forward so negate\n monthsSince = monthsSince - 3\n\n # roll forward if on same month later than first bday\n if n <= 0 and (monthsSince == 0 and other.day > first):\n n = n + 1\n # pretend to roll back if on same month but before firstbday\n elif n > 0 and (monthsSince == 0 and other.day < first):\n n = n - 1\n\n # get the first bday for result\n other = other + relativedelta(months=3 * n - monthsSince)\n wkday, _ = tslib.monthrange(other.year, other.month)\n first = _get_firstbday(wkday)\n result = datetime(other.year, other.month, first,\n other.hour, other.minute, other.second,\n other.microsecond)\n return result\n\n @property\n def rule_code(self):\n suffix = '-%s' % _month_dict[self.startingMonth]\n return 'BQS' + suffix\n\n\nclass QuarterEnd(DateOffset, CacheableOffset):\n \"\"\"DateOffset increments between business Quarter dates\n startingMonth = 1 corresponds to dates like 1/31/2007, 4/30/2007, ...\n startingMonth = 2 corresponds to dates like 2/28/2007, 5/31/2007, ...\n startingMonth = 3 corresponds to dates like 3/31/2007, 6/30/2007, ...\n \"\"\"\n _outputName = 'QuarterEnd'\n\n def __init__(self, n=1, **kwds):\n self.n = n\n self.startingMonth = kwds.get('startingMonth', 3)\n\n self.offset = MonthEnd(3)\n self.kwds = kwds\n\n def isAnchored(self):\n return (self.n == 1 and self.startingMonth is not None)\n\n def apply(self, other):\n n = self.n\n\n wkday, days_in_month = tslib.monthrange(other.year, other.month)\n\n monthsToGo = 3 - ((other.month - self.startingMonth) % 3)\n if monthsToGo == 3:\n monthsToGo = 0\n\n if n > 0 and not (other.day >= days_in_month and monthsToGo == 0):\n n = n - 1\n\n other = other + relativedelta(months=monthsToGo + 3 * n, day=31)\n\n return other\n\n def onOffset(self, dt):\n modMonth = (dt.month - self.startingMonth) % 3\n return MonthEnd().onOffset(dt) and modMonth == 0\n\n @property\n def rule_code(self):\n suffix = '-%s' % _month_dict[self.startingMonth]\n return 'Q' + suffix\n\n\nclass QuarterBegin(DateOffset, CacheableOffset):\n _outputName = 'QuarterBegin'\n\n def __init__(self, n=1, **kwds):\n self.n = n\n self.startingMonth = kwds.get('startingMonth', 3)\n\n self.offset = MonthBegin(3)\n self.kwds = kwds\n\n def isAnchored(self):\n return (self.n == 1 and self.startingMonth is not None)\n\n def apply(self, other):\n n = self.n\n\n wkday, days_in_month = tslib.monthrange(other.year, other.month)\n\n monthsSince = (other.month - self.startingMonth) % 3\n\n if n <= 0 and monthsSince != 0:\n # make sure you roll forward, so negate\n monthsSince = monthsSince - 3\n\n if n < 0 and (monthsSince == 0 and other.day > 1):\n # after start, so come back an extra period as if rolled forward\n n = n + 1\n\n other = other + relativedelta(months=3 * n - monthsSince, day=1)\n return other\n\n @property\n def rule_code(self):\n suffix = '-%s' % _month_dict[self.startingMonth]\n return 'QS' + suffix\n\n\nclass BYearEnd(DateOffset, CacheableOffset):\n \"\"\"DateOffset increments between business EOM dates\"\"\"\n _outputName = 'BusinessYearEnd'\n\n def __init__(self, n=1, **kwds):\n self.month = kwds.get('month', 12)\n\n if self.month < 1 or self.month > 12:\n raise ValueError('Month must go from 1 to 12')\n\n DateOffset.__init__(self, n=n, **kwds)\n\n def apply(self, other):\n n = self.n\n\n wkday, days_in_month = tslib.monthrange(other.year, self.month)\n lastBDay = (days_in_month -\n max(((wkday + days_in_month - 1) % 7) - 4, 0))\n\n years = n\n if n > 0:\n if (other.month < self.month or\n (other.month == self.month and other.day < lastBDay)):\n years -= 1\n elif n <= 0:\n if (other.month > self.month or\n (other.month == self.month and other.day > lastBDay)):\n years += 1\n\n other = other + relativedelta(years=years)\n\n _, days_in_month = tslib.monthrange(other.year, self.month)\n result = datetime(other.year, self.month, days_in_month,\n other.hour, other.minute, other.second,\n other.microsecond)\n\n if result.weekday() > 4:\n result = result - BDay()\n\n return result\n\n @property\n def rule_code(self):\n suffix = '-%s' % _month_dict[self.month]\n return 'BA' + suffix\n\n\nclass BYearBegin(DateOffset, CacheableOffset):\n \"\"\"DateOffset increments between business year begin dates\"\"\"\n _outputName = 'BusinessYearBegin'\n\n def __init__(self, n=1, **kwds):\n self.month = kwds.get('month', 1)\n\n if self.month < 1 or self.month > 12:\n raise ValueError('Month must go from 1 to 12')\n\n DateOffset.__init__(self, n=n, **kwds)\n\n def apply(self, other):\n n = self.n\n\n wkday, days_in_month = tslib.monthrange(other.year, self.month)\n\n first = _get_firstbday(wkday)\n\n years = n\n\n if n > 0: # roll back first for positive n\n if (other.month < self.month or\n (other.month == self.month and other.day < first)):\n years -= 1\n elif n <= 0: # roll forward\n if (other.month > self.month or\n (other.month == self.month and other.day > first)):\n years += 1\n\n # set first bday for result\n other = other + relativedelta(years=years)\n wkday, days_in_month = tslib.monthrange(other.year, self.month)\n first = _get_firstbday(wkday)\n return datetime(other.year, self.month, first)\n\n @property\n def rule_code(self):\n suffix = '-%s' % _month_dict[self.month]\n return 'BAS' + suffix\n\n\nclass YearEnd(DateOffset, CacheableOffset):\n \"\"\"DateOffset increments between calendar year ends\"\"\"\n\n def __init__(self, n=1, **kwds):\n self.month = kwds.get('month', 12)\n\n if self.month < 1 or self.month > 12:\n raise ValueError('Month must go from 1 to 12')\n\n DateOffset.__init__(self, n=n, **kwds)\n\n def apply(self, other):\n def _increment(date):\n if date.month == self.month:\n _, days_in_month = tslib.monthrange(date.year, self.month)\n if date.day != days_in_month:\n year = date.year\n else:\n year = date.year + 1\n elif date.month < self.month:\n year = date.year\n else:\n year = date.year + 1\n _, days_in_month = tslib.monthrange(year, self.month)\n return datetime(year, self.month, days_in_month,\n date.hour, date.minute, date.second,\n date.microsecond)\n\n def _decrement(date):\n year = date.year if date.month > self.month else date.year - 1\n _, days_in_month = tslib.monthrange(year, self.month)\n return datetime(year, self.month, days_in_month,\n date.hour, date.minute, date.second,\n date.microsecond)\n\n def _rollf(date):\n if (date.month != self.month or\n date.day < tslib.monthrange(date.year, date.month)[1]):\n date = _increment(date)\n return date\n\n n = self.n\n result = other\n if n > 0:\n while n > 0:\n result = _increment(result)\n n -= 1\n elif n < 0:\n while n < 0:\n result = _decrement(result)\n n += 1\n else:\n # n == 0, roll forward\n result = _rollf(result)\n\n return result\n\n def onOffset(self, dt):\n wkday, days_in_month = tslib.monthrange(dt.year, self.month)\n return self.month == dt.month and dt.day == days_in_month\n\n @property\n def rule_code(self):\n suffix = '-%s' % _month_dict[self.month]\n return 'A' + suffix\n\n\nclass YearBegin(DateOffset, CacheableOffset):\n \"\"\"DateOffset increments between calendar year begin dates\"\"\"\n\n def __init__(self, n=1, **kwds):\n self.month = kwds.get('month', 1)\n\n if self.month < 1 or self.month > 12:\n raise ValueError('Month must go from 1 to 12')\n\n DateOffset.__init__(self, n=n, **kwds)\n\n def apply(self, other):\n def _increment(date):\n year = date.year\n if date.month >= self.month:\n year += 1\n return datetime(year, self.month, 1, date.hour, date.minute,\n date.second, date.microsecond)\n\n def _decrement(date):\n year = date.year\n if date.month < self.month or (date.month == self.month and\n date.day == 1):\n year -= 1\n return datetime(year, self.month, 1, date.hour, date.minute,\n date.second, date.microsecond)\n\n def _rollf(date):\n if (date.month != self.month) or date.day > 1:\n date = _increment(date)\n return date\n\n n = self.n\n result = other\n if n > 0:\n while n > 0:\n result = _increment(result)\n n -= 1\n elif n < 0:\n while n < 0:\n result = _decrement(result)\n n += 1\n else:\n # n == 0, roll forward\n result = _rollf(result)\n\n return result\n\n def onOffset(self, dt):\n return dt.month == self.month and dt.day == 1\n\n @property\n def rule_code(self):\n suffix = '-%s' % _month_dict[self.month]\n return 'AS' + suffix\n\n\n#----------------------------------------------------------------------\n# Ticks\n\nimport operator\n\n\ndef _tick_comp(op):\n def f(self, other):\n return op(self.delta, other.delta)\n return f\n\n\nclass Tick(DateOffset):\n _inc = timedelta(microseconds=1000)\n\n __gt__ = _tick_comp(operator.gt)\n __ge__ = _tick_comp(operator.ge)\n __lt__ = _tick_comp(operator.lt)\n __le__ = _tick_comp(operator.le)\n __eq__ = _tick_comp(operator.eq)\n __ne__ = _tick_comp(operator.ne)\n\n def __add__(self, other):\n if isinstance(other, Tick):\n if type(self) == type(other):\n return type(self)(self.n + other.n)\n else:\n return _delta_to_tick(self.delta + other.delta)\n return self.apply(other)\n\n def __eq__(self, other):\n if isinstance(other, str):\n from pandas.tseries.frequencies import to_offset\n other = to_offset(other)\n\n if isinstance(other, Tick):\n return self.delta == other.delta\n else:\n return DateOffset.__eq__(self, other)\n\n # This is identical to DateOffset.__hash__, but has to be redefined here\n # for Python 3, because we've redefined __eq__.\n def __hash__(self):\n return hash(self._params())\n\n def __ne__(self, other):\n if isinstance(other, str):\n from pandas.tseries.frequencies import to_offset\n other = to_offset(other)\n\n if isinstance(other, Tick):\n return self.delta != other.delta\n else:\n return DateOffset.__ne__(self, other)\n\n @property\n def delta(self):\n return self.n * self._inc\n\n @property\n def nanos(self):\n return _delta_to_nanoseconds(self.delta)\n\n def apply(self, other):\n if type(other) == date:\n other = datetime(other.year, other.month, other.day)\n\n if isinstance(other, (datetime, timedelta)):\n return other + self.delta\n elif isinstance(other, type(self)):\n return type(self)(self.n + other.n)\n else: # pragma: no cover\n raise TypeError('Unhandled type: %s' % type(other))\n\n _rule_base = 'undefined'\n\n @property\n def rule_code(self):\n return self._rule_base\n\n def isAnchored(self):\n return False\n\n\ndef _delta_to_tick(delta):\n if delta.microseconds == 0:\n if delta.seconds == 0:\n return Day(delta.days)\n else:\n seconds = delta.days * 86400 + delta.seconds\n if seconds % 3600 == 0:\n return Hour(seconds / 3600)\n elif seconds % 60 == 0:\n return Minute(seconds / 60)\n else:\n return Second(seconds)\n else:\n nanos = _delta_to_nanoseconds(delta)\n if nanos % 1000000 == 0:\n return Milli(nanos // 1000000)\n elif nanos % 1000 == 0:\n return Micro(nanos // 1000)\n else: # pragma: no cover\n return Nano(nanos)\n\n\ndef _delta_to_nanoseconds(delta):\n if isinstance(delta, Tick):\n delta = delta.delta\n return (delta.days * 24 * 60 * 60 * 1000000\n + delta.seconds * 1000000\n + delta.microseconds) * 1000\n\n\nclass Day(Tick, CacheableOffset):\n _inc = timedelta(1)\n _rule_base = 'D'\n\n\nclass Hour(Tick):\n _inc = timedelta(0, 3600)\n _rule_base = 'H'\n\n\nclass Minute(Tick):\n _inc = timedelta(0, 60)\n _rule_base = 'T'\n\n\nclass Second(Tick):\n _inc = timedelta(0, 1)\n _rule_base = 'S'\n\n\nclass Milli(Tick):\n _rule_base = 'L'\n\n\nclass Micro(Tick):\n _inc = timedelta(microseconds=1)\n _rule_base = 'U'\n\n\nclass Nano(Tick):\n _inc = 1\n _rule_base = 'N'\n\nBDay = BusinessDay\nBMonthEnd = BusinessMonthEnd\nBMonthBegin = BusinessMonthBegin\n\n\ndef _get_firstbday(wkday):\n \"\"\"\n wkday is the result of monthrange(year, month)\n\n If it's a saturday or sunday, increment first business day to reflect this\n \"\"\"\n first = 1\n if wkday == 5: # on Saturday\n first = 3\n elif wkday == 6: # on Sunday\n first = 2\n return first\n\n\ndef generate_range(start=None, end=None, periods=None,\n offset=BDay(), time_rule=None):\n \"\"\"\n Generates a sequence of dates corresponding to the specified time\n offset. Similar to dateutil.rrule except uses pandas DateOffset\n objects to represent time increments\n\n Parameters\n ----------\n start : datetime (default None)\n end : datetime (default None)\n periods : int, optional\n time_rule : (legacy) name of DateOffset object to be used, optional\n Corresponds with names expected by tseries.frequencies.get_offset \n\n Note\n ----\n * This method is faster for generating weekdays than dateutil.rrule\n * At least two of (start, end, periods) must be specified.\n * If both start and end are specified, the returned dates will\n satisfy start <= date <= end.\n * If both time_rule and offset are specified, time_rule supersedes offset.\n\n Returns\n -------\n dates : generator object\n\n \"\"\"\n if time_rule is not None:\n from pandas.tseries.frequencies import get_offset\n offset = get_offset(time_rule)\n\n start = to_datetime(start)\n end = to_datetime(end)\n\n if start and not offset.onOffset(start):\n start = offset.rollforward(start)\n\n if end and not offset.onOffset(end):\n end = offset.rollback(end)\n\n if periods is None and end < start:\n end = None\n periods = 0\n\n if end is None:\n end = start + (periods - 1) * offset\n\n if start is None:\n start = end - (periods - 1) * offset\n\n cur = start\n\n next_date = cur\n while cur <= end:\n yield cur\n\n # faster than cur + offset\n next_date = offset.apply(cur)\n if next_date <= cur:\n raise ValueError('Offset %s did not increment date' % offset)\n cur = next_date\n",
"\"\"\"\nThis module is to support *bbox_inches* option in savefig command.\n\"\"\"\n\n\nimport warnings\nfrom matplotlib.transforms import Bbox, TransformedBbox, Affine2D\n\n\ndef adjust_bbox(fig, format, bbox_inches):\n \"\"\"\n Temporarily adjust the figure so that only the specified area\n (bbox_inches) is saved.\n\n It modifies fig.bbox, fig.bbox_inches,\n fig.transFigure._boxout, and fig.patch. While the figure size\n changes, the scale of the original figure is conserved. A\n function which restores the original values are returned.\n \"\"\"\n\n origBbox = fig.bbox\n origBboxInches = fig.bbox_inches\n _boxout = fig.transFigure._boxout\n\n asp_list = []\n locator_list = []\n for ax in fig.axes:\n pos = ax.get_position(original=False).frozen()\n locator_list.append(ax.get_axes_locator())\n asp_list.append(ax.get_aspect())\n\n def _l(a, r, pos=pos):\n return pos\n ax.set_axes_locator(_l)\n ax.set_aspect(\"auto\")\n\n def restore_bbox():\n\n for ax, asp, loc in zip(fig.axes, asp_list, locator_list):\n ax.set_aspect(asp)\n ax.set_axes_locator(loc)\n\n fig.bbox = origBbox\n fig.bbox_inches = origBboxInches\n fig.transFigure._boxout = _boxout\n fig.transFigure.invalidate()\n fig.patch.set_bounds(0, 0, 1, 1)\n\n adjust_bbox_handler = _adjust_bbox_handler_d.get(format)\n if adjust_bbox_handler is not None:\n adjust_bbox_handler(fig, bbox_inches)\n return restore_bbox\n else:\n warnings.warn(\"bbox_inches option for %s backend is not \"\n \"implemented yet.\" % (format))\n return None\n\n\ndef adjust_bbox_png(fig, bbox_inches):\n \"\"\"\n adjust_bbox for png (Agg) format\n \"\"\"\n\n tr = fig.dpi_scale_trans\n\n _bbox = TransformedBbox(bbox_inches,\n tr)\n x0, y0 = _bbox.x0, _bbox.y0\n fig.bbox_inches = Bbox.from_bounds(0, 0,\n bbox_inches.width,\n bbox_inches.height)\n\n x0, y0 = _bbox.x0, _bbox.y0\n w1, h1 = fig.bbox.width, fig.bbox.height\n fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0,\n w1, h1)\n fig.transFigure.invalidate()\n\n fig.bbox = TransformedBbox(fig.bbox_inches, tr)\n\n fig.patch.set_bounds(x0 / w1, y0 / h1,\n fig.bbox.width / w1, fig.bbox.height / h1)\n\n\ndef adjust_bbox_pdf(fig, bbox_inches):\n \"\"\"\n adjust_bbox for pdf & eps format\n \"\"\"\n\n if fig._cachedRenderer.__class__.__name__ == \"RendererPgf\":\n tr = Affine2D().scale(fig.dpi)\n f = 1.\n else:\n tr = Affine2D().scale(72)\n f = 72. / fig.dpi\n\n _bbox = TransformedBbox(bbox_inches, tr)\n\n fig.bbox_inches = Bbox.from_bounds(0, 0,\n bbox_inches.width,\n bbox_inches.height)\n x0, y0 = _bbox.x0, _bbox.y0\n w1, h1 = fig.bbox.width * f, fig.bbox.height * f\n fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0,\n w1, h1)\n fig.transFigure.invalidate()\n\n fig.bbox = TransformedBbox(fig.bbox_inches, tr)\n\n fig.patch.set_bounds(x0 / w1, y0 / h1,\n fig.bbox.width / w1, fig.bbox.height / h1)\n\n\ndef process_figure_for_rasterizing(figure,\n bbox_inches_restore, mode):\n\n \"\"\"\n This need to be called when figure dpi changes during the drawing\n (e.g., rasterizing). It recovers the bbox and re-adjust it with\n the new dpi.\n \"\"\"\n\n bbox_inches, restore_bbox = bbox_inches_restore\n restore_bbox()\n r = adjust_bbox(figure, mode,\n bbox_inches)\n\n return bbox_inches, r\n\n\n_adjust_bbox_handler_d = {}\nfor format in [\"png\", \"raw\", \"rgba\", \"jpg\", \"jpeg\", \"tiff\"]:\n _adjust_bbox_handler_d[format] = adjust_bbox_png\nfor format in [\"pdf\", \"eps\", \"svg\", \"svgz\"]:\n _adjust_bbox_handler_d[format] = adjust_bbox_pdf\n",
"# -*- coding: utf-8 -*-\n\"\"\"\n======\nRmagic\n======\n\nMagic command interface for interactive work with R via rpy2\n\nUsage\n=====\n\n``%R``\n\n{R_DOC}\n\n``%Rpush``\n\n{RPUSH_DOC}\n\n``%Rpull``\n\n{RPULL_DOC}\n\n``%Rget``\n\n{RGET_DOC}\n\n\"\"\"\n\n#-----------------------------------------------------------------------------\n# Copyright (C) 2012 The IPython Development Team\n#\n# Distributed under the terms of the BSD License. The full license is in\n# the file COPYING, distributed as part of this software.\n#-----------------------------------------------------------------------------\n\nimport sys\nimport tempfile\nfrom glob import glob\nfrom shutil import rmtree\nfrom getopt import getopt\n\n# numpy and rpy2 imports\n\nimport numpy as np\n\nimport rpy2.rinterface as ri\nimport rpy2.robjects as ro\nfrom rpy2.robjects.numpy2ri import numpy2ri\nro.conversion.py2ri = numpy2ri\n\n# IPython imports\n\nfrom IPython.core.displaypub import publish_display_data\nfrom IPython.core.magic import (Magics, magics_class, cell_magic, line_magic,\n line_cell_magic)\nfrom IPython.testing.skipdoctest import skip_doctest\nfrom IPython.core.magic_arguments import (\n argument, magic_arguments, parse_argstring\n)\nfrom IPython.utils.py3compat import str_to_unicode, unicode_to_str, PY3\n\nclass RInterpreterError(ri.RRuntimeError):\n \"\"\"An error when running R code in a %%R magic cell.\"\"\"\n def __init__(self, line, err, stdout):\n self.line = line\n self.err = err.rstrip()\n self.stdout = stdout.rstrip()\n \n def __unicode__(self):\n s = 'Failed to parse and evaluate line %r.\\nR error message: %r' % \\\n (self.line, self.err)\n if self.stdout and (self.stdout != self.err):\n s += '\\nR stdout:\\n' + self.stdout\n return s\n \n if PY3:\n __str__ = __unicode__\n else:\n def __str__(self):\n return unicode_to_str(str(self), 'utf-8')\n\ndef Rconverter(Robj, dataframe=False):\n \"\"\"\n Convert an object in R's namespace to one suitable\n for ipython's namespace.\n\n For a data.frame, it tries to return a structured array.\n It first checks for colnames, then names.\n If all are NULL, it returns np.asarray(Robj), else\n it tries to construct a recarray\n\n Parameters\n ----------\n\n Robj: an R object returned from rpy2\n \"\"\"\n is_data_frame = ro.r('is.data.frame')\n colnames = ro.r('colnames')\n rownames = ro.r('rownames') # with pandas, these could be used for the index\n names = ro.r('names')\n\n if dataframe:\n as_data_frame = ro.r('as.data.frame')\n cols = colnames(Robj)\n _names = names(Robj)\n if cols != ri.NULL:\n Robj = as_data_frame(Robj)\n names = tuple(np.array(cols))\n elif _names != ri.NULL:\n names = tuple(np.array(_names))\n else: # failed to find names\n return np.asarray(Robj)\n Robj = np.rec.fromarrays(Robj, names = names)\n return np.asarray(Robj)\n\n@magics_class\nclass RMagics(Magics):\n \"\"\"A set of magics useful for interactive work with R via rpy2.\n \"\"\"\n\n def __init__(self, shell, Rconverter=Rconverter,\n pyconverter=np.asarray,\n cache_display_data=False):\n \"\"\"\n Parameters\n ----------\n\n shell : IPython shell\n\n pyconverter : callable\n To be called on values in ipython namespace before \n assigning to variables in rpy2.\n\n cache_display_data : bool\n If True, the published results of the final call to R are \n cached in the variable 'display_cache'.\n\n \"\"\"\n super(RMagics, self).__init__(shell)\n self.cache_display_data = cache_display_data\n\n self.r = ro.R()\n\n self.Rstdout_cache = []\n self.pyconverter = pyconverter\n self.Rconverter = Rconverter\n\n def eval(self, line):\n '''\n Parse and evaluate a line with rpy2.\n Returns the output to R's stdout() connection\n and the value of eval(parse(line)).\n '''\n old_writeconsole = ri.get_writeconsole()\n ri.set_writeconsole(self.write_console)\n try:\n value = ri.baseenv['eval'](ri.parse(line))\n except (ri.RRuntimeError, ValueError) as exception:\n warning_or_other_msg = self.flush() # otherwise next return seems to have copy of error\n raise RInterpreterError(line, str_to_unicode(str(exception)), warning_or_other_msg)\n text_output = self.flush()\n ri.set_writeconsole(old_writeconsole)\n return text_output, value\n\n def write_console(self, output):\n '''\n A hook to capture R's stdout in a cache.\n '''\n self.Rstdout_cache.append(output)\n\n def flush(self):\n '''\n Flush R's stdout cache to a string, returning the string.\n '''\n value = ''.join([str_to_unicode(s, 'utf-8') for s in self.Rstdout_cache])\n self.Rstdout_cache = []\n return value\n\n @skip_doctest\n @line_magic\n def Rpush(self, line):\n '''\n A line-level magic for R that pushes\n variables from python to rpy2. The line should be made up\n of whitespace separated variable names in the IPython\n namespace::\n\n In [7]: import numpy as np\n\n In [8]: X = np.array([4.5,6.3,7.9])\n\n In [9]: X.mean()\n Out[9]: 6.2333333333333343\n\n In [10]: %Rpush X\n\n In [11]: %R mean(X)\n Out[11]: array([ 6.23333333])\n\n '''\n\n inputs = line.split(' ')\n for input in inputs:\n self.r.assign(input, self.pyconverter(self.shell.user_ns[input]))\n\n @skip_doctest\n @magic_arguments()\n @argument(\n '-d', '--as_dataframe', action='store_true',\n default=False,\n help='Convert objects to data.frames before returning to ipython.'\n )\n @argument(\n 'outputs',\n nargs='*',\n )\n @line_magic\n def Rpull(self, line):\n '''\n A line-level magic for R that pulls\n variables from python to rpy2::\n\n In [18]: _ = %R x = c(3,4,6.7); y = c(4,6,7); z = c('a',3,4)\n\n In [19]: %Rpull x y z\n\n In [20]: x\n Out[20]: array([ 3. , 4. , 6.7])\n\n In [21]: y\n Out[21]: array([ 4., 6., 7.])\n\n In [22]: z\n Out[22]:\n array(['a', '3', '4'],\n dtype='|S1')\n\n\n If --as_dataframe, then each object is returned as a structured array\n after first passed through \"as.data.frame\" in R before\n being calling self.Rconverter. \n This is useful when a structured array is desired as output, or\n when the object in R has mixed data types. \n See the %%R docstring for more examples.\n\n Notes\n -----\n\n Beware that R names can have '.' so this is not fool proof.\n To avoid this, don't name your R objects with '.'s...\n\n '''\n args = parse_argstring(self.Rpull, line)\n outputs = args.outputs\n for output in outputs:\n self.shell.push({output:self.Rconverter(self.r(output),dataframe=args.as_dataframe)})\n\n @skip_doctest\n @magic_arguments()\n @argument(\n '-d', '--as_dataframe', action='store_true',\n default=False,\n help='Convert objects to data.frames before returning to ipython.'\n )\n @argument(\n 'output',\n nargs=1,\n type=str,\n )\n @line_magic\n def Rget(self, line):\n '''\n Return an object from rpy2, possibly as a structured array (if possible).\n Similar to Rpull except only one argument is accepted and the value is \n returned rather than pushed to self.shell.user_ns::\n\n In [3]: dtype=[('x', '<i4'), ('y', '<f8'), ('z', '|S1')]\n\n In [4]: datapy = np.array([(1, 2.9, 'a'), (2, 3.5, 'b'), (3, 2.1, 'c'), (4, 5, 'e')], dtype=dtype)\n\n In [5]: %R -i datapy\n\n In [6]: %Rget datapy\n Out[6]: \n array([['1', '2', '3', '4'],\n ['2', '3', '2', '5'],\n ['a', 'b', 'c', 'e']], \n dtype='|S1')\n\n In [7]: %Rget -d datapy\n Out[7]: \n array([(1, 2.9, 'a'), (2, 3.5, 'b'), (3, 2.1, 'c'), (4, 5.0, 'e')], \n dtype=[('x', '<i4'), ('y', '<f8'), ('z', '|S1')])\n\n '''\n args = parse_argstring(self.Rget, line)\n output = args.output\n return self.Rconverter(self.r(output[0]),dataframe=args.as_dataframe)\n\n\n @skip_doctest\n @magic_arguments()\n @argument(\n '-i', '--input', action='append',\n help='Names of input variable from shell.user_ns to be assigned to R variables of the same names after calling self.pyconverter. Multiple names can be passed separated only by commas with no whitespace.'\n )\n @argument(\n '-o', '--output', action='append',\n help='Names of variables to be pushed from rpy2 to shell.user_ns after executing cell body and applying self.Rconverter. Multiple names can be passed separated only by commas with no whitespace.'\n )\n @argument(\n '-w', '--width', type=int,\n help='Width of png plotting device sent as an argument to *png* in R.'\n )\n @argument(\n '-h', '--height', type=int,\n help='Height of png plotting device sent as an argument to *png* in R.'\n )\n\n @argument(\n '-d', '--dataframe', action='append',\n help='Convert these objects to data.frames and return as structured arrays.'\n )\n @argument(\n '-u', '--units', type=int,\n help='Units of png plotting device sent as an argument to *png* in R. One of [\"px\", \"in\", \"cm\", \"mm\"].'\n )\n @argument(\n '-p', '--pointsize', type=int,\n help='Pointsize of png plotting device sent as an argument to *png* in R.'\n )\n @argument(\n '-b', '--bg',\n help='Background of png plotting device sent as an argument to *png* in R.'\n )\n @argument(\n '-n', '--noreturn',\n help='Force the magic to not return anything.',\n action='store_true',\n default=False\n )\n @argument(\n 'code',\n nargs='*',\n )\n @line_cell_magic\n def R(self, line, cell=None):\n '''\n Execute code in R, and pull some of the results back into the Python namespace.\n\n In line mode, this will evaluate an expression and convert the returned value to a Python object.\n The return value is determined by rpy2's behaviour of returning the result of evaluating the\n final line. \n\n Multiple R lines can be executed by joining them with semicolons::\n\n In [9]: %R X=c(1,4,5,7); sd(X); mean(X)\n Out[9]: array([ 4.25])\n\n As a cell, this will run a block of R code, without bringing anything back by default::\n\n In [10]: %%R\n ....: Y = c(2,4,3,9)\n ....: print(summary(lm(Y~X)))\n ....:\n\n Call:\n lm(formula = Y ~ X)\n\n Residuals:\n 1 2 3 4\n 0.88 -0.24 -2.28 1.64\n\n Coefficients:\n Estimate Std. Error t value Pr(>|t|)\n (Intercept) 0.0800 2.3000 0.035 0.975\n X 1.0400 0.4822 2.157 0.164\n\n Residual standard error: 2.088 on 2 degrees of freedom\n Multiple R-squared: 0.6993,Adjusted R-squared: 0.549\n F-statistic: 4.651 on 1 and 2 DF, p-value: 0.1638\n\n In the notebook, plots are published as the output of the cell.\n\n %R plot(X, Y)\n\n will create a scatter plot of X bs Y.\n\n If cell is not None and line has some R code, it is prepended to\n the R code in cell.\n\n Objects can be passed back and forth between rpy2 and python via the -i -o flags in line::\n\n In [14]: Z = np.array([1,4,5,10])\n\n In [15]: %R -i Z mean(Z)\n Out[15]: array([ 5.])\n\n\n In [16]: %R -o W W=Z*mean(Z)\n Out[16]: array([ 5., 20., 25., 50.])\n\n In [17]: W\n Out[17]: array([ 5., 20., 25., 50.])\n\n The return value is determined by these rules:\n\n * If the cell is not None, the magic returns None.\n\n * If the cell evaluates as False, the resulting value is returned\n unless the final line prints something to the console, in\n which case None is returned.\n\n * If the final line results in a NULL value when evaluated\n by rpy2, then None is returned.\n\n * No attempt is made to convert the final value to a structured array.\n Use the --dataframe flag or %Rget to push / return a structured array.\n\n * If the -n flag is present, there is no return value.\n\n * A trailing ';' will also result in no return value as the last\n value in the line is an empty string.\n\n The --dataframe argument will attempt to return structured arrays. \n This is useful for dataframes with\n mixed data types. Note also that for a data.frame, \n if it is returned as an ndarray, it is transposed::\n\n In [18]: dtype=[('x', '<i4'), ('y', '<f8'), ('z', '|S1')]\n\n In [19]: datapy = np.array([(1, 2.9, 'a'), (2, 3.5, 'b'), (3, 2.1, 'c'), (4, 5, 'e')], dtype=dtype)\n\n In [20]: %%R -o datar\n datar = datapy\n ....: \n\n In [21]: datar\n Out[21]: \n array([['1', '2', '3', '4'],\n ['2', '3', '2', '5'],\n ['a', 'b', 'c', 'e']], \n dtype='|S1')\n\n In [22]: %%R -d datar\n datar = datapy\n ....: \n\n In [23]: datar\n Out[23]: \n array([(1, 2.9, 'a'), (2, 3.5, 'b'), (3, 2.1, 'c'), (4, 5.0, 'e')], \n dtype=[('x', '<i4'), ('y', '<f8'), ('z', '|S1')])\n\n The --dataframe argument first tries colnames, then names.\n If both are NULL, it returns an ndarray (i.e. unstructured)::\n\n In [1]: %R mydata=c(4,6,8.3); NULL\n\n In [2]: %R -d mydata\n\n In [3]: mydata\n Out[3]: array([ 4. , 6. , 8.3])\n\n In [4]: %R names(mydata) = c('a','b','c'); NULL\n\n In [5]: %R -d mydata\n\n In [6]: mydata\n Out[6]: \n array((4.0, 6.0, 8.3), \n dtype=[('a', '<f8'), ('b', '<f8'), ('c', '<f8')])\n\n In [7]: %R -o mydata\n\n In [8]: mydata\n Out[8]: array([ 4. , 6. , 8.3])\n\n '''\n\n args = parse_argstring(self.R, line)\n\n # arguments 'code' in line are prepended to\n # the cell lines\n if not cell:\n code = ''\n return_output = True\n line_mode = True\n else:\n code = cell\n return_output = False\n line_mode = False\n\n code = ' '.join(args.code) + code\n\n if args.input:\n for input in ','.join(args.input).split(','):\n self.r.assign(input, self.pyconverter(self.shell.user_ns[input]))\n\n png_argdict = dict([(n, getattr(args, n)) for n in ['units', 'height', 'width', 'bg', 'pointsize']])\n png_args = ','.join(['%s=%s' % (o,v) for o, v in list(png_argdict.items()) if v is not None])\n # execute the R code in a temporary directory\n\n tmpd = tempfile.mkdtemp()\n self.r('png(\"%s/Rplots%%03d.png\",%s)' % (tmpd, png_args))\n\n text_output = ''\n if line_mode:\n for line in code.split(';'):\n text_result, result = self.eval(line)\n text_output += text_result\n if text_result:\n # the last line printed something to the console so we won't return it\n return_output = False\n else:\n text_result, result = self.eval(code)\n text_output += text_result\n\n self.r('dev.off()')\n\n # read out all the saved .png files\n\n images = [open(imgfile, 'rb').read() for imgfile in glob(\"%s/Rplots*png\" % tmpd)]\n\n # now publish the images\n # mimicking IPython/zmq/pylab/backend_inline.py\n fmt = 'png'\n mimetypes = { 'png' : 'image/png', 'svg' : 'image/svg+xml' }\n mime = mimetypes[fmt]\n\n # publish the printed R objects, if any\n\n display_data = []\n if text_output:\n display_data.append(('RMagic.R', {'text/plain':text_output}))\n\n # flush text streams before sending figures, helps a little with output\n for image in images:\n # synchronization in the console (though it's a bandaid, not a real sln)\n sys.stdout.flush(); sys.stderr.flush()\n display_data.append(('RMagic.R', {mime: image}))\n\n # kill the temporary directory\n rmtree(tmpd)\n\n # try to turn every output into a numpy array\n # this means that output are assumed to be castable\n # as numpy arrays\n\n if args.output:\n for output in ','.join(args.output).split(','):\n self.shell.push({output:self.Rconverter(self.r(output), dataframe=False)})\n\n if args.dataframe:\n for output in ','.join(args.dataframe).split(','):\n self.shell.push({output:self.Rconverter(self.r(output), dataframe=True)})\n\n for tag, disp_d in display_data:\n publish_display_data(tag, disp_d)\n\n # this will keep a reference to the display_data\n # which might be useful to other objects who happen to use\n # this method\n\n if self.cache_display_data:\n self.display_cache = display_data\n\n # if in line mode and return_output, return the result as an ndarray\n if return_output and not args.noreturn:\n if result != ri.NULL:\n return self.Rconverter(result, dataframe=False)\n\n__doc__ = __doc__.format(\n R_DOC = ' '*8 + RMagics.R.__doc__,\n RPUSH_DOC = ' '*8 + RMagics.Rpush.__doc__,\n RPULL_DOC = ' '*8 + RMagics.Rpull.__doc__,\n RGET_DOC = ' '*8 + RMagics.Rget.__doc__\n)\n\n\n_loaded = False\ndef load_ipython_extension(ip):\n \"\"\"Load the extension in IPython.\"\"\"\n global _loaded\n if not _loaded:\n ip.register_magics(RMagics)\n _loaded = True\n",
"\"\"\"\nC/Cython ascii file parser tests\n\"\"\"\n\nfrom pandas.util.py3compat import StringIO, BytesIO\nfrom datetime import datetime\nimport csv\nimport os\nimport sys\nimport re\nimport unittest\n\nimport nose\n\nfrom numpy import nan\nimport numpy as np\n\nfrom pandas import DataFrame, Series, Index, isnull, MultiIndex\nimport pandas.io.parsers as parsers\nfrom pandas.io.parsers import (read_csv, read_table, read_fwf,\n ExcelFile, TextParser)\nfrom pandas.util.testing import (assert_almost_equal, assert_frame_equal,\n assert_series_equal, network)\nimport pandas.lib as lib\nfrom pandas.util import py3compat\nfrom pandas.lib import Timestamp\n\nimport pandas.util.testing as tm\n\nfrom pandas._parser import TextReader\nimport pandas._parser as parser\n\n\nclass TestCParser(unittest.TestCase):\n\n def setUp(self):\n self.dirpath = tm.get_data_path('/')\n self.csv1 = os.path.join(self.dirpath, 'test1.csv')\n self.csv2 = os.path.join(self.dirpath, 'test2.csv')\n self.xls1 = os.path.join(self.dirpath, 'test.xls')\n\n def test_file_handle(self):\n try:\n f = open(self.csv1, 'rb')\n reader = TextReader(f)\n result = reader.read()\n finally:\n f.close()\n\n def test_string_filename(self):\n reader = TextReader(self.csv1, header=None)\n result = reader.read()\n\n def test_file_handle_mmap(self):\n try:\n f = open(self.csv1, 'rb')\n reader = TextReader(f, memory_map=True, header=None)\n result = reader.read()\n finally:\n f.close()\n\n def test_StringIO(self):\n text = open(self.csv1, 'rb').read()\n src = BytesIO(text)\n reader = TextReader(src, header=None)\n result = reader.read()\n\n def test_string_factorize(self):\n # should this be optional?\n data = 'a\\nb\\na\\nb\\na'\n reader = TextReader(StringIO(data), header=None)\n result = reader.read()\n self.assert_(len(set(map(id, result[0]))) == 2)\n\n def test_skipinitialspace(self):\n data = ('a, b\\n'\n 'a, b\\n'\n 'a, b\\n'\n 'a, b')\n\n reader = TextReader(StringIO(data), skipinitialspace=True,\n header=None)\n result = reader.read()\n\n self.assert_(np.array_equal(result[0], ['a', 'a', 'a', 'a']))\n self.assert_(np.array_equal(result[1], ['b', 'b', 'b', 'b']))\n\n def test_parse_booleans(self):\n data = 'True\\nFalse\\nTrue\\nTrue'\n\n reader = TextReader(StringIO(data), header=None)\n result = reader.read()\n\n self.assert_(result[0].dtype == np.bool_)\n\n def test_delimit_whitespace(self):\n data = 'a b\\na\\t\\t \"b\"\\n\"a\"\\t \\t b'\n\n reader = TextReader(StringIO(data), delim_whitespace=True,\n header=None)\n result = reader.read()\n\n self.assert_(np.array_equal(result[0], ['a', 'a', 'a']))\n self.assert_(np.array_equal(result[1], ['b', 'b', 'b']))\n\n def test_embedded_newline(self):\n data = 'a\\n\"hello\\nthere\"\\nthis'\n\n reader = TextReader(StringIO(data), header=None)\n result = reader.read()\n\n expected = ['a', 'hello\\nthere', 'this']\n self.assert_(np.array_equal(result[0], expected))\n\n def test_euro_decimal(self):\n data = '12345,67\\n345,678'\n\n reader = TextReader(StringIO(data), delimiter=':',\n decimal=',', header=None)\n result = reader.read()\n\n expected = [12345.67, 345.678]\n tm.assert_almost_equal(result[0], expected)\n\n def test_integer_thousands(self):\n data = '123,456\\n12,500'\n\n reader = TextReader(StringIO(data), delimiter=':',\n thousands=',', header=None)\n result = reader.read()\n\n expected = [123456, 12500]\n tm.assert_almost_equal(result[0], expected)\n\n def test_skip_bad_lines(self):\n # too many lines, see #2430 for why\n data = ('a:b:c\\n'\n 'd:e:f\\n'\n 'g:h:i\\n'\n 'j:k:l:m\\n'\n 'l:m:n\\n'\n 'o:p:q:r')\n\n reader = TextReader(StringIO(data), delimiter=':',\n header=None)\n self.assertRaises(parser.CParserError, reader.read)\n\n reader = TextReader(StringIO(data), delimiter=':',\n header=None,\n error_bad_lines=False,\n warn_bad_lines=False)\n result = reader.read()\n expected = {0: ['a', 'd', 'g', 'l'],\n 1: ['b', 'e', 'h', 'm'],\n 2: ['c', 'f', 'i', 'n']}\n assert_array_dicts_equal(result, expected)\n\n stderr = sys.stderr\n sys.stderr = StringIO()\n try:\n reader = TextReader(StringIO(data), delimiter=':',\n header=None,\n error_bad_lines=False,\n warn_bad_lines=True)\n reader.read()\n val = sys.stderr.getvalue()\n self.assertTrue('Skipping line 4' in val)\n self.assertTrue('Skipping line 6' in val)\n finally:\n sys.stderr = stderr\n\n def test_header_not_enough_lines(self):\n data = ('skip this\\n'\n 'skip this\\n'\n 'a,b,c\\n'\n '1,2,3\\n'\n '4,5,6')\n\n reader = TextReader(StringIO(data), delimiter=',', header=2,\n as_recarray=True)\n header = reader.header\n expected = ['a', 'b', 'c']\n self.assertEquals(header, expected)\n\n recs = reader.read()\n expected = {'a': [1, 4], 'b': [2, 5], 'c': [3, 6]}\n assert_array_dicts_equal(expected, recs)\n\n # not enough rows\n self.assertRaises(parser.CParserError, TextReader, StringIO(data),\n delimiter=',', header=5, as_recarray=True)\n\n def test_escapechar(self):\n data = ('\\\\\"hello world\\\"\\n'\n '\\\\\"hello world\\\"\\n'\n '\\\\\"hello world\\\"')\n\n reader = TextReader(StringIO(data), delimiter=',', header=None,\n escapechar='\\\\')\n result = reader.read()\n expected = {0: ['\"hello world\"'] * 3}\n assert_array_dicts_equal(result, expected)\n\n def test_eof_has_eol(self):\n # handling of new line at EOF\n pass\n\n def test_na_substitution(self):\n pass\n\n def test_numpy_string_dtype(self):\n data = \"\"\"\\\na,1\naa,2\naaa,3\naaaa,4\naaaaa,5\"\"\"\n\n def _make_reader(**kwds):\n return TextReader(StringIO(data), delimiter=',', header=None,\n **kwds)\n\n reader = _make_reader(dtype='S5,i4')\n result = reader.read()\n\n self.assert_(result[0].dtype == 'S5')\n\n ex_values = np.array(['a', 'aa', 'aaa', 'aaaa', 'aaaaa'], dtype='S5')\n self.assert_((result[0] == ex_values).all())\n self.assert_(result[1].dtype == 'i4')\n\n reader = _make_reader(dtype='S4')\n result = reader.read()\n self.assert_(result[0].dtype == 'S4')\n ex_values = np.array(['a', 'aa', 'aaa', 'aaaa', 'aaaa'], dtype='S4')\n self.assert_((result[0] == ex_values).all())\n self.assert_(result[1].dtype == 'S4')\n\n reader = _make_reader(dtype='S4', as_recarray=True)\n result = reader.read()\n self.assert_(result['0'].dtype == 'S4')\n ex_values = np.array(['a', 'aa', 'aaa', 'aaaa', 'aaaa'], dtype='S4')\n self.assert_((result['0'] == ex_values).all())\n self.assert_(result['1'].dtype == 'S4')\n\n def test_pass_dtype(self):\n data = \"\"\"\\\none,two\n1,a\n2,b\n3,c\n4,d\"\"\"\n\n def _make_reader(**kwds):\n return TextReader(StringIO(data), delimiter=',', **kwds)\n\n reader = _make_reader(dtype={'one': 'u1', 1: 'S1'})\n result = reader.read()\n self.assert_(result[0].dtype == 'u1')\n self.assert_(result[1].dtype == 'S1')\n\n reader = _make_reader(dtype={'one': np.uint8, 1: object})\n result = reader.read()\n self.assert_(result[0].dtype == 'u1')\n self.assert_(result[1].dtype == 'O')\n\n reader = _make_reader(dtype={'one': np.dtype('u1'),\n 1: np.dtype('O')})\n result = reader.read()\n self.assert_(result[0].dtype == 'u1')\n self.assert_(result[1].dtype == 'O')\n\n def test_usecols(self):\n data = \"\"\"\\\na,b,c\n1,2,3\n4,5,6\n7,8,9\n10,11,12\"\"\"\n\n def _make_reader(**kwds):\n return TextReader(StringIO(data), delimiter=',', **kwds)\n\n reader = _make_reader(usecols=(1, 2))\n result = reader.read()\n\n exp = _make_reader().read()\n self.assertEquals(len(result), 2)\n self.assertTrue((result[1] == exp[1]).all())\n self.assertTrue((result[2] == exp[2]).all())\n\n def test_cr_delimited(self):\n def _test(text, **kwargs):\n nice_text = text.replace('\\r', '\\r\\n')\n result = TextReader(StringIO(text), **kwargs).read()\n expected = TextReader(StringIO(nice_text), **kwargs).read()\n assert_array_dicts_equal(result, expected)\n\n data = 'a,b,c\\r1,2,3\\r4,5,6\\r7,8,9\\r10,11,12'\n _test(data, delimiter=',')\n\n data = 'a b c\\r1 2 3\\r4 5 6\\r7 8 9\\r10 11 12'\n _test(data, delim_whitespace=True)\n\n data = 'a,b,c\\r1,2,3\\r4,5,6\\r,88,9\\r10,11,12'\n _test(data, delimiter=',')\n\n sample = ('A,B,C,D,E,F,G,H,I,J,K,L,M,N,O\\r'\n 'AAAAA,BBBBB,0,0,0,0,0,0,0,0,0,0,0,0,0\\r'\n ',BBBBB,0,0,0,0,0,0,0,0,0,0,0,0,0')\n _test(sample, delimiter=',')\n\n data = 'A B C\\r 2 3\\r4 5 6'\n _test(data, delim_whitespace=True)\n\n def test_empty_field_eof(self):\n data = 'a,b,c\\n1,2,3\\n4,,'\n\n result = TextReader(StringIO(data), delimiter=',').read()\n\n expected = {0: np.array([1, 4]),\n 1: np.array(['2', ''], dtype=object),\n 2: np.array(['3', ''], dtype=object)}\n assert_array_dicts_equal(result, expected)\n\n\ndef assert_array_dicts_equal(left, right):\n for k, v in left.items():\n assert(np.array_equal(v, right[k]))\n\nif __name__ == '__main__':\n nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],\n exit=False)\n",
"#!/usr/bin/env python\n\"\"\"\nMatplotlib provides sophisticated date plotting capabilities, standing\non the shoulders of python :mod:`datetime`, the add-on modules\n:mod:`pytz` and :mod:`dateutils`. :class:`datetime` objects are\nconverted to floating point numbers which represent time in days\nsince 0001-01-01 UTC, plus 1. For example, 0001-01-01, 06:00 is\n1.25, not 0.25. The helper functions :func:`date2num`,\n:func:`num2date` and :func:`drange` are used to facilitate easy\nconversion to and from :mod:`datetime` and numeric ranges.\n\n.. note::\n Like Python's datetime, mpl uses the Gregorian calendar for\n all conversions between dates and floating point numbers.\n This practice is not universal, and calendar differences can\n cause confusing differences between what Python and mpl\n give as the number of days since 0001-01-01 and what other\n software and databases yield. For example, the\n `US Naval Observatory <http://www.usno.navy.mil/USNO/astronomical-applications/data-services/jul-date>`_\n uses a calendar that switches from Julian to Gregorian in\n October, 1582. Hence, using their calculator, the number of\n days between 0001-01-01 and 2006-04-01 is 732403, whereas using\n the Gregorian calendar via the datetime module we find::\n\n In [31]:date(2006,4,1).toordinal() - date(1,1,1).toordinal()\n Out[31]:732401\n\n\nA wide range of specific and general purpose date tick locators and\nformatters are provided in this module. See\n:mod:`matplotlib.ticker` for general information on tick locators\nand formatters. These are described below.\n\nAll the matplotlib date converters, tickers and formatters are\ntimezone aware, and the default timezone is given by the timezone\nparameter in your :file:`matplotlibrc` file. If you leave out a\n:class:`tz` timezone instance, the default from your rc file will be\nassumed. If you want to use a custom time zone, pass a\n:class:`pytz.timezone` instance with the tz keyword argument to\n:func:`num2date`, :func:`plot_date`, and any custom date tickers or\nlocators you create. See `pytz <http://pytz.sourceforge.net>`_ for\ninformation on :mod:`pytz` and timezone handling.\n\nThe `dateutil module <http://labix.org/python-dateutil>`_ provides\nadditional code to handle date ticking, making it easy to place ticks\non any kinds of dates. See examples below.\n\nDate tickers\n------------\n\nMost of the date tickers can locate single or multiple values. For\nexample::\n\n # tick on mondays every week\n loc = WeekdayLocator(byweekday=MO, tz=tz)\n\n # tick on mondays and saturdays\n loc = WeekdayLocator(byweekday=(MO, SA))\n\nIn addition, most of the constructors take an interval argument::\n\n # tick on mondays every second week\n loc = WeekdayLocator(byweekday=MO, interval=2)\n\nThe rrule locator allows completely general date ticking::\n\n # tick every 5th easter\n rule = rrulewrapper(YEARLY, byeaster=1, interval=5)\n loc = RRuleLocator(rule)\n\nHere are all the date tickers:\n\n * :class:`MinuteLocator`: locate minutes\n\n * :class:`HourLocator`: locate hours\n\n * :class:`DayLocator`: locate specifed days of the month\n\n * :class:`WeekdayLocator`: Locate days of the week, eg MO, TU\n\n * :class:`MonthLocator`: locate months, eg 7 for july\n\n * :class:`YearLocator`: locate years that are multiples of base\n\n * :class:`RRuleLocator`: locate using a\n :class:`matplotlib.dates.rrulewrapper`. The\n :class:`rrulewrapper` is a simple wrapper around a\n :class:`dateutils.rrule` (`dateutil\n <http://labix.org/python-dateutil>`_) which allow almost\n arbitrary date tick specifications. See `rrule example\n <../examples/pylab_examples/date_demo_rrule.html>`_.\n\n * :class:`AutoDateLocator`: On autoscale, this class picks the best\n :class:`MultipleDateLocator` to set the view limits and the tick\n locations.\n\nDate formatters\n---------------\n\nHere all all the date formatters:\n\n * :class:`AutoDateFormatter`: attempts to figure out the best format\n to use. This is most useful when used with the :class:`AutoDateLocator`.\n\n * :class:`DateFormatter`: use :func:`strftime` format strings\n\n * :class:`IndexDateFormatter`: date plots with implicit *x*\n indexing.\n\"\"\"\n\n\nimport re, time, math, datetime\n\n\nimport matplotlib\nimport numpy as np\n\nimport matplotlib.units as units\nimport matplotlib.cbook as cbook\nimport matplotlib.ticker as ticker\n\nfrom dateutil.rrule import rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY, \\\n MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY\nfrom dateutil.relativedelta import relativedelta\nimport dateutil.parser\n\n\n__all__ = ( 'date2num', 'num2date', 'drange', 'epoch2num',\n 'num2epoch', 'mx2num', 'DateFormatter',\n 'IndexDateFormatter', 'AutoDateFormatter', 'DateLocator',\n 'RRuleLocator', 'AutoDateLocator', 'YearLocator',\n 'MonthLocator', 'WeekdayLocator',\n 'DayLocator', 'HourLocator', 'MinuteLocator',\n 'SecondLocator', 'rrule', 'MO', 'TU', 'WE', 'TH', 'FR',\n 'SA', 'SU', 'YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY',\n 'HOURLY', 'MINUTELY', 'SECONDLY', 'relativedelta',\n 'seconds', 'minutes', 'hours', 'weeks')\n\n\n# Make a simple UTC instance so we don't always have to import\n# pytz. From the python datetime library docs:\n\nclass _UTC(datetime.tzinfo):\n \"\"\"UTC\"\"\"\n\n def utcoffset(self, dt):\n return datetime.timedelta(0)\n\n def tzname(self, dt):\n return \"UTC\"\n\n def dst(self, dt):\n return datetime.timedelta(0)\n\nUTC = _UTC()\n\ndef _get_rc_timezone():\n s = matplotlib.rcParams['timezone']\n if s == 'UTC':\n return UTC\n import pytz\n return pytz.timezone(s)\n\n\nHOURS_PER_DAY = 24.\nMINUTES_PER_DAY = 60.*HOURS_PER_DAY\nSECONDS_PER_DAY = 60.*MINUTES_PER_DAY\nMUSECONDS_PER_DAY = 1e6*SECONDS_PER_DAY\nSEC_PER_MIN = 60\nSEC_PER_HOUR = 3600\nSEC_PER_DAY = SEC_PER_HOUR * 24\nSEC_PER_WEEK = SEC_PER_DAY * 7\nMONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = (\n MO, TU, WE, TH, FR, SA, SU)\nWEEKDAYS = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)\n\n\n\n\ndef _to_ordinalf(dt):\n \"\"\"\n Convert :mod:`datetime` to the Gregorian date as UTC float days,\n preserving hours, minutes, seconds and microseconds. Return value\n is a :func:`float`.\n \"\"\"\n\n if hasattr(dt, 'tzinfo') and dt.tzinfo is not None:\n delta = dt.tzinfo.utcoffset(dt)\n if delta is not None:\n dt -= delta\n\n base = float(dt.toordinal())\n if hasattr(dt, 'hour'):\n base += (dt.hour/HOURS_PER_DAY + dt.minute/MINUTES_PER_DAY +\n dt.second/SECONDS_PER_DAY + dt.microsecond/MUSECONDS_PER_DAY\n )\n return base\n\ndef _from_ordinalf(x, tz=None):\n \"\"\"\n Convert Gregorian float of the date, preserving hours, minutes,\n seconds and microseconds. Return value is a :class:`datetime`.\n \"\"\"\n if tz is None: tz = _get_rc_timezone()\n ix = int(x)\n dt = datetime.datetime.fromordinal(ix)\n remainder = float(x) - ix\n hour, remainder = divmod(24*remainder, 1)\n minute, remainder = divmod(60*remainder, 1)\n second, remainder = divmod(60*remainder, 1)\n microsecond = int(1e6*remainder)\n if microsecond<10: microsecond=0 # compensate for rounding errors\n dt = datetime.datetime(\n dt.year, dt.month, dt.day, int(hour), int(minute), int(second),\n microsecond, tzinfo=UTC).astimezone(tz)\n\n if microsecond>999990: # compensate for rounding errors\n dt += datetime.timedelta(microseconds=1e6-microsecond)\n\n return dt\n\nclass strpdate2num:\n \"\"\"\n Use this class to parse date strings to matplotlib datenums when\n you know the date format string of the date you are parsing. See\n :file:`examples/load_demo.py`.\n \"\"\"\n def __init__(self, fmt):\n \"\"\" fmt: any valid strptime format is supported \"\"\"\n self.fmt = fmt\n\n def __call__(self, s):\n \"\"\"s : string to be converted\n return value: a date2num float\n \"\"\"\n return date2num(datetime.datetime(*time.strptime(s, self.fmt)[:6]))\n\ndef datestr2num(d):\n \"\"\"\n Convert a date string to a datenum using\n :func:`dateutil.parser.parse`. *d* can be a single string or a\n sequence of strings.\n \"\"\"\n if cbook.is_string_like(d):\n dt = dateutil.parser.parse(d)\n return date2num(dt)\n else:\n return date2num([dateutil.parser.parse(s) for s in d])\n\n\ndef date2num(d):\n \"\"\"\n *d* is either a :class:`datetime` instance or a sequence of datetimes.\n\n Return value is a floating point number (or sequence of floats)\n which gives the number of days (fraction part represents hours,\n minutes, seconds) since 0001-01-01 00:00:00 UTC, *plus* *one*.\n The addition of one here is a historical artifact. Also, note\n that the Gregorian calendar is assumed; this is not universal\n practice. For details, see the module docstring.\n \"\"\"\n if not cbook.iterable(d): return _to_ordinalf(d)\n else: return np.asarray([_to_ordinalf(val) for val in d])\n\n\ndef julian2num(j):\n 'Convert a Julian date (or sequence) to a matplotlib date (or sequence).'\n if cbook.iterable(j): j = np.asarray(j)\n return j - 1721424.5\n\ndef num2julian(n):\n 'Convert a matplotlib date (or sequence) to a Julian date (or sequence).'\n if cbook.iterable(n): n = np.asarray(n)\n return n + 1721424.5\n\ndef num2date(x, tz=None):\n \"\"\"\n *x* is a float value which gives the number of days\n (fraction part represents hours, minutes, seconds) since\n 0001-01-01 00:00:00 UTC *plus* *one*.\n The addition of one here is a historical artifact. Also, note\n that the Gregorian calendar is assumed; this is not universal\n practice. For details, see the module docstring.\n\n Return value is a :class:`datetime` instance in timezone *tz* (default to\n rcparams TZ value).\n\n If *x* is a sequence, a sequence of :class:`datetime` objects will\n be returned.\n \"\"\"\n if tz is None: tz = _get_rc_timezone()\n if not cbook.iterable(x): return _from_ordinalf(x, tz)\n else: return [_from_ordinalf(val, tz) for val in x]\n\ndef drange(dstart, dend, delta):\n \"\"\"\n Return a date range as float Gregorian ordinals. *dstart* and\n *dend* are :class:`datetime` instances. *delta* is a\n :class:`datetime.timedelta` instance.\n \"\"\"\n step = (delta.days + delta.seconds/SECONDS_PER_DAY +\n delta.microseconds/MUSECONDS_PER_DAY)\n f1 = _to_ordinalf(dstart)\n f2 = _to_ordinalf(dend)\n\n num = int(np.ceil((f2-f1)/step)) #calculate the difference between dend and dstart in times of delta\n dinterval_end = dstart + num*delta #calculate end of the interval which will be generated\n if dinterval_end >= dend: #ensure, that an half open interval will be generated [dstart, dend)\n dinterval_end -= delta #if the endpoint is greated than dend, just subtract one delta\n num -= 1\n\n f2 = _to_ordinalf(dinterval_end) #new float-endpoint\n return np.linspace(f1, f2, num+1)\n\n### date tickers and formatters ###\n\n\n\nclass DateFormatter(ticker.Formatter):\n \"\"\"\n Tick location is seconds since the epoch. Use a :func:`strftime`\n format string.\n\n Python only supports :mod:`datetime` :func:`strftime` formatting\n for years greater than 1900. Thanks to Andrew Dalke, Dalke\n Scientific Software who contributed the :func:`strftime` code\n below to include dates earlier than this year.\n \"\"\"\n\n illegal_s = re.compile(r\"((^|[^%])(%%)*%s)\")\n\n def __init__(self, fmt, tz=None):\n \"\"\"\n *fmt* is an :func:`strftime` format string; *tz* is the\n :class:`tzinfo` instance.\n \"\"\"\n if tz is None: tz = _get_rc_timezone()\n self.fmt = fmt\n self.tz = tz\n\n def __call__(self, x, pos=0):\n if x==0:\n raise ValueError('DateFormatter found a value of x=0, which is an illegal date. This usually occurs because you have not informed the axis that it is plotting dates, eg with ax.xaxis_date()')\n dt = num2date(x, self.tz)\n return self.strftime(dt, self.fmt)\n\n def set_tzinfo(self, tz):\n self.tz = tz\n\n def _findall(self, text, substr):\n # Also finds overlaps\n sites = []\n i = 0\n while 1:\n j = text.find(substr, i)\n if j == -1:\n break\n sites.append(j)\n i=j+1\n return sites\n\n # Dalke: I hope I did this math right. Every 28 years the\n # calendar repeats, except through century leap years excepting\n # the 400 year leap years. But only if you're using the Gregorian\n # calendar.\n\n def strftime(self, dt, fmt):\n fmt = self.illegal_s.sub(r\"\\1\", fmt)\n fmt = fmt.replace(\"%s\", \"s\")\n if dt.year > 1900:\n return cbook.unicode_safe(dt.strftime(fmt))\n\n year = dt.year\n # For every non-leap year century, advance by\n # 6 years to get into the 28-year repeat cycle\n delta = 2000 - year\n off = 6*(delta // 100 + delta // 400)\n year = year + off\n\n # Move to around the year 2000\n year = year + ((2000 - year)//28)*28\n timetuple = dt.timetuple()\n s1 = time.strftime(fmt, (year,) + timetuple[1:])\n sites1 = self._findall(s1, str(year))\n\n s2 = time.strftime(fmt, (year+28,) + timetuple[1:])\n sites2 = self._findall(s2, str(year+28))\n\n sites = []\n for site in sites1:\n if site in sites2:\n sites.append(site)\n\n s = s1\n syear = \"%4d\" % (dt.year,)\n for site in sites:\n s = s[:site] + syear + s[site+4:]\n\n return cbook.unicode_safe(s)\n\n\n\nclass IndexDateFormatter(ticker.Formatter):\n \"\"\"\n Use with :class:`~matplotlib.ticker.IndexLocator` to cycle format\n strings by index.\n \"\"\"\n def __init__(self, t, fmt, tz=None):\n \"\"\"\n *t* is a sequence of dates (floating point days). *fmt* is a\n :func:`strftime` format string.\n \"\"\"\n if tz is None: tz = _get_rc_timezone()\n self.t = t\n self.fmt = fmt\n self.tz = tz\n\n def __call__(self, x, pos=0):\n 'Return the label for time *x* at position *pos*'\n ind = int(round(x))\n if ind>=len(self.t) or ind<=0: return ''\n\n dt = num2date(self.t[ind], self.tz)\n\n return cbook.unicode_safe(dt.strftime(self.fmt))\n\n\nclass AutoDateFormatter(ticker.Formatter):\n \"\"\"\n This class attempts to figure out the best format to use. This is\n most useful when used with the :class:`AutoDateLocator`.\n\n\n The AutoDateFormatter has a scale dictionary that maps the scale\n of the tick (the distance in days between one major tick) and a\n format string. The default looks like this::\n\n self.scaled = {\n 365.0 : '%Y',\n 30. : '%b %Y',\n 1.0 : '%b %d %Y',\n 1./24. : '%H:%M:%D',\n }\n\n\n The algorithm picks the key in the dictionary that is >= the\n current scale and uses that format string. You can customize this\n dictionary by doing::\n\n\n formatter = AutoDateFormatter()\n formatter.scaled[1/(24.*60.)] = '%M:%S' # only show min and sec\n\n \"\"\"\n\n # This can be improved by providing some user-level direction on\n # how to choose the best format (precedence, etc...)\n\n # Perhaps a 'struct' that has a field for each time-type where a\n # zero would indicate \"don't show\" and a number would indicate\n # \"show\" with some sort of priority. Same priorities could mean\n # show all with the same priority.\n\n # Or more simply, perhaps just a format string for each\n # possibility...\n\n def __init__(self, locator, tz=None, defaultfmt='%Y-%m-%d'):\n \"\"\"\n Autofmt the date labels. The default format is the one to use\n if none of the times in scaled match\n \"\"\"\n self._locator = locator\n self._tz = tz\n self.defaultfmt = defaultfmt\n self._formatter = DateFormatter(self.defaultfmt, tz)\n self.scaled = {\n 365.0 : '%Y',\n 30. : '%b %Y',\n 1.0 : '%b %d %Y',\n 1./24. : '%H:%M:%S',\n }\n\n def __call__(self, x, pos=0):\n\n scale = float( self._locator._get_unit() )\n\n fmt = self.defaultfmt\n\n for k in sorted(self.scaled):\n if k>=scale:\n fmt = self.scaled[k]\n break\n\n self._formatter = DateFormatter(fmt, self._tz)\n return self._formatter(x, pos)\n\n\n\nclass rrulewrapper:\n\n def __init__(self, freq, **kwargs):\n self._construct = kwargs.copy()\n self._construct[\"freq\"] = freq\n self._rrule = rrule(**self._construct)\n\n def set(self, **kwargs):\n self._construct.update(kwargs)\n self._rrule = rrule(**self._construct)\n\n def __getattr__(self, name):\n if name in self.__dict__:\n return self.__dict__[name]\n return getattr(self._rrule, name)\n\nclass DateLocator(ticker.Locator):\n hms0d = {'byhour':0, 'byminute':0,'bysecond':0}\n def __init__(self, tz=None):\n \"\"\"\n *tz* is a :class:`tzinfo` instance.\n \"\"\"\n if tz is None: tz = _get_rc_timezone()\n self.tz = tz\n\n def set_tzinfo(self, tz):\n self.tz = tz\n\n def datalim_to_dt(self):\n dmin, dmax = self.axis.get_data_interval()\n return num2date(dmin, self.tz), num2date(dmax, self.tz)\n\n def viewlim_to_dt(self):\n vmin, vmax = self.axis.get_view_interval()\n return num2date(vmin, self.tz), num2date(vmax, self.tz)\n\n def _get_unit(self):\n \"\"\"\n Return how many days a unit of the locator is; used for\n intelligent autoscaling.\n \"\"\"\n return 1\n\n def _get_interval(self):\n \"\"\"\n Return the number of units for each tick.\n \"\"\"\n return 1\n\n def nonsingular(self, vmin, vmax):\n unit = self._get_unit()\n interval = self._get_interval()\n if abs(vmax - vmin) < 1e-6:\n vmin -= 2*unit*interval\n vmax += 2*unit*interval\n return vmin, vmax\n\nclass RRuleLocator(DateLocator):\n # use the dateutil rrule instance\n\n def __init__(self, o, tz=None):\n DateLocator.__init__(self, tz)\n self.rule = o\n\n def __call__(self):\n # if no data have been set, this will tank with a ValueError\n try: dmin, dmax = self.viewlim_to_dt()\n except ValueError: return []\n\n if dmin>dmax:\n dmax, dmin = dmin, dmax\n delta = relativedelta(dmax, dmin)\n\n # We need to cap at the endpoints of valid datetime\n try:\n start = dmin - delta\n except ValueError:\n start = _from_ordinalf( 1.0 )\n\n try:\n stop = dmax + delta\n except ValueError:\n # The magic number!\n stop = _from_ordinalf( 3652059.9999999 )\n\n self.rule.set(dtstart=start, until=stop, count=self.MAXTICKS + 1)\n\n # estimate the number of ticks very approximately so we don't\n # have to do a very expensive (and potentially near infinite)\n # 'between' calculation, only to find out it will fail.\n nmax, nmin = date2num((dmax, dmin))\n estimate = (nmax - nmin) / (self._get_unit() * self._get_interval())\n # This estimate is only an estimate, so be really conservative\n # about bailing...\n if estimate > self.MAXTICKS * 2:\n raise RuntimeError(\n 'RRuleLocator estimated to generate %d ticks from %s to %s: exceeds Locator.MAXTICKS * 2 (%d) ' % (estimate, dmin, dmax, self.MAXTICKS * 2))\n\n dates = self.rule.between(dmin, dmax, True)\n if len(dates) == 0:\n return date2num([dmin, dmax])\n return self.raise_if_exceeds(date2num(dates))\n\n def _get_unit(self):\n \"\"\"\n Return how many days a unit of the locator is; used for\n intelligent autoscaling.\n \"\"\"\n freq = self.rule._rrule._freq\n return self.get_unit_generic(freq)\n\n def get_unit_generic(freq):\n if ( freq == YEARLY ):\n return 365.0\n elif ( freq == MONTHLY ):\n return 30.0\n elif ( freq == WEEKLY ):\n return 7.0\n elif ( freq == DAILY ):\n return 1.0\n elif ( freq == HOURLY ):\n return (1.0/24.0)\n elif ( freq == MINUTELY ):\n return (1.0/(24*60))\n elif ( freq == SECONDLY ):\n return (1.0/(24*3600))\n else:\n # error\n return -1 #or should this just return '1'?\n get_unit_generic = staticmethod(get_unit_generic)\n\n def _get_interval(self):\n return self.rule._rrule._interval\n\n def autoscale(self):\n \"\"\"\n Set the view limits to include the data range.\n \"\"\"\n dmin, dmax = self.datalim_to_dt()\n if dmin>dmax:\n dmax, dmin = dmin, dmax\n\n delta = relativedelta(dmax, dmin)\n\n # We need to cap at the endpoints of valid datetime\n try:\n start = dmin - delta\n except ValueError:\n start = _from_ordinalf( 1.0 )\n\n try:\n stop = dmax + delta\n except ValueError:\n # The magic number!\n stop = _from_ordinalf( 3652059.9999999 )\n\n self.rule.set(dtstart=start, until=stop)\n dmin, dmax = self.datalim_to_dt()\n\n\n vmin = self.rule.before(dmin, True)\n if not vmin: vmin=dmin\n\n vmax = self.rule.after(dmax, True)\n if not vmax: vmax=dmax\n\n vmin = date2num(vmin)\n vmax = date2num(vmax)\n\n return self.nonsingular(vmin, vmax)\n\n\nclass AutoDateLocator(DateLocator):\n \"\"\"\n On autoscale, this class picks the best\n :class:`MultipleDateLocator` to set the view limits and the tick\n locations.\n \"\"\"\n def __init__(self, tz=None, minticks=5, maxticks=None,\n interval_multiples=False):\n \"\"\"\n *minticks* is the minimum number of ticks desired, which is used to\n select the type of ticking (yearly, monthly, etc.).\n\n *maxticks* is the maximum number of ticks desired, which controls\n any interval between ticks (ticking every other, every 3, etc.).\n For really fine-grained control, this can be a dictionary mapping\n individual rrule frequency constants (YEARLY, MONTHLY, etc.)\n to their own maximum number of ticks. This can be used to keep\n the number of ticks appropriate to the format chosen in\n class:`AutoDateFormatter`. Any frequency not specified in this\n dictionary is given a default value.\n\n *tz* is a :class:`tzinfo` instance.\n\n *interval_multiples* is a boolean that indicates whether ticks\n should be chosen to be multiple of the interval. This will lock\n ticks to 'nicer' locations. For example, this will force the\n ticks to be at hours 0,6,12,18 when hourly ticking is done at\n 6 hour intervals.\n\n The AutoDateLocator has an interval dictionary that maps the\n frequency of the tick (a constant from dateutil.rrule) and a\n multiple allowed for that ticking. The default looks like this::\n\n self.intervald = {\n YEARLY : [1, 2, 4, 5, 10],\n MONTHLY : [1, 2, 3, 4, 6],\n DAILY : [1, 2, 3, 7, 14],\n HOURLY : [1, 2, 3, 4, 6, 12],\n MINUTELY: [1, 5, 10, 15, 30],\n SECONDLY: [1, 5, 10, 15, 30]\n }\n\n The interval is used to specify multiples that are appropriate for\n the frequency of ticking. For instance, every 7 days is sensible\n for daily ticks, but for minutes/seconds, 15 or 30 make sense.\n You can customize this dictionary by doing::\n\n locator = AutoDateLocator()\n locator.intervald[HOURLY] = [3] # only show every 3 hours\n \"\"\"\n DateLocator.__init__(self, tz)\n self._locator = YearLocator()\n self._freq = YEARLY\n self._freqs = [YEARLY, MONTHLY, DAILY, HOURLY, MINUTELY, SECONDLY]\n self.minticks = minticks\n\n self.maxticks = {YEARLY : 16, MONTHLY : 12, DAILY : 11, HOURLY : 16,\n MINUTELY : 11, SECONDLY : 11}\n if maxticks is not None:\n try:\n self.maxticks.update(maxticks)\n except TypeError:\n # Assume we were given an integer. Use this as the maximum\n # number of ticks for every frequency and create a\n # dictionary for this\n self.maxticks = dict(zip(self._freqs,\n [maxticks]*len(self._freqs)))\n self.interval_multiples = interval_multiples\n self.intervald = {\n YEARLY : [1, 2, 4, 5, 10],\n MONTHLY : [1, 2, 3, 4, 6],\n DAILY : [1, 2, 3, 7, 14],\n HOURLY : [1, 2, 3, 4, 6, 12],\n MINUTELY: [1, 5, 10, 15, 30],\n SECONDLY: [1, 5, 10, 15, 30]\n }\n self._byranges = [None, list(range(1, 13)), list(range(1, 32)), list(range(0, 24)),\n list(range(0, 60)), list(range(0, 60))]\n\n def __call__(self):\n 'Return the locations of the ticks'\n self.refresh()\n return self._locator()\n\n def set_axis(self, axis):\n DateLocator.set_axis(self, axis)\n self._locator.set_axis(axis)\n\n def refresh(self):\n 'Refresh internal information based on current limits.'\n dmin, dmax = self.viewlim_to_dt()\n self._locator = self.get_locator(dmin, dmax)\n\n def _get_unit(self):\n return RRuleLocator.get_unit_generic(self._freq)\n\n def autoscale(self):\n 'Try to choose the view limits intelligently.'\n dmin, dmax = self.datalim_to_dt()\n self._locator = self.get_locator(dmin, dmax)\n return self._locator.autoscale()\n\n def get_locator(self, dmin, dmax):\n 'Pick the best locator based on a distance.'\n\n delta = relativedelta(dmax, dmin)\n\n numYears = (delta.years * 1.0)\n numMonths = (numYears * 12.0) + delta.months\n numDays = (numMonths * 31.0) + delta.days\n numHours = (numDays * 24.0) + delta.hours\n numMinutes = (numHours * 60.0) + delta.minutes\n numSeconds = (numMinutes * 60.0) + delta.seconds\n\n nums = [numYears, numMonths, numDays, numHours, numMinutes, numSeconds]\n\n # Default setting of bymonth, etc. to pass to rrule\n # [unused (for year), bymonth, bymonthday, byhour, byminute, bysecond]\n byranges = [None, 1, 1, 0, 0, 0]\n\n # Loop over all the frequencies and try to find one that gives at\n # least a minticks tick positions. Once this is found, look for\n # an interval from an list specific to that frequency that gives no\n # more than maxticks tick positions. Also, set up some ranges\n # (bymonth, etc.) as appropriate to be passed to rrulewrapper.\n for i, (freq, num) in enumerate(zip(self._freqs, nums)):\n # If this particular frequency doesn't give enough ticks, continue\n if num < self.minticks:\n # Since we're not using this particular frequency, set\n # the corresponding by_ to None so the rrule can act as\n # appropriate\n byranges[i] = None\n continue\n\n # Find the first available interval that doesn't give too many ticks\n for interval in self.intervald[freq]:\n if num <= interval * (self.maxticks[freq] - 1):\n break\n else:\n # We went through the whole loop without breaking, default to 1\n interval = 1\n\n # Set some parameters as appropriate\n self._freq = freq\n\n if self._byranges[i] and self.interval_multiples:\n byranges[i] = self._byranges[i][::interval]\n interval = 1\n else:\n byranges[i] = self._byranges[i]\n\n # We found what frequency to use\n break\n else:\n # We couldn't find a good frequency.\n # do what?\n # microseconds as floats, but floats from what reference point?\n byranges = [None, 1, 1, 0, 0, 0]\n interval = 1\n\n unused, bymonth, bymonthday, byhour, byminute, bysecond = byranges\n del unused\n\n rrule = rrulewrapper( self._freq, interval=interval,\n dtstart=dmin, until=dmax,\n bymonth=bymonth, bymonthday=bymonthday,\n byhour=byhour, byminute = byminute,\n bysecond=bysecond )\n\n locator = RRuleLocator(rrule, self.tz)\n locator.set_axis(self.axis)\n\n locator.set_view_interval(*self.axis.get_view_interval())\n locator.set_data_interval(*self.axis.get_data_interval())\n return locator\n\n\nclass YearLocator(DateLocator):\n \"\"\"\n Make ticks on a given day of each year that is a multiple of base.\n\n Examples::\n\n # Tick every year on Jan 1st\n locator = YearLocator()\n\n # Tick every 5 years on July 4th\n locator = YearLocator(5, month=7, day=4)\n \"\"\"\n def __init__(self, base=1, month=1, day=1, tz=None):\n \"\"\"\n Mark years that are multiple of base on a given month and day\n (default jan 1).\n \"\"\"\n DateLocator.__init__(self, tz)\n self.base = ticker.Base(base)\n self.replaced = { 'month' : month,\n 'day' : day,\n 'hour' : 0,\n 'minute' : 0,\n 'second' : 0,\n 'tzinfo' : tz\n }\n\n def __call__(self):\n dmin, dmax = self.viewlim_to_dt()\n ymin = self.base.le(dmin.year)\n ymax = self.base.ge(dmax.year)\n\n\n ticks = [dmin.replace(year=ymin, **self.replaced)]\n while 1:\n dt = ticks[-1]\n if dt.year>=ymax: return date2num(ticks)\n year = dt.year + self.base.get_base()\n ticks.append(dt.replace(year=year, **self.replaced))\n\n def autoscale(self):\n \"\"\"\n Set the view limits to include the data range.\n \"\"\"\n dmin, dmax = self.datalim_to_dt()\n\n ymin = self.base.le(dmin.year)\n ymax = self.base.ge(dmax.year)\n vmin = dmin.replace(year=ymin, **self.replaced)\n vmax = dmax.replace(year=ymax, **self.replaced)\n\n vmin = date2num(vmin)\n vmax = date2num(vmax)\n return self.nonsingular(vmin, vmax)\n\n\nclass MonthLocator(RRuleLocator):\n \"\"\"\n Make ticks on occurances of each month month, eg 1, 3, 12.\n \"\"\"\n def __init__(self, bymonth=None, bymonthday=1, interval=1, tz=None):\n \"\"\"\n Mark every month in *bymonth*; *bymonth* can be an int or\n sequence. Default is ``range(1,13)``, i.e. every month.\n\n *interval* is the interval between each iteration. For\n example, if ``interval=2``, mark every second occurance.\n \"\"\"\n if bymonth is None: bymonth=list(range(1,13))\n o = rrulewrapper(MONTHLY, bymonth=bymonth, bymonthday=bymonthday,\n interval=interval, **self.hms0d)\n RRuleLocator.__init__(self, o, tz)\n\n\nclass WeekdayLocator(RRuleLocator):\n \"\"\"\n Make ticks on occurances of each weekday.\n \"\"\"\n\n def __init__(self, byweekday=1, interval=1, tz=None):\n \"\"\"\n Mark every weekday in *byweekday*; *byweekday* can be a number or\n sequence.\n\n Elements of *byweekday* must be one of MO, TU, WE, TH, FR, SA,\n SU, the constants from :mod:`dateutils.rrule`.\n\n *interval* specifies the number of weeks to skip. For example,\n ``interval=2`` plots every second week.\n \"\"\"\n o = rrulewrapper(DAILY, byweekday=byweekday,\n interval=interval, **self.hms0d)\n RRuleLocator.__init__(self, o, tz)\n\n\nclass DayLocator(RRuleLocator):\n \"\"\"\n Make ticks on occurances of each day of the month. For example,\n 1, 15, 30.\n \"\"\"\n def __init__(self, bymonthday=None, interval=1, tz=None):\n \"\"\"\n Mark every day in *bymonthday*; *bymonthday* can be an int or\n sequence.\n\n Default is to tick every day of the month: ``bymonthday=range(1,32)``\n \"\"\"\n if bymonthday is None: bymonthday=list(range(1,32))\n o = rrulewrapper(DAILY, bymonthday=bymonthday,\n interval=interval, **self.hms0d)\n RRuleLocator.__init__(self, o, tz)\n\n\nclass HourLocator(RRuleLocator):\n \"\"\"\n Make ticks on occurances of each hour.\n \"\"\"\n def __init__(self, byhour=None, interval=1, tz=None):\n \"\"\"\n Mark every hour in *byhour*; *byhour* can be an int or sequence.\n Default is to tick every hour: ``byhour=range(24)``\n\n *interval* is the interval between each iteration. For\n example, if ``interval=2``, mark every second occurrence.\n \"\"\"\n if byhour is None: byhour=list(range(24))\n rule = rrulewrapper(HOURLY, byhour=byhour, interval=interval,\n byminute=0, bysecond=0)\n RRuleLocator.__init__(self, rule, tz)\n\n\nclass MinuteLocator(RRuleLocator):\n \"\"\"\n Make ticks on occurances of each minute.\n \"\"\"\n def __init__(self, byminute=None, interval=1, tz=None):\n \"\"\"\n Mark every minute in *byminute*; *byminute* can be an int or\n sequence. Default is to tick every minute: ``byminute=range(60)``\n\n *interval* is the interval between each iteration. For\n example, if ``interval=2``, mark every second occurrence.\n \"\"\"\n if byminute is None: byminute=list(range(60))\n rule = rrulewrapper(MINUTELY, byminute=byminute, interval=interval,\n bysecond=0)\n RRuleLocator.__init__(self, rule, tz)\n\n\nclass SecondLocator(RRuleLocator):\n \"\"\"\n Make ticks on occurances of each second.\n \"\"\"\n def __init__(self, bysecond=None, interval=1, tz=None):\n \"\"\"\n Mark every second in *bysecond*; *bysecond* can be an int or\n sequence. Default is to tick every second: ``bysecond = range(60)``\n\n *interval* is the interval between each iteration. For\n example, if ``interval=2``, mark every second occurrence.\n\n \"\"\"\n if bysecond is None: bysecond=list(range(60))\n rule = rrulewrapper(SECONDLY, bysecond=bysecond, interval=interval)\n RRuleLocator.__init__(self, rule, tz)\n\n\ndef _close_to_dt(d1, d2, epsilon=5):\n 'Assert that datetimes *d1* and *d2* are within *epsilon* microseconds.'\n delta = d2-d1\n mus = abs(delta.days*MUSECONDS_PER_DAY + delta.seconds*1e6 +\n delta.microseconds)\n assert(mus<epsilon)\n\ndef _close_to_num(o1, o2, epsilon=5):\n 'Assert that float ordinals *o1* and *o2* are within *epsilon* microseconds.'\n delta = abs((o2-o1)*MUSECONDS_PER_DAY)\n assert(delta<epsilon)\n\ndef epoch2num(e):\n \"\"\"\n Convert an epoch or sequence of epochs to the new date format,\n that is days since 0001.\n \"\"\"\n spd = 24.*3600.\n return 719163 + np.asarray(e)/spd\n\ndef num2epoch(d):\n \"\"\"\n Convert days since 0001 to epoch. *d* can be a number or sequence.\n \"\"\"\n spd = 24.*3600.\n return (np.asarray(d)-719163)*spd\n\ndef mx2num(mxdates):\n \"\"\"\n Convert mx :class:`datetime` instance (or sequence of mx\n instances) to the new date format.\n \"\"\"\n scalar = False\n if not cbook.iterable(mxdates):\n scalar = True\n mxdates = [mxdates]\n ret = epoch2num([m.ticks() for m in mxdates])\n if scalar: return ret[0]\n else: return ret\n\n\ndef date_ticker_factory(span, tz=None, numticks=5):\n \"\"\"\n Create a date locator with *numticks* (approx) and a date formatter\n for *span* in days. Return value is (locator, formatter).\n \"\"\"\n\n if span==0: span = 1/24.\n\n minutes = span*24*60\n hours = span*24\n days = span\n weeks = span/7.\n months = span/31. # approx\n years = span/365.\n\n if years>numticks:\n locator = YearLocator(int(years/numticks), tz=tz) # define\n fmt = '%Y'\n elif months>numticks:\n locator = MonthLocator(tz=tz)\n fmt = '%b %Y'\n elif weeks>numticks:\n locator = WeekdayLocator(tz=tz)\n fmt = '%a, %b %d'\n elif days>numticks:\n locator = DayLocator(interval=int(math.ceil(days/numticks)), tz=tz)\n fmt = '%b %d'\n elif hours>numticks:\n locator = HourLocator(interval=int(math.ceil(hours/numticks)), tz=tz)\n fmt = '%H:%M\\n%b %d'\n elif minutes>numticks:\n locator = MinuteLocator(interval=int(math.ceil(minutes/numticks)), tz=tz)\n fmt = '%H:%M:%S'\n else:\n locator = MinuteLocator(tz=tz)\n fmt = '%H:%M:%S'\n\n\n formatter = DateFormatter(fmt, tz=tz)\n return locator, formatter\n\n\ndef seconds(s):\n 'Return seconds as days.'\n return float(s)/SEC_PER_DAY\n\ndef minutes(m):\n 'Return minutes as days.'\n return float(m)/MINUTES_PER_DAY\n\ndef hours(h):\n 'Return hours as days.'\n return h/24.\n\ndef weeks(w):\n 'Return weeks as days.'\n return w*7.\n\n\nclass DateConverter(units.ConversionInterface):\n \"\"\"\n Converter for datetime.date and datetime.datetime data,\n or for date/time data represented as it would be converted\n by :func:`date2num`.\n\n The 'unit' tag for such data is None or a tzinfo instance.\n \"\"\"\n\n @staticmethod\n def axisinfo(unit, axis):\n \"\"\"\n Return the :class:`~matplotlib.units.AxisInfo` for *unit*.\n\n *unit* is a tzinfo instance or None.\n The *axis* argument is required but not used.\n \"\"\"\n tz = unit\n\n majloc = AutoDateLocator(tz=tz)\n majfmt = AutoDateFormatter(majloc, tz=tz)\n datemin = datetime.date(2000, 1, 1)\n datemax = datetime.date(2010, 1, 1)\n\n return units.AxisInfo( majloc=majloc, majfmt=majfmt, label='',\n default_limits=(datemin, datemax))\n\n @staticmethod\n def convert(value, unit, axis):\n \"\"\"\n If *value* is not already a number or sequence of numbers,\n convert it with :func:`date2num`.\n\n The *unit* and *axis* arguments are not used.\n \"\"\"\n if units.ConversionInterface.is_numlike(value):\n return value\n return date2num(value)\n\n @staticmethod\n def default_units(x, axis):\n 'Return the tzinfo instance of *x* or of its first element, or None'\n try:\n x = x[0]\n except (TypeError, IndexError):\n pass\n\n try:\n return x.tzinfo\n except AttributeError:\n pass\n return None\n\n\nunits.registry[datetime.date] = DateConverter()\nunits.registry[datetime.datetime] = DateConverter()\n\n\n\nif __name__=='__main__':\n\n #tz = None\n tz = pytz.timezone('US/Pacific')\n #tz = UTC\n\n dt = datetime.datetime(1011, 10, 9, 13, 44, 22, 101010, tzinfo=tz)\n x = date2num(dt)\n _close_to_dt(dt, num2date(x, tz))\n\n #tz = _get_rc_timezone()\n\n\n d1 = datetime.datetime( 2000, 3, 1, tzinfo=tz)\n d2 = datetime.datetime( 2000, 3, 5, tzinfo=tz)\n\n #d1 = datetime.datetime( 2002, 1, 5, tzinfo=tz)\n #d2 = datetime.datetime( 2003, 12, 1, tzinfo=tz)\n delta = datetime.timedelta(hours=6)\n dates = drange(d1, d2, delta)\n\n # MGDTODO: Broken on transforms branch\n #print 'orig', d1\n #print 'd2n and back', num2date(date2num(d1), tz)\n from _transforms import Value, Interval\n v1 = Value(date2num(d1))\n v2 = Value(date2num(d2))\n dlim = Interval(v1,v2)\n vlim = Interval(v1,v2)\n\n #locator = HourLocator(byhour=(3,15), tz=tz)\n #locator = MinuteLocator(byminute=(15,30,45), tz=tz)\n #locator = YearLocator(base=5, month=7, day=4, tz=tz)\n #locator = MonthLocator(bymonthday=15)\n locator = DayLocator(tz=tz)\n locator.set_data_interval(dlim)\n locator.set_view_interval(vlim)\n dmin, dmax = locator.autoscale()\n vlim.set_bounds(dmin, dmax)\n ticks = locator()\n\n\n fmt = '%Y-%m-%d %H:%M:%S %Z'\n formatter = DateFormatter(fmt, tz)\n\n #for t in ticks: print formatter(t)\n\n for t in dates: print(formatter(t))\n"
] |
[
[
"pandas.tseries.tools.to_datetime",
"pandas.tseries.frequencies.get_offset",
"pandas.tseries.frequencies.to_offset",
"pandas.tslib.monthrange"
],
[
"matplotlib.transforms.Bbox.from_bounds",
"matplotlib.transforms.Affine2D",
"matplotlib.transforms.TransformedBbox"
],
[
"numpy.array",
"numpy.asarray",
"numpy.rec.fromarrays"
],
[
"numpy.array",
"numpy.array_equal",
"pandas.util.py3compat.BytesIO",
"pandas.util.testing.assert_almost_equal",
"pandas._parser.TextReader",
"pandas.util.testing.get_data_path",
"pandas.util.py3compat.StringIO",
"numpy.dtype"
],
[
"numpy.ceil",
"matplotlib.cbook.is_string_like",
"numpy.asarray",
"matplotlib.units.ConversionInterface.is_numlike",
"matplotlib.cbook.iterable",
"matplotlib.cbook.unicode_safe",
"matplotlib.units.AxisInfo",
"numpy.linspace",
"matplotlib.ticker.Base"
]
] |
ocNflag/point2seq
|
[
"710686f576b3df5469a06c66860758b25f852dbd"
] |
[
"pcdet/models/dense_heads/e2e_seqfuse_head.py"
] |
[
"import numpy as np\nimport torch\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\nimport copy\nimport math\n\nfrom pcdet.ops.iou3d_nms.iou3d_nms_utils import boxes_iou3d_gpu\n\nfrom pcdet.models.dense_heads.utils import _sigmoid\n\nfrom ...utils import box_coder_utils, common_utils\nfrom pcdet.utils import matcher\nfrom pcdet.utils.set_crit import SetCriterion\nfrom pcdet.models.dense_heads.e2e_fusion_modules import \\\n OneNetSeqFusionHead, OneNetSeqFusionHeadCST, OneNetSeqFusionHeadTCS, \\\n OneNetSeqFusionHeadDense, OneNetSeqFusionHeadTSC, OneNetSeqFusionHeadCLSCTS, \\\n OneNetSeqFusionHeadCLSTSC, OneNetSeqFusionHeadCLSTCS, \\\n OneNetSeqFusionHeadCLSSTC\nfrom pcdet.models.dense_heads.target_assigner.merged_assigner import MergedAssigner\nfrom pcdet.utils import loss_utils\nfrom ...ops.iou3d_nms import iou3d_nms_cuda\n\nSingleHeadDict = {\n 'OneNetSeqFusionHeadCTS': OneNetSeqFusionHead,\n 'OneNetSeqFusionHead': OneNetSeqFusionHead,\n 'OneNetSeqFusionHeadCST': OneNetSeqFusionHeadCST,\n 'OneNetSeqFusionHeadTCS': OneNetSeqFusionHeadTCS,\n 'OneNetSeqFusionHeadDense': OneNetSeqFusionHeadDense,\n 'OneNetSeqFusionHeadTSC': OneNetSeqFusionHeadTSC,\n 'OneNetSeqFusionHeadCLSCTS': OneNetSeqFusionHeadCLSCTS,\n 'OneNetSeqFusionHeadCLSTSC': OneNetSeqFusionHeadCLSTSC,\n 'OneNetSeqFusionHeadCLSTCS': OneNetSeqFusionHeadCLSTCS,\n 'OneNetSeqFusionHeadCLSSTC': OneNetSeqFusionHeadCLSSTC,\n}\n\n\nclass E2ESeqFusionHead(nn.Module):\n def __init__(self, model_cfg, input_channels, num_class, class_names, grid_size, voxel_size,\n point_cloud_range, predict_boxes_when_training, **kwargs):\n super().__init__()\n self.xoffset = None\n self.yoffset = None\n self.no_log = False\n self.forward_ret_dict = {}\n self.model_cfg = model_cfg\n self.voxel_size = [model_cfg.TARGET_ASSIGNER_CONFIG['out_size_factor'] * iter for iter in voxel_size]\n\n self.period = 2 * np.pi\n # if self.use_dir_classifier:\n # self.period = self.period / self.num_dir_bins\n\n self.single_head = self.model_cfg.get('SingleHead', 'OneNetSeqFusionHead')\n self.post_cfg = model_cfg.TEST_CONFIG\n self.in_channels = input_channels\n self.predict_boxes_when_training = predict_boxes_when_training\n\n self.grid_size = grid_size\n self.point_cloud_range = point_cloud_range\n self.out_size_factor = model_cfg.OUT_SIZE_FACTOR\n self._generate_offset_grid()\n\n self.num_classes = [t[\"num_class\"] for t in model_cfg.TASKS]\n self.class_names = [t[\"class_names\"] for t in model_cfg.TASKS]\n self.template_boxes = [t[\"template_box\"] for t in model_cfg.TASKS]\n self.total_classes = sum(self.num_classes)\n\n box_coder_config = self.model_cfg.CODER_CONFIG.get('BOX_CODER_CONFIG', {})\n box_coder_config['period'] = self.period\n box_coder = getattr(box_coder_utils, self.model_cfg.CODER_CONFIG.BOX_CODER)(**box_coder_config)\n\n set_crit_settings = model_cfg.SET_CRIT_CONFIG\n matcher_settings = model_cfg.MATCHER_CONFIG\n self.matcher_weight_dict = matcher_settings['weight_dict']\n self.use_focal_loss = model_cfg.USE_FOCAL_LOSS\n self.box_coder = box_coder\n\n matcher_settings['box_coder'] = box_coder\n matcher_settings['period'] = self.period\n self.matcher_weight_dict = matcher_settings['weight_dict']\n self.matcher = getattr(matcher, self.model_cfg.MATCHER)(**matcher_settings)\n\n set_crit_settings['box_coder'] = box_coder\n set_crit_settings['matcher'] = self.matcher\n self.set_crit = SetCriterion(**set_crit_settings)\n\n self.aux_loss_weights = self.model_cfg.AUX_LOSS_WEIGHTS\n self.loss_center = loss_utils.CenterNetFocalLoss()\n self.loss_corner = loss_utils.CenterNetFocalLoss()\n self.loss_foreground = loss_utils.ForegroundFocalLoss()\n\n self.target_assigner = MergedAssigner(model_cfg.TARGET_ASSIGNER_CONFIG, num_classes=sum(self.num_classes),\n no_log=self.no_log, grid_size=grid_size, pc_range=point_cloud_range,\n voxel_size=voxel_size)\n\n # self.box_n_dim = 9 if self.dataset == 'nuscenes' else 7\n # self.bev_only = True if model_cfg.MODE == \"bev\" else False\n shared_ch = model_cfg.PARAMETERS.shared_ch\n self.shared_conv = nn.Sequential(\n nn.Conv2d(self.in_channels, shared_ch, kernel_size=3, padding=1, bias=True),\n nn.BatchNorm2d(shared_ch),\n nn.ReLU(inplace=True)\n )\n\n self.common_heads = model_cfg.PARAMETERS.common_heads\n self.output_box_attrs = [k for k in self.common_heads]\n self.tasks = nn.ModuleList()\n\n for num_cls, template_box in zip(self.num_classes, self.template_boxes):\n heads = copy.deepcopy(self.common_heads)\n heads.update(\n dict(\n num_classes=num_cls,\n template_box=template_box,\n pc_range=self.point_cloud_range,\n offset_grid=self.offset_grid,\n voxel_size=self.voxel_size\n )\n )\n self.tasks.append(\n SingleHeadDict[self.single_head](shared_ch, heads)\n )\n\n def _nms_gpu_3d(self, boxes, scores, thresh, pre_maxsize=None, post_max_size=None):\n \"\"\"\n :param boxes: (N, 7) [x, y, z, dx, dy, dz, heading]\n :param scores: (N)\n :param thresh:\n :return:\n \"\"\"\n assert boxes.shape[1] == 7\n order = scores.sort(0, descending=True)[1]\n if pre_maxsize is not None:\n order = order[:pre_maxsize]\n\n boxes = boxes[order].contiguous()\n keep = torch.LongTensor(boxes.size(0))\n num_out = iou3d_nms_cuda.nms_gpu(boxes, keep, thresh)\n selected = order[keep[:num_out].cuda()].contiguous()\n\n if post_max_size is not None:\n selected = selected[:post_max_size]\n\n return selected\n\n def _generate_offset_grid(self):\n x, y = self.grid_size[:2] // self.out_size_factor\n xmin, ymin, zmin, xmax, ymax, zmax = self.point_cloud_range\n\n xoffset = (xmax - xmin) / x\n yoffset = (ymax - ymin) / y\n\n yv, xv = torch.meshgrid([torch.arange(0, y), torch.arange(0, x)])\n yvp = (yv.float() + 0.5) * yoffset + ymin\n xvp = (xv.float() + 0.5) * xoffset + xmin\n\n yvc = yv.float() * yoffset + ymin\n xvc = xv.float() * xoffset + xmin\n\n # size (1, 2, h, w)\n self.register_buffer('offset_grid', torch.stack([xvp, yvp], dim=0)[None])\n self.register_buffer('xy_offset', torch.stack([xvc, yvc], dim=0)[None])\n\n def forward(self, data_dict):\n multi_head_features = []\n spatial_features_2d = data_dict['spatial_features_2d']\n spatial_features_2d = self.shared_conv(spatial_features_2d)\n for task in self.tasks:\n multi_head_features.append(task(spatial_features_2d))\n\n self.forward_ret_dict['multi_head_features'] = multi_head_features\n final_feat = torch.cat([iter['final_feat'] for iter in multi_head_features] + [spatial_features_2d, ], dim=1)\n data_dict['final_feat'] = final_feat\n\n if self.training:\n self.forward_ret_dict['gt_dicts'] = self.target_assigner.assign_targets_cuda(data_dict['gt_boxes'])\n\n if not self.training and not self.predict_boxes_when_training:\n data_dict = self.generate_predicted_boxes(data_dict)\n # else:\n # data_dict = self.generate_predicted_boxes_for_roi_head(data_dict)\n\n return data_dict\n\n def get_proper_xy(self, pred_boxes):\n tmp, res = pred_boxes[:, :2, :, :], pred_boxes[:, 2:, :, :]\n tmp = tmp + self.offset_grid\n return torch.cat([tmp, res], dim=1)\n\n def _reshape_corner_map(self, corner_map):\n bs, c, h, w = corner_map.size()\n return corner_map.view(bs, c // 4, 4, h, w)\n\n def get_loss(self, curr_epoch, **kwargs):\n tb_dict = {}\n pred_dicts = self.forward_ret_dict['multi_head_features']\n losses = []\n self.forward_ret_dict['pred_box_encoding'] = {}\n for task_id, pred_dict in enumerate(pred_dicts):\n task_pred_boxes = self.get_proper_xy(pred_dict['pred_boxes'])\n bs, code, h, w = task_pred_boxes.size()\n task_pred_boxes = task_pred_boxes.permute(0, 2, 3, 1).view(bs, h * w, code)\n task_pred_logits = pred_dict['pred_logits']\n _, cls, _, _ = task_pred_logits.size()\n task_pred_logits = task_pred_logits.permute(0, 2, 3, 1).view(bs, h * w, cls)\n\n task_pred_dicts = {\n 'pred_logits': task_pred_logits,\n 'pred_boxes': task_pred_boxes\n }\n\n task_gt_dicts = self.forward_ret_dict['gt_dicts'][task_id]\n task_loss_dicts = self.set_crit(task_pred_dicts, task_gt_dicts, curr_epoch)\n\n aux_loss_dict = {}\n\n pred_dict['center_map'] = _sigmoid(pred_dict['center_map'])\n pred_dict['corner_map'] = _sigmoid(self._reshape_corner_map(pred_dict['corner_map']))\n pred_dict['foreground_map'] = pred_dict['foreground_map']\n\n aux_loss_dict['loss_center'] = self.loss_center(\n pred_dict['center_map'],\n self.forward_ret_dict['gt_dicts']['center_map'][task_id]\n )\n aux_loss_dict['loss_corner'] = self.loss_corner(\n pred_dict['corner_map'],\n self.forward_ret_dict['gt_dicts']['corner_map'][task_id]\n )\n aux_loss_dict['loss_foreground'] = self.loss_foreground(\n pred_dict['foreground_map'],\n self.forward_ret_dict['gt_dicts']['foreground_map'][task_id]\n )\n\n tmp_loss = task_loss_dicts['loss']\n for k in self.aux_loss_weights:\n tmp_loss = tmp_loss + self.aux_loss_weights[k] * aux_loss_dict[k]\n\n task_loss_dicts.update(aux_loss_dict)\n task_loss_dicts['loss'] = tmp_loss\n\n tb_key = 'task_' + str(task_id) + '/'\n tb_dict.update({\n tb_key + 'loss_x': task_loss_dicts['loc_loss_elem'][0].item(),\n tb_key + 'loss_y': task_loss_dicts['loc_loss_elem'][1].item(),\n tb_key + 'loss_z': task_loss_dicts['loc_loss_elem'][2].item(),\n tb_key + 'loss_w': task_loss_dicts['loc_loss_elem'][3].item(),\n tb_key + 'loss_l': task_loss_dicts['loc_loss_elem'][4].item(),\n tb_key + 'loss_h': task_loss_dicts['loc_loss_elem'][5].item(),\n tb_key + 'loss_sin': task_loss_dicts['loc_loss_elem'][6].item(),\n tb_key + 'loss_cos': task_loss_dicts['loc_loss_elem'][7].item(),\n tb_key + 'loss_ce': task_loss_dicts['loss_ce'],\n tb_key + 'loss_bbox': task_loss_dicts['loss_bbox'],\n tb_key + 'loss_center': task_loss_dicts['loss_center'],\n tb_key + 'loss_corner': task_loss_dicts['loss_corner'],\n tb_key + 'loss_foreground': task_loss_dicts['loss_foreground'],\n })\n\n losses.append(task_loss_dicts['loss'])\n\n return sum(losses), tb_dict\n\n @torch.no_grad()\n def generate_predicted_boxes_for_roi_head(self, data_dict):\n pred_dicts = self.forward_ret_dict['multi_head_features']\n\n task_box_preds = {}\n task_score_preds = {}\n\n k_list = self.post_cfg.k_list\n\n for task_id, pred_dict in enumerate(pred_dicts):\n tmp = {}\n tmp.update(pred_dict)\n _pred_boxes = self.get_proper_xy(tmp['pred_boxes'])\n if self.use_focal_loss:\n _pred_score = tmp['pred_logits'].sigmoid()\n else:\n _pred_score = tmp['pred_logits'].softmax(2)\n\n _pred_score = _pred_score.flatten(2).permute(0, 2, 1)\n _pred_boxes = self.box_coder.decode_torch(_pred_boxes.flatten(2).permute(0, 2, 1))\n\n task_box_preds[task_id] = _pred_boxes\n task_score_preds[task_id] = _pred_score\n\n batch_cls_preds = []\n batch_box_preds = []\n\n bs = len(task_box_preds[0])\n for idx in range(bs):\n cls_offset = 1\n pred_boxes, pred_scores, pred_labels = [], [], []\n for task_id, class_name in enumerate(self.class_names):\n raw_scores = task_score_preds[task_id][idx]\n raw_boxes = task_box_preds[task_id][idx]\n\n cls_num = raw_scores.size(1)\n tmp_scores, tmp_cat_inds = torch.topk(raw_scores, k=k_list[task_id], dim=0)\n\n final_score_task, tmp_inds = torch.topk(tmp_scores.reshape(-1), k=k_list[task_id])\n final_label = (tmp_inds % cls_num) + cls_offset\n\n topk_boxes_cat = raw_boxes[tmp_cat_inds.reshape(-1), :]\n final_box = topk_boxes_cat[tmp_inds, :]\n raw_scores = raw_scores[tmp_cat_inds.reshape(-1), :]\n\n final_score = final_score_task.new_zeros((final_box.shape[0], self.total_classes))\n final_score[:, cls_offset - 1: cls_offset - 1 + cls_num] = raw_scores\n\n pred_boxes.append(final_box)\n pred_scores.append(final_score)\n pred_labels.append(final_label)\n\n cls_offset += len(class_name)\n\n batch_box_preds.append(torch.cat(pred_boxes))\n batch_cls_preds.append(torch.cat(pred_scores))\n\n data_dict['batch_cls_preds'] = torch.stack(batch_cls_preds, dim=0)\n data_dict['batch_box_preds'] = torch.stack(batch_box_preds, dim=0)\n if self.training:\n data_dict['gt_dicts'] = self.forward_ret_dict['gt_dicts']\n\n return data_dict\n\n @torch.no_grad()\n def generate_predicted_boxes(self, data_dict):\n cur_epoch = data_dict['cur_epoch']\n pred_dicts = self.forward_ret_dict['multi_head_features']\n\n task_box_preds = {}\n task_score_preds = {}\n\n k_list = self.post_cfg.k_list\n thresh_list = self.post_cfg.thresh_list\n num_queries = self.post_cfg.num_queries\n # use_nms = self.post_cfg.use_nms\n # vis_dir = getattr(self.post_cfg, 'bev_vis_dir', None)\n\n for task_id, pred_dict in enumerate(pred_dicts):\n tmp = {}\n tmp.update(pred_dict)\n _pred_boxes = self.get_proper_xy(tmp['pred_boxes'])\n\n if self.use_focal_loss:\n _pred_score = tmp['pred_logits'].sigmoid()\n else:\n _pred_score = tmp['pred_logits'].softmax(2)\n\n _pred_score = _pred_score.flatten(2).permute(0, 2, 1)\n _pred_boxes = self.box_coder.decode_torch(_pred_boxes.flatten(2).permute(0, 2, 1))\n\n task_box_preds[task_id] = _pred_boxes\n task_score_preds[task_id] = _pred_score\n\n pred_dicts = []\n bs = len(task_box_preds[0])\n\n for idx in range(bs):\n cls_offset = 1\n final_boxes, final_scores, final_labels = [], [], []\n for task_id, class_name in enumerate(self.class_names):\n task_scores = task_score_preds[task_id][idx]\n task_boxes = task_box_preds[task_id][idx]\n\n cls_num = task_scores.size(1)\n topk_scores_cat, topk_inds_cat = torch.topk(task_scores, k=k_list[task_id], dim=0)\n topk_scores, topk_inds = torch.topk(topk_scores_cat.reshape(-1), k=k_list[task_id])\n topk_labels = (topk_inds % cls_num) + cls_offset\n topk_boxes_cat = task_boxes[topk_inds_cat.reshape(-1), :]\n topk_boxes = topk_boxes_cat[topk_inds, :]\n\n mask = topk_scores >= thresh_list[task_id]\n\n task_boxes = topk_boxes[mask]\n task_scores = topk_scores[mask]\n task_labels = topk_labels[mask]\n\n final_boxes.append(task_boxes)\n final_scores.append(task_scores)\n final_labels.append(task_labels)\n\n cls_offset += len(class_name)\n\n final_boxes = torch.cat(final_boxes)\n final_scores = torch.cat(final_scores)\n final_labels = torch.cat(final_labels)\n end = min(final_scores.size(0), num_queries)\n\n record_dict = {\n \"pred_boxes\": final_boxes[:end],\n \"pred_scores\": final_scores[:end],\n \"pred_labels\": final_labels[:end]\n }\n pred_dicts.append(record_dict)\n\n # import pdb; pdb.set_trace()\n data_dict['pred_dicts'] = pred_dicts\n data_dict['has_class_labels'] = True # Force to be true\n return data_dict\n"
] |
[
[
"torch.cat",
"torch.stack",
"torch.nn.ModuleList",
"torch.arange",
"torch.no_grad",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.topk"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.