repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
george200150/Licenta
[ "9c3f7d86abf3cc5d90204db0acc956eb8bee26dc" ]
[ "Processor/tsne.py" ]
[ "import argparse\nfrom tqdm import tqdm\nimport cv2\nimport torch\nimport random\nimport numpy as np\nfrom sklearn.manifold import TSNE\nimport matplotlib.pyplot as plt\n\nfrom ResNeSt.encoding.models.backbone import resnet101, resnest101, resnest200\nfrom animals10 import AnimalsDataset, collate_skip_empty, colors_per_class\n\n\ndef fix_random_seeds():\n seed = 10\n random.seed(seed)\n torch.manual_seed(seed)\n np.random.seed(seed)\n\n\ndef get_features(dataset, batch, num_images):\n # move the input and model to GPU for speed if available\n if torch.cuda.is_available():\n device = 'cuda'\n else:\n device = 'cpu'\n\n # initialize our implementation of ResNet\n # model = resnest101(pretrained=True)\n model = resnest200(pretrained=True)\n model.eval()\n model.to(device)\n\n # read the dataset and initialize the data loader\n dataset = AnimalsDataset(dataset, num_images)\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch, collate_fn=collate_skip_empty, shuffle=True)\n\n # we'll store the features as NumPy array of size num_images x feature_size\n features = None\n\n # we'll also store the image labels and paths to visualize them later\n labels = []\n image_paths = []\n\n for batch in tqdm(dataloader, desc='Running the model inference'):\n images = batch['image'].to(device)\n labels += batch['label']\n image_paths += batch['image_path']\n\n with torch.no_grad():\n output = model.forward(images)\n\n current_features = output.cpu().numpy()\n if features is not None:\n features = np.concatenate((features, current_features))\n else:\n features = current_features\n\n print(features)\n print(labels)\n print(image_paths)\n\n return features, labels, image_paths\n\n\n# scale and move the coordinates so they fit [0; 1] range\ndef scale_to_01_range(x):\n # compute the distribution range\n value_range = (np.max(x) - np.min(x))\n\n # move the distribution so that it starts from zero\n # by extracting the minimal value from all its values\n starts_from_zero = x - np.min(x)\n\n # make the distribution fit [0; 1] by dividing by its range\n return starts_from_zero / value_range\n\n\ndef scale_image(image, max_image_size):\n image_height, image_width, _ = image.shape\n\n scale = max(1, image_width / max_image_size, image_height / max_image_size)\n image_width = int(image_width / scale)\n image_height = int(image_height / scale)\n\n image = cv2.resize(image, (image_width, image_height))\n return image\n\n\ndef draw_rectangle_by_class(image, label):\n image_height, image_width, _ = image.shape\n\n # get the color corresponding to image class\n color = colors_per_class[label]\n image = cv2.rectangle(image, (0, 0), (image_width - 1, image_height - 1), color=color, thickness=5)\n\n return image\n\n\ndef compute_plot_coordinates(image, x, y, image_centers_area_size, offset):\n image_height, image_width, _ = image.shape\n\n # compute the image center coordinates on the plot\n center_x = int(image_centers_area_size * x) + offset\n\n # in matplotlib, the y axis is directed upward\n # to have the same here, we need to mirror the y coordinate\n center_y = int(image_centers_area_size * (1 - y)) + offset\n\n # knowing the image center, compute the coordinates of the top left and bottom right corner\n tl_x = center_x - int(image_width / 2)\n tl_y = center_y - int(image_height / 2)\n\n br_x = tl_x + image_width\n br_y = tl_y + image_height\n\n return tl_x, tl_y, br_x, br_y\n\n\ndef visualize_tsne_images(tx, ty, images, labels, plot_size=1000, max_image_size=100):\n # we'll put the image centers in the central area of the plot\n # and use offsets to make sure the images fit the plot\n offset = max_image_size // 2\n image_centers_area_size = plot_size - 2 * offset\n\n tsne_plot = 255 * np.ones((plot_size, plot_size, 3), np.uint8)\n\n # now we'll put a small copy of every image to its corresponding T-SNE coordinate\n for image_path, label, x, y in tqdm(\n zip(images, labels, tx, ty),\n desc='Building the T-SNE plot',\n total=len(images)\n ):\n image = cv2.imread(image_path)\n\n # scale the image to put it to the plot\n image = scale_image(image, max_image_size)\n\n # draw a rectangle with a color corresponding to the image class\n image = draw_rectangle_by_class(image, label)\n\n # compute the coordinates of the image on the scaled plot visualization\n tl_x, tl_y, br_x, br_y = compute_plot_coordinates(image, x, y, image_centers_area_size, offset)\n\n # put the image to its TSNE coordinates using numpy subarray indices\n tsne_plot[tl_y:br_y, tl_x:br_x, :] = image\n\n plt.imshow(tsne_plot[:, :, ::-1])\n plt.show()\n\n\ndef visualize_tsne_points(tx, ty, labels):\n # initialize matplotlib plot\n fig = plt.figure()\n ax = fig.add_subplot(111)\n\n # for every class, we'll add a scatter plot separately\n for label in colors_per_class:\n # find the samples of the current class in the data\n indices = [i for i, l in enumerate(labels) if l == label]\n\n # extract the coordinates of the points of this class only\n current_tx = np.take(tx, indices)\n current_ty = np.take(ty, indices)\n\n # convert the class color to matplotlib format:\n # BGR -> RGB, divide by 255, convert to np.array\n color = np.array([colors_per_class[label][::-1]], dtype=np.float) / 255\n\n # add a scatter plot with the corresponding color and label\n ax.scatter(current_tx, current_ty, c=color, label=label)\n\n # build a legend using the labels we set previously\n ax.legend(loc='best')\n\n # finally, show the plot\n plt.show()\n\n\ndef visualize_tsne(tsne, images, labels, plot_size=1000, max_image_size=100):\n # extract x and y coordinates representing the positions of the images on T-SNE plot\n tx = tsne[:, 0]\n ty = tsne[:, 1]\n\n # scale and move the coordinates so they fit [0; 1] range\n tx = scale_to_01_range(tx)\n ty = scale_to_01_range(ty)\n\n # visualize the plot: samples as colored points\n visualize_tsne_points(tx, ty, labels)\n\n # visualize the plot: samples as images\n visualize_tsne_images(tx, ty, images, labels, plot_size=plot_size, max_image_size=max_image_size)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--path', type=str, default='C:/Users/George/Datasets/animals10/archive/raw-img/')\n parser.add_argument('--batch', type=int, default=64)\n parser.add_argument('--num_images', type=int, default=500)\n args = parser.parse_args()\n\n fix_random_seeds()\n\n features, labels, image_paths = get_features(\n dataset=args.path,\n batch=args.batch,\n num_images=args.num_images\n )\n\n tsne = TSNE(n_components=2).fit_transform(features)\n\n visualize_tsne(tsne, image_paths, labels)\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "matplotlib.pyplot.imshow", "numpy.take", "numpy.random.seed", "numpy.min", "torch.manual_seed", "torch.utils.data.DataLoader", "numpy.ones", "numpy.concatenate", "numpy.max", "sklearn.manifold.TSNE", "torch.no_grad", "torch.cuda.is_available", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
fwtan/tensorflow
[ "5e6479904941624cf7ce58ab3d236375c8012ef4", "5e6479904941624cf7ce58ab3d236375c8012ef4" ]
[ "tensorflow/python/client/session_test.py", "tensorflow/python/autograph/operators/control_flow_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\"\"\"Tests for tensorflow.python.client.session.Session.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport random\nimport os\nimport sys\nimport threading\nimport time\nimport warnings\n\nimport numpy as np\nimport six\nfrom six.moves import xrange # pylint: disable=redefined-builtin\n\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.core.lib.core import error_codes_pb2\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import config\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import device as framework_device_lib\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import function\nfrom tensorflow.python.framework import importer\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.framework import versions\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import data_flow_ops\nfrom tensorflow.python.ops import gen_control_flow_ops\n# Import gradients to resolve circular imports\nfrom tensorflow.python.ops import gradients # pylint: disable=unused-import\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import math_ops\n# Import resource_variable_ops for the variables-to-tensor implicit conversion.\nfrom tensorflow.python.ops import resource_variable_ops # pylint: disable=unused-import\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import googletest\nfrom tensorflow.python.training import server_lib\nfrom tensorflow.python.util import compat\n\ntry:\n import attr # pylint:disable=g-import-not-at-top\nexcept ImportError:\n attr = None\n\n\nclass SessionTest(test_util.TensorFlowTestCase):\n\n def setUp(self):\n super(SessionTest, self).setUp()\n warnings.simplefilter('always')\n\n def testUseExistingGraph(self):\n with ops.Graph().as_default() as g, ops.device('/cpu:0'):\n a = constant_op.constant(6.0, shape=[1, 1])\n b = constant_op.constant(7.0, shape=[1, 1])\n c = math_ops.matmul(a, b, name='matmul')\n with session.Session(graph=g):\n result = c.eval()\n self.assertAllEqual(result, [[42.0]])\n\n def testUseDefaultGraph(self):\n with ops.Graph().as_default(), ops.device('/cpu:0'):\n a = constant_op.constant(6.0, shape=[1, 1])\n b = constant_op.constant(7.0, shape=[1, 1])\n c = math_ops.matmul(a, b, name='matmul')\n with session.Session():\n result = c.eval()\n self.assertAllEqual(result, [[42.0]])\n\n def testCreate(self):\n with session.Session():\n inp = constant_op.constant(10.0, shape=[2, 3], name='W1')\n copy = array_ops.identity(inp)\n # Test with feed.\n # TODO(mrry): Investigate why order='F' didn't work.\n arr = np.asarray([[0, 1, 2], [3, 4, 5]], dtype=np.float32, order='C')\n copy_val = copy.eval({'W1:0': arr})\n self.assertAllEqual(arr, copy_val)\n # Test without feed.\n copy_val = copy.eval()\n self.assertAllEqual(\n np.asarray(\n [[10.0, 10.0, 10.0], [10.0, 10.0, 10.0]], dtype=np.float32),\n copy_val)\n\n def testManyCPUs(self):\n with session.Session(\n config=config_pb2.ConfigProto(device_count={\n 'CPU': 2, 'GPU': 0\n })) as sess:\n inp = constant_op.constant(10.0, name='W1')\n self.assertAllEqual(inp.eval(), 10.0)\n\n num_cpu_devices = 0\n num_gpu_devices = 0\n for device in sess.list_devices():\n device_type = framework_device_lib.DeviceSpec.from_string(\n device.name).device_type\n if device_type == 'CPU':\n num_cpu_devices += 1\n elif device_type == 'GPU':\n num_gpu_devices += 1\n self.assertEqual(2, num_cpu_devices)\n self.assertEqual(0, num_gpu_devices)\n\n def testPerSessionThreads(self):\n with session.Session(\n config=config_pb2.ConfigProto(use_per_session_threads=True)):\n inp = constant_op.constant(10.0, name='W1')\n self.assertAllEqual(inp.eval(), 10.0)\n\n def testSessionInterOpThreadPool(self):\n config_pb = config_pb2.ConfigProto()\n pool = config_pb.session_inter_op_thread_pool.add()\n with session.Session(config=config_pb) as s:\n inp = constant_op.constant(10.0, name='W1')\n results = s.run([inp])\n self.assertAllEqual([10.0], results)\n\n pool = config_pb.session_inter_op_thread_pool.add()\n pool.num_threads = 1\n with session.Session(config=config_pb) as s:\n inp = constant_op.constant(20.0, name='W2')\n results = s.run([inp])\n self.assertAllEqual([20.0], results)\n\n pool = config_pb.session_inter_op_thread_pool.add()\n pool.num_threads = 1\n pool.global_name = 't1'\n run_options = config_pb2.RunOptions()\n run_options.inter_op_thread_pool = (\n len(config_pb.session_inter_op_thread_pool) - 1)\n with session.Session(config=config_pb) as s:\n inp = constant_op.constant(30.0, name='W2')\n results = s.run([inp], options=run_options)\n self.assertAllEqual([30.0], results)\n\n def testErrorsReported(self):\n with session.Session() as s:\n constant_op.constant(10.0, name='W1')\n with self.assertRaises(ValueError):\n s.run('foo:0')\n\n def testErrorPayload(self):\n with session.Session():\n a = array_ops.placeholder(dtypes.float32)\n with self.assertRaisesOpError(lambda e: e.op == a.op):\n a.eval()\n\n def testErrorCodeWithNoNodeDef(self):\n with session.Session() as s:\n a = array_ops.placeholder(dtypes.float32, shape=[])\n b = array_ops.placeholder(dtypes.float32, shape=[])\n r1 = math_ops.add(a, b)\n\n def exc_predicate(e):\n return (e.op is None and e.node_def is None and\n e.error_code == error_codes_pb2.INVALID_ARGUMENT)\n\n with self.assertRaisesOpError(exc_predicate):\n # Run with a bogus handle.\n s.partial_run('foo', r1, feed_dict={a: 1, b: 2})\n\n def testErrorBasedOn(self):\n with session.Session() as sess:\n a = constant_op.constant(0.0, shape=[2, 3])\n # NOTE(mrry): The original_op is nonsense, but used here to test that the\n # errors are reported correctly.\n with sess.graph._original_op(a.op):\n b = array_ops.identity(a, name='id')\n with sess.graph._original_op(b.op):\n c = array_ops.placeholder(dtypes.float32)\n\n def exc_predicate(e):\n return (e.op == c.op and e.op._original_op == b.op and\n e.op._original_op._original_op == a.op)\n\n with self.assertRaisesOpError(exc_predicate):\n c.eval()\n\n def testFetchNone(self):\n with session.Session() as s:\n a = constant_op.constant(1.0)\n with self.assertRaises(TypeError):\n s.run(None)\n with self.assertRaises(TypeError):\n s.run([None])\n with self.assertRaises(TypeError):\n s.run({'b': None})\n with self.assertRaises(TypeError):\n s.run({'a': a, 'b': None})\n\n def testFetchSingleton(self):\n with session.Session() as sess:\n a = constant_op.constant(42.0)\n res = sess.run(a)\n self.assertEqual(42.0, res)\n res = sess.run(a.op) # An op, not a tensor.\n self.assertEqual(None, res)\n tensor_runner = sess.make_callable(a)\n res = tensor_runner()\n self.assertEqual(42.0, res)\n op_runner = sess.make_callable(a.op)\n res = op_runner()\n self.assertEqual(None, res)\n\n def testFetchSingletonByName(self):\n with session.Session() as sess:\n a = constant_op.constant(42.0)\n res = sess.run(a.name)\n self.assertEqual(42.0, res)\n res = sess.run(a.op) # An op, not a tensor.\n self.assertEqual(None, res)\n\n def testFetchList(self):\n with session.Session() as sess:\n a = constant_op.constant(42.0)\n b = control_flow_ops.no_op() # An op, not a tensor.\n c = constant_op.constant(44.0)\n v = variables.Variable([54.0])\n assign = v.assign([63.0])\n res = sess.run([a, b, c, a.name, assign.op])\n self.assertTrue(isinstance(res, list))\n self.assertEqual([42.0, None, 44.0, 42.0, None], res)\n list_runner = sess.make_callable([a, b, c, a.name, assign.op])\n res = list_runner()\n self.assertTrue(isinstance(res, list))\n self.assertEqual([42.0, None, 44.0, 42.0, None], res)\n\n def testFetchTuple(self):\n with session.Session() as sess:\n a = constant_op.constant(42.0)\n b = control_flow_ops.no_op() # An op, not a tensor.\n c = constant_op.constant(44.0)\n res = sess.run((a, b, c, a.name))\n self.assertTrue(isinstance(res, tuple))\n self.assertEqual((42.0, None, 44.0, 42.0), res)\n tuple_runner = sess.make_callable((a, b, c, a.name))\n res = tuple_runner()\n self.assertTrue(isinstance(res, tuple))\n self.assertEqual((42.0, None, 44.0, 42.0), res)\n\n def testFetchNamedTuple(self):\n # pylint: disable=invalid-name\n ABC = collections.namedtuple('ABC', ['a', 'b', 'c'])\n # pylint: enable=invalid-name\n with session.Session() as sess:\n a = constant_op.constant(42.0)\n b = control_flow_ops.no_op() # An op, not a tensor.\n c = constant_op.constant(44.0)\n res = sess.run(ABC(a, b, c))\n self.assertTrue(isinstance(res, ABC))\n self.assertEqual(42.0, res.a)\n self.assertEqual(None, res.b)\n self.assertEqual(44.0, res.c)\n namedtuple_runner = sess.make_callable(ABC(a, b, c))\n res = namedtuple_runner()\n self.assertTrue(isinstance(res, ABC))\n self.assertEqual(42.0, res.a)\n self.assertEqual(None, res.b)\n self.assertEqual(44.0, res.c)\n\n def testFetchDict(self):\n with session.Session() as sess:\n a = constant_op.constant(42.0)\n b = control_flow_ops.no_op() # An op, not a tensor.\n c = constant_op.constant(44.0)\n res = sess.run({'a': a, 'b': b, 'c': c})\n self.assertTrue(isinstance(res, dict))\n self.assertEqual(42.0, res['a'])\n self.assertEqual(None, res['b'])\n self.assertEqual(44.0, res['c'])\n\n def testFetchOrderedDict(self):\n with session.Session() as sess:\n a = constant_op.constant(42.0)\n b = control_flow_ops.no_op() # An op, not a tensor.\n c = constant_op.constant(44.0)\n res = sess.run(collections.OrderedDict([(3, a), (2, b), (1, c)]))\n self.assertTrue(isinstance(res, collections.OrderedDict))\n self.assertEqual([3, 2, 1], list(res.keys()))\n self.assertEqual(42.0, res[3])\n self.assertEqual(None, res[2])\n self.assertEqual(44.0, res[1])\n\n @test_util.run_v1_only('b/120545219')\n def testFetchAttrs(self):\n if attr is None:\n self.skipTest('attr module is unavailable.')\n\n @attr.s\n class SampleAttr(object):\n field1 = attr.ib()\n field2 = attr.ib()\n\n val1 = np.array([1.2, 3.4, 5.6])\n val2 = np.array([[1, 2], [4, 3]])\n val3 = np.array([10, 20, 30])\n\n t1 = constant_op.constant(val1)\n t2 = constant_op.constant(val2)\n\n sample = SampleAttr(t1, t2)\n with session.Session() as sess:\n result = sess.run(sample)\n self.assertIsInstance(result, SampleAttr)\n self.assertAllEqual(val1, result.field1)\n self.assertAllEqual(val2, result.field2)\n\n result = sess.run(sample, feed_dict={sample.field1: val3})\n self.assertIsInstance(result, SampleAttr)\n self.assertAllEqual(val3, result.field1)\n self.assertAllEqual(val2, result.field2)\n\n @test_util.run_v1_only('b/120545219')\n def testFetchNestedAttrs(self):\n if attr is None:\n self.skipTest('attr module is unavailable.')\n\n @attr.s\n class SampleAttr(object):\n field0 = attr.ib()\n field1 = attr.ib()\n\n v1 = 10\n v2 = 20\n v3 = np.float32(1.2)\n v4 = np.float32(3.4)\n v5 = np.float64(100.001)\n v6 = np.float64(-23.451)\n arr1 = np.array([1.2, 6.7, 3.4])\n arr2 = np.array([7, 11, 3])\n sample = SampleAttr(\n SampleAttr(\n SampleAttr(constant_op.constant(v1), constant_op.constant(v2)),\n SampleAttr(constant_op.constant(arr1), constant_op.constant(arr2))),\n {'A': SampleAttr(constant_op.constant(v3), constant_op.constant(v4)),\n 'B': [SampleAttr(constant_op.constant(v5), constant_op.constant(v6))]})\n\n with session.Session() as sess:\n result = sess.run(sample)\n self.assertIsInstance(result, SampleAttr)\n self.assertIsInstance(result.field0, SampleAttr)\n self.assertIsInstance(result.field0.field0, SampleAttr)\n self.assertIsInstance(result.field0.field1, SampleAttr)\n self.assertIsInstance(result.field0.field1.field0, np.ndarray)\n self.assertAllEqual(arr1, result.field0.field1.field0)\n self.assertIsInstance(result.field0.field1.field1, np.ndarray)\n self.assertAllEqual(arr2, result.field0.field1.field1)\n self.assertIsInstance(result.field1, dict)\n self.assertIn('A', result.field1)\n self.assertIn('B', result.field1)\n self.assertIsInstance(result.field1['A'], SampleAttr)\n self.assertAllEqual(\n [v3, v4],\n [result.field1['A'].field0, result.field1['A'].field1])\n self.assertIsInstance(result.field1['B'], list)\n self.assertEqual(1, len(result.field1['B']))\n self.assertIsInstance(result.field1['B'][0], SampleAttr)\n self.assertAllEqual(\n [v5, v6],\n [result.field1['B'][0].field0, result.field1['B'][0].field1])\n\n def testFetchNestingEmptyOneLevel(self):\n with session.Session() as sess:\n a_val = 11.0\n a = constant_op.constant(a_val)\n\n res = sess.run([[], tuple(), {}])\n self.assertTrue(isinstance(res, list))\n self.assertEqual(3, len(res))\n self.assertTrue(isinstance(res[0], list))\n self.assertEqual(0, len(res[0]))\n self.assertTrue(isinstance(res[1], tuple))\n self.assertEqual(0, len(res[1]))\n self.assertTrue(isinstance(res[2], dict))\n self.assertEqual(0, len(res[2]))\n\n res = sess.run([[], tuple(), {}, a])\n self.assertTrue(isinstance(res, list))\n self.assertEqual(4, len(res))\n self.assertTrue(isinstance(res[0], list))\n self.assertEqual(0, len(res[0]))\n self.assertTrue(isinstance(res[1], tuple))\n self.assertEqual(0, len(res[1]))\n self.assertTrue(isinstance(res[2], dict))\n self.assertEqual(0, len(res[2]))\n self.assertEqual(a_val, res[3])\n\n def testFetchNestingOneLevel(self):\n with session.Session() as sess:\n # pylint: disable=invalid-name\n ABC = collections.namedtuple('ABC', ['a', 'b', 'c'])\n DEFG = collections.namedtuple('DEFG', ['d', 'e', 'f', 'g'])\n # pylint: enable=invalid-name\n a_val = 42.0\n b_val = None\n c_val = 44.0\n a = constant_op.constant(a_val)\n b = control_flow_ops.no_op() # An op, not a tensor.\n c = constant_op.constant(c_val)\n # List of lists, tuples, namedtuple, and dict\n res = sess.run([[a, b, c], (a, b, c),\n ABC(a=a, b=b, c=c), {\n 'a': a.name,\n 'c': c,\n 'b': b\n }])\n self.assertTrue(isinstance(res, list))\n self.assertEqual(4, len(res))\n self.assertTrue(isinstance(res[0], list))\n self.assertEqual(3, len(res[0]))\n self.assertEqual(a_val, res[0][0])\n self.assertEqual(b_val, res[0][1])\n self.assertEqual(c_val, res[0][2])\n self.assertTrue(isinstance(res[1], tuple))\n self.assertEqual(3, len(res[1]))\n self.assertEqual(a_val, res[1][0])\n self.assertEqual(b_val, res[1][1])\n self.assertEqual(c_val, res[1][2])\n self.assertTrue(isinstance(res[2], ABC))\n self.assertEqual(a_val, res[2].a)\n self.assertEqual(b_val, res[2].b)\n self.assertEqual(c_val, res[2].c)\n self.assertTrue(isinstance(res[3], dict))\n self.assertEqual(3, len(res[3]))\n self.assertEqual(a_val, res[3]['a'])\n self.assertEqual(b_val, res[3]['b'])\n self.assertEqual(c_val, res[3]['c'])\n # Tuple of lists, tuples, namedtuple, and dict\n res = sess.run(([a, b, c], (a.name, b, c), ABC(a=a, b=b, c=c), {\n 'a': a,\n 'c': c,\n 'b': b\n }))\n self.assertTrue(isinstance(res, tuple))\n self.assertEqual(4, len(res))\n self.assertTrue(isinstance(res[0], list))\n self.assertEqual(3, len(res[0]))\n self.assertEqual(a_val, res[0][0])\n self.assertEqual(b_val, res[0][1])\n self.assertEqual(c_val, res[0][2])\n self.assertTrue(isinstance(res[1], tuple))\n self.assertEqual(3, len(res[1]))\n self.assertEqual(a_val, res[1][0])\n self.assertEqual(b_val, res[1][1])\n self.assertEqual(c_val, res[1][2])\n self.assertTrue(isinstance(res[2], ABC))\n self.assertEqual(a_val, res[2].a)\n self.assertEqual(b_val, res[2].b)\n self.assertEqual(c_val, res[2].c)\n self.assertTrue(isinstance(res[3], dict))\n self.assertEqual(3, len(res[3]))\n self.assertEqual(a_val, res[3]['a'])\n self.assertEqual(b_val, res[3]['b'])\n self.assertEqual(c_val, res[3]['c'])\n # Namedtuple of lists, tuples, namedtuples, and dict\n res = sess.run(\n DEFG(\n d=[a, b, c],\n e=(a, b, c),\n f=ABC(a=a.name, b=b, c=c),\n g={\n 'a': a,\n 'c': c,\n 'b': b\n }))\n self.assertTrue(isinstance(res, DEFG))\n self.assertTrue(isinstance(res.d, list))\n self.assertEqual(3, len(res.d))\n self.assertEqual(a_val, res.d[0])\n self.assertEqual(b_val, res.d[1])\n self.assertEqual(c_val, res.d[2])\n self.assertTrue(isinstance(res.e, tuple))\n self.assertEqual(3, len(res.e))\n self.assertEqual(a_val, res.e[0])\n self.assertEqual(b_val, res.e[1])\n self.assertEqual(c_val, res.e[2])\n self.assertTrue(isinstance(res.f, ABC))\n self.assertEqual(a_val, res.f.a)\n self.assertEqual(b_val, res.f.b)\n self.assertEqual(c_val, res.f.c)\n self.assertTrue(isinstance(res.g, dict))\n self.assertEqual(3, len(res.g))\n self.assertEqual(a_val, res.g['a'])\n self.assertEqual(b_val, res.g['b'])\n self.assertEqual(c_val, res.g['c'])\n # Dict of lists, tuples, namedtuples, and dict\n res = sess.run({\n 'd': [a, b, c],\n 'e': (a, b, c),\n 'f': ABC(a=a, b=b, c=c),\n 'g': {\n 'a': a.name,\n 'c': c,\n 'b': b\n }\n })\n self.assertTrue(isinstance(res, dict))\n self.assertEqual(4, len(res))\n self.assertTrue(isinstance(res['d'], list))\n self.assertEqual(3, len(res['d']))\n self.assertEqual(a_val, res['d'][0])\n self.assertEqual(b_val, res['d'][1])\n self.assertEqual(c_val, res['d'][2])\n self.assertTrue(isinstance(res['e'], tuple))\n self.assertEqual(3, len(res['e']))\n self.assertEqual(a_val, res['e'][0])\n self.assertEqual(b_val, res['e'][1])\n self.assertEqual(c_val, res['e'][2])\n self.assertTrue(isinstance(res['f'], ABC))\n self.assertEqual(a_val, res['f'].a)\n self.assertEqual(b_val, res['f'].b)\n self.assertEqual(c_val, res['f'].c)\n self.assertTrue(isinstance(res['g'], dict))\n self.assertEqual(3, len(res['g']))\n self.assertEqual(a_val, res['g']['a'])\n self.assertEqual(b_val, res['g']['b'])\n self.assertEqual(c_val, res['g']['c'])\n\n def testFetchTensorObject(self):\n with session.Session() as s:\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n c = math_ops.matmul(a, b)\n results_with_list = s.run([c])\n self.assertAllEqual([[4.0, 4.0, 4.0]], results_with_list[0])\n results_with_single = s.run(c)\n self.assertAllEqual([[4.0, 4.0, 4.0]], results_with_single)\n results_with_get = c.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], results_with_get)\n a_val, b_val = s.run([a, b]) # Test multiple fetches.\n self.assertAllEqual([[1.0, 1.0]], a_val)\n self.assertAllEqual([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]], b_val)\n results_with_dict = s.run({'a': [a], 'b': b, 'z': [a, b]})\n self.assertAllEqual([[1.0, 1.0]], results_with_dict['a'][0])\n self.assertAllEqual([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]],\n results_with_dict['b'])\n self.assertAllEqual(results_with_dict['a'][0], results_with_dict['z'][0])\n self.assertAllEqual(results_with_dict['b'], results_with_dict['z'][1])\n\n # Test nested structures\n results_with_nested_list = s.run([[[a, b], b], a, [a, b]])\n self.assertAllEqual([[1.0, 1.0]], results_with_nested_list[0][0][0])\n self.assertAllEqual([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]],\n results_with_nested_list[0][0][1])\n self.assertAllEqual(results_with_nested_list[0][0][0],\n results_with_nested_list[1])\n self.assertAllEqual(results_with_nested_list[1],\n results_with_nested_list[2][0])\n self.assertAllEqual(results_with_nested_list[0][0][1],\n results_with_nested_list[0][1])\n self.assertAllEqual(results_with_nested_list[0][1],\n results_with_nested_list[2][1])\n\n def testFetchScalar(self):\n with session.Session() as s:\n for scalar in np.int32, np.int64, np.float16, np.float32, np.float64:\n x = scalar(7)\n y = scalar(8)\n tf_x = constant_op.constant(x, shape=[])\n tf_y = constant_op.constant(y)\n tf_xy = math_ops.add(tf_x, tf_y)\n # Single fetch\n xy = s.run(tf_xy)\n self.assertEqual(scalar, type(xy))\n self.assertEqual(x + y, xy)\n # List fetch\n xy, = s.run([tf_xy])\n self.assertEqual(scalar, type(xy))\n self.assertEqual(x + y, xy)\n # Dict fetch\n xy = s.run({'xy': tf_xy})['xy']\n self.assertEqual(scalar, type(xy))\n self.assertEqual(x + y, xy)\n # Nested list fetch\n xy = s.run([[[tf_xy]], tf_xy, [tf_xy]])\n self.assertAllEqual(xy, [[[x + y]], x + y, [x + y]])\n self.assertEqual(scalar, type(xy[0][0][0]))\n self.assertEqual(scalar, type(xy[1]))\n self.assertEqual(scalar, type(xy[2][0]))\n\n def testFetchOperationObject(self):\n with session.Session() as s:\n a = constant_op.constant(1.0, shape=[1, 2])\n v = variables.Variable(a, name='testFetchOperationObject_v')\n s.run(v.initializer)\n v_val = s.run(v)\n self.assertAllEqual([[1.0, 1.0]], v_val)\n\n def testFetchSparseTensor(self):\n with session.Session() as s:\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n values = np.array([1.0, 2.0]).astype(np.float32)\n shape = np.array([7, 9, 2]).astype(np.int64)\n sp = sparse_tensor.SparseTensor(\n constant_op.constant(indices), constant_op.constant(values),\n constant_op.constant(shape))\n # Single fetch, use as tuple\n sp_out = s.run(sp)\n indices_out, values_out, shape_out = sp_out\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Single fetch, use as SparseTensorValue\n sp_out = s.run(sp)\n self.assertAllEqual(sp_out.indices, indices)\n self.assertAllEqual(sp_out.values, values)\n self.assertAllEqual(sp_out.dense_shape, shape)\n # Tuple fetch, use as tuple\n indices_out, values_out, shape_out = s.run(sp)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # List fetch, use as tuple\n (indices_out, values_out, shape_out), = s.run([sp])\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # List fetch, use as SparseTensorValue\n sp_out, = s.run([sp])\n self.assertAllEqual(sp_out.indices, indices)\n self.assertAllEqual(sp_out.values, values)\n self.assertAllEqual(sp_out.dense_shape, shape)\n # Dict fetch (single value), use as tuple\n indices_out, values_out, shape_out = s.run({'sp': sp})['sp']\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Dict fetch (list value), use as tuple\n (indices_out, values_out, shape_out), = s.run({'sp': [sp]})['sp']\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Dict fetch, use as SparseTensorValue\n sp_out = s.run({'sp': sp})['sp']\n self.assertAllEqual(sp_out.indices, indices)\n self.assertAllEqual(sp_out.values, values)\n self.assertAllEqual(sp_out.dense_shape, shape)\n # Nested list fetch use as tuple\n sp_out = s.run([[[sp]], sp])\n indices_out, values_out, shape_out = sp_out[0][0][0]\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n indices_out, values_out, shape_out = sp_out[1]\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Nested list fetch, use as SparseTensorValue\n sp_out = s.run([[[sp]], sp])\n self.assertAllEqual(sp_out[0][0][0].indices, indices)\n self.assertAllEqual(sp_out[0][0][0].values, values)\n self.assertAllEqual(sp_out[0][0][0].dense_shape, shape)\n self.assertAllEqual(sp_out[1].indices, indices)\n self.assertAllEqual(sp_out[1].values, values)\n self.assertAllEqual(sp_out[1].dense_shape, shape)\n\n def testFeedSparseTensor(self):\n with session.Session() as s:\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n values = np.array([1.0, 2.0]).astype(np.float32)\n shape = np.array([7, 9, 2]).astype(np.int64)\n sp = sparse_tensor.SparseTensor(\n array_ops.placeholder(dtype=np.int64, shape=(2, 3)),\n array_ops.placeholder(dtype=np.float32, shape=(2,)),\n array_ops.placeholder(dtype=np.int64, shape=(3,)),\n )\n sp_indices = array_ops.identity(sp.indices)\n sp_values = array_ops.identity(sp.values)\n sp_shape = array_ops.identity(sp.dense_shape)\n sp2 = sparse_tensor.SparseTensor(sp_indices, sp_values, sp_shape)\n # Feed with tuple\n indices_out, values_out, shape_out = s.run(\n [sp_indices, sp_values, sp_shape], {\n sp: (indices, values, shape)\n })\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Feed with tuple, fetch sp directly\n sp_out = s.run(sp, {sp: (indices, values, shape)})\n self.assertAllEqual(sp_out.indices, indices)\n self.assertAllEqual(sp_out.values, values)\n self.assertAllEqual(sp_out.dense_shape, shape)\n # Feed with SparseTensorValue\n indices_out, values_out, shape_out = s.run(\n [sp_indices, sp_values, sp_shape], {\n sp: sparse_tensor.SparseTensorValue(indices, values, shape)\n })\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Feed with SparseTensorValue, fetch SparseTensorValue\n sp2_out = s.run(sp2, {\n sp: sparse_tensor.SparseTensorValue(indices, values, shape)\n })\n self.assertAllEqual(sp2_out.indices, indices)\n self.assertAllEqual(sp2_out.values, values)\n self.assertAllEqual(sp2_out.dense_shape, shape)\n # Feed SparseTensorValue and fetch sp directly.\n sp_out = s.run(sp, {\n sp: sparse_tensor.SparseTensorValue(indices, values, shape)\n })\n self.assertAllEqual(sp_out.indices, indices)\n self.assertAllEqual(sp_out.values, values)\n self.assertAllEqual(sp_out.dense_shape, shape)\n\n def testFeedSparsePlaceholder(self):\n with session.Session() as s:\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n values = np.array([1.0, 2.0]).astype(np.float32)\n shape = np.array([7, 9, 2]).astype(np.int64)\n sp = array_ops.sparse_placeholder(dtype=np.float32, name='placeholder1')\n sp_indices = array_ops.identity(sp.indices)\n sp_values = array_ops.identity(sp.values)\n sp_shape = array_ops.identity(sp.dense_shape)\n sp2 = sparse_tensor.SparseTensor(sp_indices, sp_values, sp_shape)\n # Feed with tuple\n indices_out, values_out, shape_out = s.run(\n [sp_indices, sp_values, sp_shape], {\n sp: (indices, values, shape)\n })\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Feed with SparseTensorValue\n indices_out, values_out, shape_out = s.run(\n [sp_indices, sp_values, sp_shape], {\n sp: sparse_tensor.SparseTensorValue(indices, values, shape)\n })\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Feed with SparseTensorValue, fetch SparseTensorValue\n sp2_out = s.run(sp2, {\n sp: sparse_tensor.SparseTensorValue(indices, values, shape)\n })\n self.assertAllEqual(sp2_out.indices, indices)\n self.assertAllEqual(sp2_out.values, values)\n self.assertAllEqual(sp2_out.dense_shape, shape)\n\n def testFeedSparsePlaceholderPartialShape(self):\n with session.Session() as s:\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n values = np.array([1.0, 2.0]).astype(np.float32)\n shape = np.array([7, 9, 2]).astype(np.int64)\n sp = array_ops.sparse_placeholder(\n shape=[None, 9, 2], dtype=np.float32, name='placeholder1')\n sp_indices = array_ops.identity(sp.indices)\n sp_values = array_ops.identity(sp.values)\n sp_shape = array_ops.identity(sp.dense_shape)\n sp2 = sparse_tensor.SparseTensor(sp_indices, sp_values, sp_shape)\n # Feed with tuple\n indices_out, values_out, shape_out = s.run(\n [sp_indices, sp_values, sp_shape], {\n sp: (indices, values, shape)\n })\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Feed with SparseTensorValue\n indices_out, values_out, shape_out = s.run(\n [sp_indices, sp_values, sp_shape], {\n sp: sparse_tensor.SparseTensorValue(indices, values, shape)\n })\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Feed with SparseTensorValue, fetch SparseTensorValue\n sp2_out = s.run(sp2, {\n sp: sparse_tensor.SparseTensorValue(indices, values, shape)\n })\n self.assertAllEqual(sp2_out.indices, indices)\n self.assertAllEqual(sp2_out.values, values)\n self.assertAllEqual(sp2_out.dense_shape, shape)\n\n def testFeedSparsePlaceholderConstantShape(self):\n with session.Session() as s:\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n values = np.array([1.0, 2.0]).astype(np.float32)\n shape = np.array([7, 9, 2]).astype(np.int64)\n sp = array_ops.sparse_placeholder(\n dtype=np.float32, shape=shape, name='placeholder1')\n self.assertAllEqual(sp.dense_shape.eval(session=s), shape)\n self.assertAllEqual(tensor_util.constant_value(sp.shape), shape)\n sp_indices = array_ops.identity(sp.indices)\n sp_values = array_ops.identity(sp.values)\n sp_shape = array_ops.identity(sp.dense_shape)\n # Feed with tuple\n indices_out, values_out, shape_out = s.run(\n [sp_indices, sp_values, sp_shape], {\n sp: (indices, values)\n })\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n\n def testFetchIndexedSlices(self):\n with session.Session() as s:\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n values = np.array([1.0, 2.0]).astype(np.float32)\n dense_shape = np.array([7, 9, 2]).astype(np.int64)\n ind = ops.IndexedSlices(\n constant_op.constant(values), constant_op.constant(indices),\n constant_op.constant(dense_shape))\n # Single fetch, use as tuple\n ind_out = s.run(ind)\n values_out, indices_out, dense_shape_out = ind_out\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # Single fetch, use as IndexedSlicesValue\n ind_out = s.run(ind)\n self.assertAllEqual(ind_out.values, values)\n self.assertAllEqual(ind_out.indices, indices)\n self.assertAllEqual(ind_out.dense_shape, dense_shape)\n # Tuple fetch, use as tuple\n values_out, indices_out, dense_shape_out = s.run(ind)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # List fetch, use as tuple\n (values_out, indices_out, dense_shape_out), = s.run([ind])\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # List fetch, use as IndexedSlicesValue\n ind_out, = s.run([ind])\n self.assertAllEqual(ind_out.values, values)\n self.assertAllEqual(ind_out.indices, indices)\n self.assertAllEqual(ind_out.dense_shape, dense_shape)\n\n def testFeedIndexedSlices(self):\n with session.Session() as s:\n values = np.array([1.0, 2.0]).astype(np.float32)\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n dense_shape = np.array([7, 9, 2]).astype(np.int64)\n ind = ops.IndexedSlices(\n array_ops.placeholder(dtype=np.float32, shape=(2,)),\n array_ops.placeholder(dtype=np.int64, shape=(2, 3)),\n array_ops.placeholder(dtype=np.int64, shape=(3,)),\n )\n ind_values = array_ops.identity(ind.values)\n ind_indices = array_ops.identity(ind.indices)\n ind_dense_shape = array_ops.identity(ind.dense_shape)\n ind2 = ops.IndexedSlices(ind_values, ind_indices, ind_dense_shape)\n # Feed with tuple\n values_out, indices_out, dense_shape_out = s.run(\n [ind_values, ind_indices, ind_dense_shape], {\n ind: (values, indices, dense_shape)\n })\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # Feed with IndexedSlicesValue\n values_out, indices_out, dense_shape_out = s.run(\n [ind_values, ind_indices, ind_dense_shape], {\n ind: ops.IndexedSlicesValue(values, indices, dense_shape)\n })\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # Feed with IndexedSlicesValue, fetch IndexedSlicesValue\n ind2_out = s.run(ind2, {\n ind: ops.IndexedSlicesValue(values, indices, dense_shape)\n })\n self.assertAllEqual(ind2_out.values, values)\n self.assertAllEqual(ind2_out.indices, indices)\n self.assertAllEqual(ind2_out.dense_shape, dense_shape)\n\n def testFetchIndexedSlicesWithoutDenseShape(self):\n with session.Session() as s:\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n values = np.array([1.0, 2.0]).astype(np.float32)\n dense_shape = None\n ind = ops.IndexedSlices(\n constant_op.constant(values), constant_op.constant(indices), None)\n # Single fetch, use as tuple\n ind_out = s.run(ind)\n values_out, indices_out, dense_shape_out = ind_out\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # Single fetch, use as IndexedSlicesValue\n ind_out = s.run(ind)\n self.assertAllEqual(ind_out.values, values)\n self.assertAllEqual(ind_out.indices, indices)\n self.assertAllEqual(ind_out.dense_shape, dense_shape)\n # Tuple fetch, use as tuple\n values_out, indices_out, dense_shape_out = s.run(ind)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # List fetch, use as tuple\n (values_out, indices_out, dense_shape_out), = s.run([ind])\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # List fetch, use as IndexedSlicesValue\n ind_out, = s.run([ind])\n self.assertAllEqual(ind_out.values, values)\n self.assertAllEqual(ind_out.indices, indices)\n self.assertAllEqual(ind_out.dense_shape, dense_shape)\n\n def testFeedIndexedSlicesWithoutDenseShape(self):\n with session.Session() as s:\n values = np.array([1.0, 2.0]).astype(np.float32)\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n dense_shape = None\n ind = ops.IndexedSlices(\n array_ops.placeholder(dtype=np.float32, shape=(2,)),\n array_ops.placeholder(dtype=np.int64, shape=(2, 3)), None)\n ind_values = array_ops.identity(ind.values)\n ind_indices = array_ops.identity(ind.indices)\n ind2 = ops.IndexedSlices(ind_values, ind_indices)\n # Feed with tuple\n values_out, indices_out = s.run([ind_values, ind_indices], {\n ind: (values, indices)\n })\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n # Feed with IndexedSlicesValue\n values_out, indices_out = s.run([ind_values, ind_indices], {\n ind: ops.IndexedSlicesValue(values, indices, dense_shape)\n })\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n # Feed with IndexedSlicesValue, fetch IndexedSlicesValue\n ind2_out = s.run(ind2, {\n ind: ops.IndexedSlicesValue(values, indices, dense_shape)\n })\n self.assertAllEqual(ind2_out.values, values)\n self.assertAllEqual(ind2_out.indices, indices)\n self.assertAllEqual(ind2_out.dense_shape, dense_shape)\n\n def testExtendWithStatelessOperations(self):\n with session.Session() as s:\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n c = math_ops.matmul(a, b)\n c_val = s.run(c)\n self.assertAllEqual([[4.0, 4.0, 4.0]], c_val)\n d = constant_op.constant([1.0, 2.0, 3.0], shape=[3, 1])\n e = math_ops.matmul(c, d)\n # Extend will happen here.\n e_val = s.run(e)\n self.assertAllEqual([[24.0]], e_val)\n\n def testExtendWithStatefulOperations(self):\n with session.Session() as s:\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n c = math_ops.matmul(a, b)\n v = variables.Variable(c, name='testExtendWithStatefulOperations_v')\n v.initializer.run()\n v_val = v.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)\n d = constant_op.constant(3.0, shape=[2, 3])\n e = math_ops.matmul(a, d)\n assign_e_to_v = state_ops.assign(v, e)\n # Extend will happen here.\n e_val = e.eval()\n self.assertAllEqual([[6.0, 6.0, 6.0]], e_val)\n v_val = v.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)\n s.run(assign_e_to_v)\n v_val = v.eval()\n self.assertAllEqual([[6.0, 6.0, 6.0]], v_val)\n\n def testExtendWithGroupBy(self):\n with session.Session() as s:\n a = constant_op.constant(1.0, shape=[1, 2])\n p = variables.Variable(a, name='testExtendWithGroupBy_p')\n a_val = a.eval() # Force an Extend after this op.\n self.assertAllEqual([[1.0, 1.0]], a_val)\n\n b = constant_op.constant(2.0, shape=[1, 2])\n q = variables.Variable(b, name='testExtendWithGroupBy_q')\n # Extend will happen here.\n init = control_flow_ops.group(p.initializer, q.initializer)\n s.run(init)\n p_val, q_val = s.run([p, q])\n\n self.assertAllEqual([[1.0, 1.0]], p_val)\n self.assertAllEqual([[2.0, 2.0]], q_val)\n\n def testTensorGetMethod(self):\n with session.Session():\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n c = math_ops.matmul(a, b)\n\n c_val = c.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], c_val)\n\n fed_c_val = c.eval(feed_dict={a.name: [[4.0, 4.0]]})\n self.assertAllEqual([[16.0, 16.0, 16.0]], fed_c_val)\n\n @test_util.run_v1_only('b/120545219')\n def testOperationRunMethod(self):\n with session.Session():\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[1, 2], name='b')\n v = variables.VariableV1(a, a.dtype)\n assign_a_to_v = state_ops.assign(v, a)\n\n assign_a_to_v.eval()\n\n v_val = v.eval()\n self.assertAllEqual([[1.0, 1.0]], v_val)\n\n assign_b_to_v = state_ops.assign(v, b)\n\n assign_b_to_v.eval()\n v_val = v.eval()\n self.assertAllEqual([[2.0, 2.0]], v_val)\n\n assign_b_to_v.eval(feed_dict={'b:0': [[3.0, 3.0]]})\n v_val = v.eval()\n self.assertAllEqual([[3.0, 3.0]], v_val)\n\n def testDefaultGraph(self):\n with session.Session() as s:\n self.assertEqual(ops.get_default_graph(), s.graph)\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n self.assertEqual(ops.get_default_graph(), a.graph)\n self.assertEqual(ops.get_default_graph(), b.graph)\n c = math_ops.matmul(a, b)\n v = variables.Variable(c, name='testDefaultGraph_v')\n v.initializer.run()\n v_val = v.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)\n d = constant_op.constant(3.0, shape=[2, 3])\n e = math_ops.matmul(a, d)\n assign_e_to_v = state_ops.assign(v, e)\n e_val = e.eval()\n self.assertAllEqual([[6.0, 6.0, 6.0]], e_val)\n v_val = v.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)\n s.run(assign_e_to_v)\n v_val = v.eval()\n self.assertAllEqual([[6.0, 6.0, 6.0]], v_val)\n self.assertEqual(ops.get_default_graph(), s.graph)\n\n def _testDefaultGraphInThread(self, constructed_event, continue_event, i):\n with session.Session() as s:\n self.assertEqual(ops.get_default_graph(), s.graph)\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n c = math_ops.matmul(a, b)\n v = variables.Variable(c, name='var_%d' % i)\n\n # Block here until all threads have constructed their graph.\n constructed_event.set()\n continue_event.wait()\n\n assign_c_to_v = state_ops.assign(v, c)\n v.initializer.run()\n assign_c_to_v.eval()\n v_val = v.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)\n d = constant_op.constant(3.0, shape=[2, 3])\n e = math_ops.matmul(a, d)\n assign_e_to_v = state_ops.assign(v, e)\n e_val = e.eval()\n self.assertAllEqual([[6.0, 6.0, 6.0]], e_val)\n v_val = v.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)\n s.run(assign_e_to_v)\n v_val = v.eval()\n self.assertAllEqual([[6.0, 6.0, 6.0]], v_val)\n self.assertEqual(ops.get_default_graph(), s.graph)\n\n def testDefaultGraphWithThreads(self):\n # Fork ten threads that use their thread-local default graph.\n threads = []\n constructed_events = [threading.Event() for _ in range(10)]\n continue_event = threading.Event()\n for i, constructed_event in enumerate(constructed_events):\n t = self.checkedThread(\n target=self._testDefaultGraphInThread,\n args=(constructed_event, continue_event, i))\n threads.append(t)\n for t in threads:\n t.start()\n for constructed_event in constructed_events:\n constructed_event.wait()\n continue_event.set()\n for t in threads:\n t.join()\n\n def testParallelRun(self):\n with session.Session() as sess:\n c = constant_op.constant(5.0)\n ev = threading.Event()\n\n def run_step():\n ev.wait()\n val = c.eval(session=sess)\n self.assertEqual(val, 5.0)\n\n threads = [self.checkedThread(target=run_step) for _ in range(100)]\n for t in threads:\n t.start()\n ev.set()\n for t in threads:\n t.join()\n\n @staticmethod\n def _build_graph():\n time.sleep(random.random() * 0.1)\n # Do some graph construction. Try to exercise non-trivial paths.\n graph = ops.get_default_graph()\n gdef = None\n for _ in range(10):\n x = array_ops.placeholder(dtype=dtypes.float32)\n with ops.colocate_with(x):\n y = array_ops.placeholder(dtype=dtypes.float32)\n with ops.device('/cpu:0'):\n z = control_flow_ops.while_loop(\n lambda x, y: x < 10, lambda x, y: (x + 1, x * y), [x, y])\n with graph._attr_scope({'_a': attr_value_pb2.AttrValue(b=False)}):\n gradients_impl.gradients(z, [x, y])\n if gdef is None:\n gdef = graph.as_graph_def()\n else:\n importer.import_graph_def(gdef, name='import')\n\n @test_util.run_v1_only('b/120545219')\n def testParallelRunAndSingleBuild(self):\n with session.Session() as sess:\n c = constant_op.constant(5.0)\n stop = threading.Event()\n\n def run_loop():\n while not stop.is_set():\n time.sleep(random.random() * 0.1)\n self.assertEqual(sess.run(c), 5.0)\n\n threads = [self.checkedThread(target=run_loop) for _ in range(10)]\n for t in threads:\n t.start()\n\n SessionTest._build_graph()\n\n stop.set()\n for t in threads:\n t.join()\n\n @test_util.run_v1_only('b/120545219')\n def testParallelRunAndParallelBuild(self):\n with session.Session() as sess:\n c = constant_op.constant(5.0)\n stop = threading.Event()\n\n def run_loop():\n while not stop.is_set():\n time.sleep(random.random() * 0.1)\n self.assertEqual(sess.run(c), 5.0)\n\n run_threads = [self.checkedThread(target=run_loop) for _ in range(10)]\n for t in run_threads:\n t.start()\n\n build_threads = [self.checkedThread(target=SessionTest._build_graph)\n for _ in range(10)]\n for t in build_threads:\n t.start()\n for t in build_threads:\n t.join()\n\n # Let the run_threads run until the build threads are finished.\n stop.set()\n for t in run_threads:\n t.join()\n\n def testRunFeedDict(self):\n with session.Session() as s:\n x = array_ops.zeros([2])\n\n y = s.run(2 * x, feed_dict={x: np.ones(2).astype(np.float32)})\n self.assertAllEqual(y, 2 * np.ones(2))\n\n y = s.run(2 * x, feed_dict={x.name: np.ones(2).astype(np.float32)})\n self.assertAllEqual(y, 2 * np.ones(2))\n\n y = s.run(2 * x, feed_dict={x: [1, 1]})\n assert (y == 2 * np.ones(2)).all()\n\n # Test nested tuple keys\n z = (((array_ops.zeros([2]),),), array_ops.zeros([2]),\n (array_ops.zeros([2]),))\n result = [z[0][0][0] * 2, z[1] * 2, z[2][0] * 2]\n values = (((np.array([1, 1]),),), np.array([2, 2]), (np.array([3, 3]),))\n result_value = s.run(result, feed_dict={z: values})\n self.assertAllEqual(result_value[0], 2 * np.ones(2))\n self.assertAllEqual(result_value[1], 2 * np.array([2, 2]))\n self.assertAllEqual(result_value[2], 2 * np.array([3, 3]))\n\n def testGraphDef(self):\n with session.Session() as sess:\n self.assertProtoEquals('versions { producer: %d min_consumer: %d }' %\n (versions.GRAPH_DEF_VERSION,\n versions.GRAPH_DEF_VERSION_MIN_CONSUMER),\n sess.graph_def)\n c = constant_op.constant(5.0, name='c')\n self.assertEqual(len(sess.graph_def.node), 1)\n d = constant_op.constant(6.0, name='d')\n self.assertEqual(len(sess.graph_def.node), 2)\n self.assertAllEqual(c.eval(), 5.0)\n self.assertAllEqual(d.eval(), 6.0)\n e = constant_op.constant(7.0, name='e')\n self.assertEqual(len(sess.graph_def.node), 3)\n self.assertAllEqual(e.eval(), 7.0)\n\n def testUseAfterClose(self):\n with session.Session() as sess:\n c = constant_op.constant(5.0)\n self.assertAllEqual(sess.run(c), 5.0)\n with self.assertRaisesWithPredicateMatch(\n RuntimeError, lambda e: 'Attempted to use a closed Session.' in str(e)):\n sess.run(c)\n\n def testUseAfterCloseConcurrent(self):\n with session.Session() as sess:\n c = constant_op.constant(5.0)\n self.assertAllEqual(sess.run(c), 5.0)\n\n def update_thread():\n with self.assertRaisesWithPredicateMatch(\n RuntimeError,\n lambda e: 'Attempted to use a closed Session.' in str(e)):\n while True:\n sess.run(c)\n\n t = threading.Thread(target=update_thread)\n t.start()\n time.sleep(0.1)\n sess.close()\n t.join()\n\n def testUseEmptyGraph(self):\n with session.Session() as sess:\n with self.assertRaisesRegexp(RuntimeError, 'The Session graph is empty.'):\n sess.run([])\n with self.assertRaisesRegexp(RuntimeError, 'The Session graph is empty.'):\n sess.run(())\n with self.assertRaisesRegexp(RuntimeError, 'The Session graph is empty.'):\n sess.run({})\n\n @test_util.run_v1_only('b/120545219')\n def testNotEntered(self):\n # pylint: disable=protected-access\n self.assertEqual(ops._default_session_stack.get_default(), None)\n # pylint: enable=protected-access\n with ops.device('/cpu:0'):\n sess = session.Session()\n c_1 = constant_op.constant(5.0)\n with sess.graph.as_default():\n c_2 = constant_op.constant(5.0)\n self.assertEqual(c_1.graph, c_2.graph)\n self.assertEqual(sess.run(c_2), 5.0)\n with self.assertRaisesWithPredicateMatch(\n ValueError, lambda e: 'No default session is registered.' in str(e)):\n c_2.eval()\n\n @test_util.run_v1_only('b/120545219')\n def testInteractive(self):\n with ops.device('/cpu:0'):\n sess = session.InteractiveSession()\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n c = math_ops.matmul(a, b)\n self.assertAllEqual([[4.0, 4.0, 4.0]], c.eval())\n d = constant_op.constant([1.0, 2.0, 3.0], shape=[3, 1])\n e = math_ops.matmul(c, d)\n self.assertAllEqual([[24.0]], e.eval())\n sess.close()\n\n @test_util.run_v1_only('b/120545219')\n def testMultipleInteractiveSessionsWarning(self):\n # Reinitialize the global state to ensure that the expected warnings will\n # be emitted.\n session.InteractiveSession._active_session_count = 0 # pylint: disable=protected-access\n\n sess = session.InteractiveSession()\n sess.run(constant_op.constant(4.0)) # Run so that the session is \"opened\".\n sess.close()\n # Opening and closing interactive sessions serially should not warn.\n with warnings.catch_warnings(record=True) as w:\n sess = session.InteractiveSession()\n sess.close()\n self.assertEqual(0, len(w))\n\n with warnings.catch_warnings(record=True) as w:\n sess = session.InteractiveSession()\n self.assertEqual(0, len(w))\n with warnings.catch_warnings(record=True) as w:\n sess2 = session.InteractiveSession()\n self.assertEqual(1, len(w))\n self.assertTrue('An interactive session is already active. This can cause '\n 'out-of-memory errors in some cases. You must explicitly '\n 'call `InteractiveSession.close()` to release resources '\n 'held by the other session(s).' in str(w[0].message))\n sess2.close()\n sess.close()\n\n @test_util.run_v1_only('b/120545219')\n def testInteractivePlacePrunedGraph(self):\n sess = session.InteractiveSession()\n\n # Build a graph that has a bad op in it (no kernel).\n #\n # This test currently does not link in any GPU kernels,\n # which is why placing this is invalid. If at some point\n # GPU kernels are added to this test, some other different\n # op / device combo should be chosen.\n with ops.device('/device:GPU:0'):\n a = constant_op.constant(1.0, shape=[1, 2])\n\n b = constant_op.constant(1.0, shape=[1, 2])\n\n # Only run the valid op, this should work.\n b.eval()\n\n with self.assertRaises(errors.InvalidArgumentError):\n a.eval()\n sess.close()\n\n @test_util.run_v1_only('b/120545219')\n def testDefaultSessionPlacePrunedGraph(self):\n sess = session.Session()\n\n # Build a graph that has a bad op in it (no kernel).\n #\n # This test currently does not link in any GPU kernels,\n # which is why placing this is invalid. If at some point\n # GPU kernels are added to this test, some other different\n # op / device combo should be chosen.\n with ops.device('/device:GPU:0'):\n _ = constant_op.constant(1.0, shape=[1, 2])\n\n b = constant_op.constant(1.0, shape=[1, 2])\n\n with self.assertRaises(errors.InvalidArgumentError):\n # Even though we don't run the bad op, we place the entire\n # graph, which should fail with a non-interactive session.\n sess.run(b)\n\n sess.close()\n\n def testSharedGraph(self):\n with ops.Graph().as_default() as g, ops.device('/cpu:0'):\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n c = math_ops.matmul(a, b)\n\n with session.Session(graph=g) as sess1:\n with session.Session(graph=g) as sess2:\n self.assertAllEqual(sess1.run(c), sess2.run(c))\n\n def testDuplicatedInputs(self):\n with session.Session() as sess:\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[1, 3])\n a_val, b_val, a2_val = sess.run([a, b, a])\n self.assertAllEqual(a_val, [[1.0, 1.0]])\n self.assertAllEqual(b_val, [[2.0, 2.0, 2.0]])\n self.assertAllEqual(a2_val, [[1.0, 1.0]])\n\n def testFeedAndFetch(self):\n with session.Session() as sess:\n for dtype in [\n dtypes.float16, dtypes.float32, dtypes.float64, dtypes.int32,\n dtypes.uint8, dtypes.int16, dtypes.int8, dtypes.int64, dtypes.bool,\n dtypes.complex64, dtypes.complex128\n ]:\n for shape in [(32, 4, 128), (37,), (2, 0, 6), (0, 0, 0)]:\n np_dtype = dtype.as_numpy_dtype\n\n feed_t = array_ops.placeholder(dtype=dtype, shape=shape)\n out_t = array_ops.identity(feed_t)\n\n np_array = np.random.randint(-10, 10, shape)\n\n if dtype == dtypes.bool:\n np_array = np_array > 0\n elif dtype == dtypes.complex64:\n np_array = np.sqrt(np_array.astype(np_dtype))\n elif dtype == dtypes.complex64:\n np_array = np.sqrt(np_array.astype(np_dtype))\n else:\n np_array = np_array.astype(np_dtype)\n\n self.assertAllEqual(np_array,\n sess.run(out_t, feed_dict={\n feed_t: np_array\n }))\n # Check that we can also get the feed back.\n self.assertAllEqual(np_array,\n sess.run(feed_t, feed_dict={\n feed_t: np_array\n }))\n # Also check that we can get both back.\n out_v, feed_v = sess.run(\n [out_t, feed_t], feed_dict={\n feed_t: np_array\n })\n self.assertAllEqual(np_array, out_v)\n self.assertAllEqual(np_array, feed_v)\n\n feed_fetch_runner = sess.make_callable([out_t, feed_t], [feed_t])\n out_v, feed_v = feed_fetch_runner(np_array)\n self.assertAllEqual(np_array, out_v)\n self.assertAllEqual(np_array, feed_v)\n\n def testMakeCallableOnTensorWithRunOptions(self):\n with session.Session() as sess:\n a = constant_op.constant(42.0)\n tensor_runner = sess.make_callable(a, accept_options=True)\n run_options = config_pb2.RunOptions(\n trace_level=config_pb2.RunOptions.FULL_TRACE)\n run_metadata = config_pb2.RunMetadata()\n self.assertEqual(0, len(run_metadata.step_stats.dev_stats))\n res = tensor_runner(options=run_options, run_metadata=run_metadata)\n self.assertEqual(42.0, res)\n self.assertGreater(len(run_metadata.step_stats.dev_stats), 0)\n\n def testMakeCallableOnOperationWithRunOptions(self):\n with session.Session() as sess:\n a = variables.Variable(42.0)\n b = state_ops.assign_add(a, 1.0)\n sess.run(a.initializer)\n tensor_runner = sess.make_callable(b.op, accept_options=True)\n run_options = config_pb2.RunOptions(\n trace_level=config_pb2.RunOptions.FULL_TRACE)\n run_metadata = config_pb2.RunMetadata()\n self.assertEqual(0, len(run_metadata.step_stats.dev_stats))\n tensor_runner(options=run_options, run_metadata=run_metadata)\n self.assertEqual(43.0, sess.run(a))\n self.assertGreater(len(run_metadata.step_stats.dev_stats), 0)\n\n def testMakeCallableWithFeedListAndRunOptions(self):\n with session.Session() as sess:\n ph = array_ops.placeholder(dtypes.float32)\n a = math_ops.add(ph, 1.0)\n tensor_runner = sess.make_callable(\n a, feed_list=[ph.name], accept_options=True)\n run_options = config_pb2.RunOptions(\n trace_level=config_pb2.RunOptions.FULL_TRACE)\n run_metadata = config_pb2.RunMetadata()\n self.assertEqual(0, len(run_metadata.step_stats.dev_stats))\n self.assertAllClose(42.0,\n tensor_runner(\n 41.0,\n options=run_options,\n run_metadata=run_metadata))\n self.assertGreater(len(run_metadata.step_stats.dev_stats), 0)\n\n def testOptimizedMakeCallable(self):\n with session.Session() as sess:\n ph = array_ops.placeholder(dtypes.float32)\n a = math_ops.add(ph, 1.0)\n callable_opts = config_pb2.CallableOptions()\n callable_opts.feed.append(ph.name)\n callable_opts.fetch.append(a.name)\n for _ in range(3):\n callable_fn = sess._make_callable_from_options(callable_opts)\n for _ in range(5):\n self.assertEqual([2.0], callable_fn(np.array(1.0, dtype=np.float32)))\n\n def testOptimizedMakeCallableWithRunMetadata(self):\n with session.Session() as sess:\n ph = array_ops.placeholder(dtypes.float32)\n a = math_ops.add(ph, 1.0)\n callable_opts = config_pb2.CallableOptions()\n callable_opts.feed.append(ph.name)\n callable_opts.fetch.append(a.name)\n callable_opts.run_options.trace_level = config_pb2.RunOptions.FULL_TRACE\n callable_fn = sess._make_callable_from_options(callable_opts)\n run_metadata = config_pb2.RunMetadata()\n self.assertEqual([2.0], callable_fn(np.array(1.0, dtype=np.float32),\n run_metadata=run_metadata))\n self.assertGreater(len(run_metadata.step_stats.dev_stats), 0)\n\n def testFeedError(self):\n with session.Session() as sess:\n feed_t = array_ops.placeholder(dtype=dtypes.float32)\n out_t = array_ops.identity(feed_t)\n feed_val = constant_op.constant(5.0)\n with self.assertRaisesRegexp(TypeError, 'cannot be a tf.Tensor object'):\n sess.run(out_t, feed_dict={feed_t: feed_val})\n with self.assertRaisesRegexp(TypeError, 'cannot be a tf.Tensor object'):\n out_t.eval(feed_dict={feed_t: feed_val})\n with self.assertRaisesRegexp(TypeError, 'cannot be a tf.Tensor object'):\n out_t.op.run(feed_dict={feed_t: feed_val})\n\n def testFeedPrecisionLossError(self):\n with session.Session() as sess:\n largest_int64 = np.iinfo(np.int64).max\n\n feed_int_implicit_int32 = constant_op.constant(1)\n feed_int_explicit_int32 = constant_op.constant(1, dtype=dtypes.int32)\n\n out_t = constant_op.constant(1.0)\n\n with self.assertRaisesRegexp(TypeError,\n 'is not compatible with Tensor type'):\n sess.run(out_t, feed_dict={feed_int_implicit_int32: largest_int64})\n with self.assertRaisesRegexp(TypeError,\n 'is not compatible with Tensor type'):\n sess.run(out_t, feed_dict={feed_int_explicit_int32: largest_int64})\n\n def testStringFetch(self):\n with session.Session():\n for shape in [(32, 4, 128), (37,), (2, 0, 6), (0, 0, 0)]:\n size = 1\n for s in shape:\n size *= s\n c_list = np.array(\n [compat.as_bytes(str(i)) for i in xrange(size)],\n dtype=np.object).reshape(shape) if size > 0 else []\n c = constant_op.constant(c_list)\n self.assertAllEqual(c.eval(), c_list)\n\n def testStringFeed(self):\n with session.Session() as sess:\n for shape in [(32, 4, 128), (37,), (2, 0, 6), (0, 0, 0)]:\n size = 1\n for s in shape:\n size *= s\n c_list = np.array(\n [compat.as_bytes(str(i)) for i in xrange(size)],\n dtype=np.object).reshape(shape)\n feed_t = array_ops.placeholder(dtype=dtypes.string, shape=shape)\n c = array_ops.identity(feed_t)\n self.assertAllEqual(sess.run(c, feed_dict={feed_t: c_list}), c_list)\n self.assertAllEqual(\n sess.run(feed_t, feed_dict={\n feed_t: c_list\n }), c_list)\n c_v, feed_v = sess.run([c, feed_t], feed_dict={feed_t: c_list})\n self.assertAllEqual(c_v, c_list)\n self.assertAllEqual(feed_v, c_list)\n\n def testStringFeedWithNullCharacters(self):\n with session.Session():\n c_list = [b'\\n\\x01\\x00', b'\\n\\x00\\x01']\n feed_t = array_ops.placeholder(dtype=dtypes.string, shape=[2])\n c = array_ops.identity(feed_t)\n out = c.eval(feed_dict={feed_t: c_list})\n self.assertEqual(c_list[0], out[0])\n self.assertEqual(c_list[1], out[1])\n\n def testStringFeedWithUnicode(self):\n with session.Session():\n c_list = [\n u'\\n\\x01\\x00', u'\\n\\x00\\x01', u'\\u26a3 unicode',\n u'\\U0001f60e deal with it'\n ]\n feed_t = array_ops.placeholder(dtype=dtypes.string, shape=[len(c_list)])\n c = array_ops.identity(feed_t)\n\n out = c.eval(feed_dict={feed_t: c_list})\n for i in range(len(c_list)):\n self.assertEqual(c_list[i], out[i].decode('utf-8'))\n\n out = c.eval(feed_dict={feed_t: np.array(c_list, dtype=np.object)})\n for i in range(len(c_list)):\n self.assertEqual(c_list[i], out[i].decode('utf-8'))\n\n def testInvalidTargetFails(self):\n with self.assertRaisesRegexp(\n errors.NotFoundError,\n 'No session factory registered for the given session options'):\n session.Session('INVALID_TARGET')\n\n def testFetchByNameDifferentStringTypes(self):\n with session.Session() as sess:\n c = constant_op.constant(42.0, name='c')\n d = constant_op.constant(43.0, name=u'd')\n e = constant_op.constant(44.0, name=b'e')\n f = constant_op.constant(45.0, name=r'f')\n\n self.assertTrue(isinstance(c.name, six.text_type))\n self.assertTrue(isinstance(d.name, six.text_type))\n self.assertTrue(isinstance(e.name, six.text_type))\n self.assertTrue(isinstance(f.name, six.text_type))\n\n self.assertEqual(42.0, sess.run('c:0'))\n self.assertEqual(42.0, sess.run(u'c:0'))\n self.assertEqual(42.0, sess.run(b'c:0'))\n self.assertEqual(42.0, sess.run(r'c:0'))\n\n self.assertEqual(43.0, sess.run('d:0'))\n self.assertEqual(43.0, sess.run(u'd:0'))\n self.assertEqual(43.0, sess.run(b'd:0'))\n self.assertEqual(43.0, sess.run(r'd:0'))\n\n self.assertEqual(44.0, sess.run('e:0'))\n self.assertEqual(44.0, sess.run(u'e:0'))\n self.assertEqual(44.0, sess.run(b'e:0'))\n self.assertEqual(44.0, sess.run(r'e:0'))\n\n self.assertEqual(45.0, sess.run('f:0'))\n self.assertEqual(45.0, sess.run(u'f:0'))\n self.assertEqual(45.0, sess.run(b'f:0'))\n self.assertEqual(45.0, sess.run(r'f:0'))\n\n def testIncorrectGraph(self):\n with ops.Graph().as_default() as g_1:\n c_1 = constant_op.constant(1.0, name='c')\n\n with ops.Graph().as_default() as g_2:\n c_2 = constant_op.constant(2.0, name='c')\n\n self.assertEqual('c', c_1.op.name)\n self.assertEqual('c', c_2.op.name)\n\n with session.Session(graph=g_1) as sess_1:\n self.assertEqual(1.0, sess_1.run(c_1))\n with self.assertRaises(ValueError):\n sess_1.run(c_2)\n with self.assertRaises(ValueError):\n sess_1.run(c_2.op)\n\n with session.Session(graph=g_2) as sess_2:\n with self.assertRaises(ValueError):\n sess_2.run(c_1)\n with self.assertRaises(ValueError):\n sess_2.run(c_1.op)\n self.assertEqual(2.0, sess_2.run(c_2))\n\n def testFeedDictKeyException(self):\n with session.Session() as sess:\n a = constant_op.constant(1.0, dtypes.float32, name='a')\n with self.assertRaisesRegexp(TypeError, 'Cannot interpret feed_dict'):\n sess.run(a, feed_dict={'a': [2.0]})\n\n def testPerStepTrace(self):\n run_options = config_pb2.RunOptions(\n trace_level=config_pb2.RunOptions.SOFTWARE_TRACE)\n run_metadata = config_pb2.RunMetadata()\n\n with ops.device('/cpu:0'):\n with session.Session() as sess:\n sess.run(constant_op.constant(1.0))\n self.assertTrue(not run_metadata.HasField('step_stats'))\n\n sess.run(constant_op.constant(1.0), run_metadata=run_metadata)\n self.assertTrue(not run_metadata.HasField('step_stats'))\n\n sess.run(\n constant_op.constant(1.0),\n options=run_options,\n run_metadata=run_metadata)\n\n self.assertTrue(run_metadata.HasField('step_stats'))\n self.assertEqual(len(run_metadata.step_stats.dev_stats), 1)\n\n def testRunOptionsRunMetadata(self):\n run_options = config_pb2.RunOptions(\n trace_level=config_pb2.RunOptions.SOFTWARE_TRACE)\n run_metadata = config_pb2.RunMetadata()\n\n with ops.device('/cpu:0'):\n with session.Session() as sess:\n # all combinations are valid\n sess.run(constant_op.constant(1.0), options=None, run_metadata=None)\n sess.run(\n constant_op.constant(1.0), options=None, run_metadata=run_metadata)\n self.assertTrue(not run_metadata.HasField('step_stats'))\n\n sess.run(\n constant_op.constant(1.0), options=run_options, run_metadata=None)\n self.assertTrue(not run_metadata.HasField('step_stats'))\n\n sess.run(\n constant_op.constant(1.0),\n options=run_options,\n run_metadata=run_metadata)\n\n self.assertTrue(run_metadata.HasField('step_stats'))\n self.assertEqual(len(run_metadata.step_stats.dev_stats), 1)\n\n def testFeedShapeCompatibility(self):\n with session.Session() as sess:\n some_tensor = constant_op.constant([2.0, 2.0, 2.0, 2.0])\n new_shape = constant_op.constant([2, 2])\n reshaped_tensor = array_ops.reshape(some_tensor, new_shape)\n\n with self.assertRaisesRegexp(ValueError, 'Cannot feed value of shape'):\n sess.run(reshaped_tensor, feed_dict={some_tensor: [1.0, 2.0, 3.0]})\n\n with self.assertRaisesRegexp(\n errors.InvalidArgumentError,\n 'Input to reshape is a tensor with 4 values, '\n 'but the requested shape has 21'):\n sess.run(reshaped_tensor, feed_dict={new_shape: [3, 7]})\n\n def testInferShapesFalse(self):\n with ops.Graph().as_default(), ops.device('/cpu:0'):\n a = constant_op.constant([[1, 2]])\n sess = session.Session()\n self.assertFalse('_output_shapes' in sess.graph_def.node[0].attr)\n # Avoid lint error regarding 'unused' var a.\n self.assertTrue(a == a)\n\n def testInferShapesTrue(self):\n config_pb = config_pb2.ConfigProto(\n graph_options=config_pb2.GraphOptions(infer_shapes=True))\n with ops.Graph().as_default(), ops.device('/cpu:0'):\n a = constant_op.constant([[1, 2]])\n sess = session.Session(config=config_pb)\n self.assertTrue('_output_shapes' in sess.graph_def.node[0].attr)\n # Avoid lint error regarding 'unused' var a.\n self.assertTrue(a == a)\n\n def testBuildCostModel(self):\n run_options = config_pb2.RunOptions()\n config_pb = config_pb2.ConfigProto(\n allow_soft_placement=True,\n graph_options=config_pb2.GraphOptions(build_cost_model=100))\n with session.Session(config=config_pb) as sess:\n with ops.device('/device:GPU:0'):\n a = array_ops.placeholder(dtypes.float32, shape=[])\n b = math_ops.add(a, a)\n c = array_ops.identity(b)\n d = math_ops.multiply(c, c)\n for step in xrange(120):\n run_metadata = config_pb2.RunMetadata()\n sess.run(\n d,\n feed_dict={a: 1.0},\n options=run_options,\n run_metadata=run_metadata)\n if step == 99:\n self.assertTrue(run_metadata.HasField('cost_graph'))\n else:\n self.assertFalse(run_metadata.HasField('cost_graph'))\n\n def runTestOutputPartitionGraphs(self, sess):\n run_options = config_pb2.RunOptions(output_partition_graphs=True)\n a = constant_op.constant(1)\n run_metadata = config_pb2.RunMetadata()\n sess.run(a, options=run_options, run_metadata=run_metadata)\n self.assertGreater(len(run_metadata.partition_graphs), 0)\n sess.run(a, run_metadata=run_metadata)\n self.assertEqual(len(run_metadata.partition_graphs), 0)\n\n @test_util.run_v1_only('b/120545219')\n def testOutputPartitionGraphsDirect(self):\n self.runTestOutputPartitionGraphs(session.Session())\n\n @test_util.run_v1_only('b/120545219')\n def testOutputPartitionGraphsDistributed(self):\n server = server_lib.Server.create_local_server()\n self.runTestOutputPartitionGraphs(session.Session(server.target))\n\n def testNonInteractiveSessionNesting(self):\n sess1 = session.Session()\n sess1_controller = sess1.as_default()\n sess1_controller.__enter__()\n\n sess2 = session.Session()\n sess2_controller = sess2.as_default()\n sess2_controller.__enter__()\n\n with self.assertRaisesRegexp(AssertionError, 'Nesting violated'):\n sess1_controller.__exit__(None, None, None)\n\n ops._default_session_stack.reset()\n\n def testInteractiveSessionNesting(self):\n sess1 = session.InteractiveSession()\n sess2 = session.InteractiveSession()\n del sess1\n del sess2\n\n @test_util.run_v1_only('b/120545219')\n def testAsDefault(self):\n c = constant_op.constant(37)\n sess = session.Session()\n with sess.as_default():\n self.assertEqual(37, c.eval())\n\n # Ensure that the session remains valid even when it is not captured.\n with session.Session().as_default():\n self.assertEqual(37, c.eval())\n\n def testReentry(self):\n sess = session.Session()\n with self.assertRaisesRegexp(RuntimeError, 'not re-entrant'):\n with sess:\n with sess:\n pass\n\n def testInvalidArgument(self):\n with self.assertRaisesRegexp(TypeError, 'target must be a string'):\n session.Session(37)\n with self.assertRaisesRegexp(TypeError, 'config must be a tf.ConfigProto'):\n session.Session(config=37)\n with self.assertRaisesRegexp(TypeError, 'graph must be a tf.Graph'):\n session.Session(graph=37)\n\n @test_util.run_v1_only('b/120545219')\n def testTimeoutWithShortOperations(self):\n num_epochs = 5\n q = data_flow_ops.FIFOQueue(capacity=50, dtypes=[dtypes.int32], shapes=[()])\n enqueue_op = q.enqueue_many(constant_op.constant([1, 2]))\n\n # Use a 10-second timeout, which should be longer than any\n # non-blocking enqueue_many op.\n config_pb = config_pb2.ConfigProto(operation_timeout_in_ms=10000)\n with session.Session(config=config_pb) as sess:\n for _ in range(num_epochs):\n sess.run(enqueue_op)\n self.assertEqual(sess.run(q.size()), num_epochs * 2)\n\n @test_util.run_v1_only('b/120545219')\n def testRegisterFetchAndFeedConversionFunctions(self):\n\n class SquaredTensor(object):\n\n def __init__(self, tensor):\n self.sq = math_ops.square(tensor)\n\n fetch_fn = lambda squared_tensor: ([squared_tensor.sq], lambda val: val[0])\n feed_fn1 = lambda feed, feed_val: [(feed.sq, feed_val)]\n feed_fn2 = lambda feed: [feed.sq]\n\n session.register_session_run_conversion_functions(SquaredTensor, fetch_fn,\n feed_fn1, feed_fn2)\n with self.assertRaises(ValueError):\n session.register_session_run_conversion_functions(SquaredTensor, fetch_fn,\n feed_fn1, feed_fn2)\n with self.cached_session() as sess:\n np1 = np.array([1.0, 1.5, 2.0, 2.5])\n np2 = np.array([3.0, 3.5, 4.0, 4.5])\n squared_tensor = SquaredTensor(np2)\n squared_eval = sess.run(squared_tensor)\n self.assertAllClose(np2 * np2, squared_eval)\n squared_eval = sess.run(\n squared_tensor, feed_dict={\n squared_tensor: np1 * np1\n })\n self.assertAllClose(np1 * np1, squared_eval)\n partial_run = sess.partial_run_setup([squared_tensor], [])\n squared_eval = sess.partial_run(partial_run, squared_tensor)\n self.assertAllClose(np2 * np2, squared_eval)\n\n def testDefaultLogDevicePlacement(self):\n\n class CaptureStderr(str):\n \"\"\"Class to capture stderr from C++ shared library.\"\"\"\n\n def __enter__(self):\n self._esc = compat.as_str('\\b')\n self._output = compat.as_str('')\n self._stderr = sys.stderr\n self._fd = self._stderr.fileno()\n self._out_pipe, in_pipe = os.pipe()\n # Save the original io stream.\n self._dup_fd = os.dup(self._fd)\n # Replace the original io stream with in pipe.\n os.dup2(in_pipe, self._fd)\n return self\n\n def __exit__(self, *args):\n self._stderr.write(self._esc)\n self._stderr.flush()\n self.read()\n os.close(self._out_pipe)\n # Restore the original io stream.\n os.dup2(self._dup_fd, self._fd)\n\n def read(self):\n while True:\n data = os.read(self._out_pipe, 1)\n if not data or compat.as_str(data) == self._esc:\n break\n self._output += compat.as_str(data)\n\n def __str__(self):\n return self._output\n\n if context.executing_eagerly():\n context.set_log_device_placement(True)\n with CaptureStderr() as log:\n a = constant_op.constant(1)\n b = constant_op.constant(2)\n c = a + b\n # Ensure if the same kernel with the same arguments is executed then its\n # execution is logged.\n d = a + b\n else:\n # Passing the config to the server, but not the session should still\n # result in logging device placement.\n config_pb = config_pb2.ConfigProto(log_device_placement=True)\n server = server_lib.Server.create_local_server(config=config_pb)\n a = constant_op.constant(1)\n b = constant_op.constant(2)\n c = a + b\n d = a + b\n with session.Session(server.target) as sess:\n with CaptureStderr() as log:\n c, d = sess.run([c, d])\n\n self.assertEqual(c, 3)\n self.assertEqual(d, 3)\n # Ensure that we did log device placement.\n add_executions = [l for l in str(log).splitlines() if 'AddV2' in l]\n self.assertEqual(len(add_executions), 2)\n\n @test_util.run_v1_only('b/120545219')\n def testLocalMasterSessionTimeout(self):\n # Test that the timeout passed in a config to the session works correctly.\n config_pb = config_pb2.ConfigProto(operation_timeout_in_ms=1000)\n server = server_lib.Server.create_local_server()\n q = data_flow_ops.FIFOQueue(1, dtypes.float32)\n dequeued_t = q.dequeue()\n\n with session.Session(server.target, config=config_pb) as sess:\n # Intentionally do not run any enqueue_ops so that dequeue will block\n # until operation_timeout_in_ms.\n with self.assertRaises(errors.DeadlineExceededError):\n sess.run(dequeued_t)\n\n @test_util.run_v1_only('b/120545219')\n def testDefaultServerTimeout(self):\n # Test that the default server config timeout gets used when no Session\n # config is provided.\n config_pb = config_pb2.ConfigProto(operation_timeout_in_ms=1000)\n server = server_lib.Server.create_local_server(config=config_pb)\n q = data_flow_ops.FIFOQueue(1, dtypes.float32)\n dequeued_t = q.dequeue()\n\n with session.Session(server.target) as sess:\n # Intentionally do not run any enqueue_ops so that dequeue will block\n # until operation_timeout_in_ms.\n with self.assertRaises(errors.DeadlineExceededError):\n sess.run(dequeued_t)\n\n def runTestBuildGraphError(self, sess):\n # Ensure that errors from building the graph get propagated.\n data = array_ops.placeholder(dtypes.float32, shape=[])\n # pylint: disable=protected-access\n enter_1 = gen_control_flow_ops.enter(data, 'foo_1', False)\n enter_2 = gen_control_flow_ops.enter(data, 'foo_2', False)\n # pylint: enable=protected-access\n res = math_ops.add(enter_1, enter_2)\n with self.assertRaisesOpError('has inputs from different frames'):\n sess.run(res, feed_dict={data: 1.0})\n\n @test_util.run_v1_only('b/120545219')\n def testBuildGraphErrorDirect(self):\n self.runTestBuildGraphError(session.Session())\n\n @test_util.run_v1_only('b/120545219')\n def testBuildGraphErrorDist(self):\n server = server_lib.Server.create_local_server()\n self.runTestBuildGraphError(session.Session(server.target))\n\n def testDeviceAttributes(self):\n attrs = session._DeviceAttributes(\n '/job:worker/replica:0/task:3/device:CPU:2', 'TYPE', 1337, 1000000)\n self.assertEqual(1337, attrs.memory_limit_bytes)\n self.assertEqual('/job:worker/replica:0/task:3/device:CPU:2', attrs.name)\n self.assertEqual('TYPE', attrs.device_type)\n self.assertEqual(1000000, attrs.incarnation)\n str_repr = '%s' % attrs\n self.assertTrue(str_repr.startswith('_DeviceAttributes'), str_repr)\n\n def testDeviceAttributesCanonicalization(self):\n attrs = session._DeviceAttributes('/job:worker/replica:0/task:3/cpu:1',\n 'TYPE', 1337, 1000000)\n self.assertEqual(1337, attrs.memory_limit_bytes)\n self.assertEqual('/job:worker/replica:0/task:3/device:CPU:1', attrs.name)\n self.assertEqual('TYPE', attrs.device_type)\n self.assertEqual(1000000, attrs.incarnation)\n str_repr = '%s' % attrs\n self.assertTrue(str_repr.startswith('_DeviceAttributes'), str_repr)\n\n def runTestAddFunctionToSession(self, target=''):\n \"\"\"Add a function to a session after the graph has already been run.\"\"\"\n\n @function.Defun(dtypes.float32)\n def foo(x):\n return x + 1\n\n x = constant_op.constant(1.0)\n with session.Session(target=target) as sess:\n sess.run(x)\n f = foo(x)\n result = sess.run(f)\n self.assertEqual(result, 2.0)\n\n @test_util.run_v1_only('b/120545219')\n def testAddFunctionToSession(self):\n self.runTestAddFunctionToSession()\n\n @test_util.run_v1_only('b/120545219')\n def testAddFunctionToGrpcSession(self):\n server = server_lib.Server.create_local_server()\n self.runTestAddFunctionToSession(server.target)\n\n def testOpenAndCloseGrpcSession(self):\n server = server_lib.Server.create_local_server()\n with session.Session(server.target):\n pass\n\n def testOpenAndCloseSession(self):\n with session.Session():\n pass\n\n @test_util.run_v1_only('b/120545219')\n def testAutoConvertAndCheckData(self):\n with self.cached_session() as sess:\n a = array_ops.placeholder(dtype=dtypes.string)\n with self.assertRaisesRegexp(\n TypeError, r'Type of feed value 1 with type <(\\w+) \\'int\\'> is not'):\n sess.run(a, feed_dict={a: 1})\n\n @test_util.run_v1_only('b/120545219')\n def testOptimizerOptions(self):\n config.set_optimizer_experimental_options({'min_graph_nodes': -1})\n\n with ops.Graph().as_default():\n sess = session.Session()\n self.assertEqual(\n sess._config.graph_options.rewrite_options.min_graph_nodes, -1)\n\n\nif __name__ == '__main__':\n googletest.main()\n", "# Lint as: python3\n# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for control_flow module.\"\"\"\n\n# Unfortunately pylint has false positives when nonlocal is present.\n# pylint:disable=unused-variable\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport re\nimport sys\n\nimport numpy as np\nimport six\n\nfrom tensorflow.python.autograph.operators import control_flow\nfrom tensorflow.python.autograph.operators import variables as variable_operators\nfrom tensorflow.python.autograph.utils import ag_logging\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import func_graph\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gen_math_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.ops.ragged import ragged_factory_ops\nfrom tensorflow.python.platform import test\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass ForLoopTest(test.TestCase):\n\n def test_tensor(self):\n def body(i):\n nonlocal s\n s = s * 10 + i\n\n def set_state(loop_vars):\n nonlocal s\n s, = loop_vars\n\n s = 0\n control_flow.for_stmt(\n constant_op.constant([1, 2, 3, 4]),\n extra_test=lambda: True,\n body=body,\n get_state=lambda: (s,),\n set_state=set_state,\n symbol_names=('s',),\n opts={})\n self.assertEqual(self.evaluate(s), (1234,))\n\n def test_range_tensor(self):\n def body(i):\n nonlocal s\n s = s * 10 + i\n\n def set_state(loop_vars):\n nonlocal s\n s, = loop_vars\n\n s = 0\n control_flow.for_stmt(\n math_ops.range(5),\n extra_test=lambda: True,\n body=body,\n get_state=lambda: (s,),\n set_state=set_state,\n symbol_names=('s',),\n opts={'iterate_names': 'i'})\n self.assertEqual(self.evaluate(s), (1234,))\n\n def test_range_tensor_explicit_limit_delta(self):\n def body(i):\n nonlocal s\n s = s * 100 + i\n\n def set_state(loop_vars):\n nonlocal s\n s, = loop_vars\n\n s = 0\n control_flow.for_stmt(\n math_ops.range(-17, -3, 5),\n extra_test=lambda: True,\n body=body,\n get_state=lambda: (s,),\n set_state=set_state,\n symbol_names=('s',),\n opts={'iterate_names': 'i'})\n self.assertEqual(self.evaluate(s), (-171207,))\n\n def test_range_tensor_explicit_limit_negative_delta(self):\n def body(i):\n nonlocal s\n s = s * 100 + i\n\n def set_state(loop_vars):\n nonlocal s\n s, = loop_vars\n\n s = 0\n control_flow.for_stmt(\n math_ops.range(17, 3, -5),\n extra_test=lambda: True,\n body=body,\n get_state=lambda: (s,),\n set_state=set_state,\n symbol_names=('s',),\n opts={'iterate_names': 'i'})\n self.assertEqual(self.evaluate(s), (171207,))\n\n def test_range_tensor_random_delta(self):\n def body(i):\n nonlocal s\n s = s * 10 + i\n\n def set_state(loop_vars):\n nonlocal s\n s, = loop_vars\n\n s = 0\n random_one = random_ops.random_uniform((), 1, 2, dtype=dtypes.int32)\n control_flow.for_stmt(\n math_ops.range(0, 5, random_one),\n extra_test=lambda: True,\n body=body,\n get_state=lambda: (s,),\n set_state=set_state,\n symbol_names=('s',),\n opts={'iterate_names': 'i'})\n self.assertEqual(self.evaluate(s), (1234,))\n\n def test_range_tensor_random_negative_delta(self):\n def body(i):\n nonlocal s\n s = s * 100 + i\n\n def set_state(loop_vars):\n nonlocal s\n s, = loop_vars\n\n s = 0\n random_neg_five = random_ops.random_uniform((), -5, -4, dtype=dtypes.int32)\n control_flow.for_stmt(\n math_ops.range(17, 3, random_neg_five),\n extra_test=lambda: True,\n body=body,\n get_state=lambda: (s,),\n set_state=set_state,\n symbol_names=('s',),\n opts={'iterate_names': 'i'})\n self.assertEqual(self.evaluate(s), (171207,))\n\n def test_tensor_with_extra_test_object_vars(self):\n class MutableObject(object):\n field_1 = constant_op.constant(0, dtype=dtypes.int32)\n field_2 = constant_op.constant(1, dtype=dtypes.int32)\n state = MutableObject()\n\n def body(i):\n state.field_1 += i\n state.field_2 *= i\n\n def get_state():\n return state.field_1, state.field_2\n\n def set_state(loop_vars):\n state.field_1, state.field_2 = loop_vars\n\n control_flow.for_stmt(\n iter_=constant_op.constant([1, 2, 3, 4]),\n body=body,\n extra_test=lambda: state.field_1 < 6,\n get_state=get_state,\n set_state=set_state,\n symbol_names=('state.field_1', 'state.field_2'),\n opts={})\n self.assertEqual(self.evaluate((state.field_1, state.field_2)), (6, 6))\n\n def test_python(self):\n def body(i):\n nonlocal s\n s = s * 10 + i\n\n def set_state(loop_vars):\n nonlocal s\n s, = loop_vars\n\n s = 0\n control_flow.for_stmt(\n range(5),\n extra_test=lambda: True,\n body=body,\n get_state=lambda: (s,),\n set_state=set_state,\n symbol_names=('s',),\n opts={})\n self.assertEqual(s, 1234)\n\n def test_python_generator_with_extra_test(self):\n def new_generator():\n for i in range(1, 5):\n yield i\n\n gen = new_generator()\n def run_loop():\n s = 0\n c = 0\n\n def body(i):\n nonlocal s, c\n s = s * 10 + i\n c += 1\n\n control_flow.for_stmt(\n gen,\n extra_test=lambda: c == 0, # Break after first iteration\n body=body,\n get_state=None,\n set_state=None,\n symbol_names=('s', 'c'),\n opts={})\n return s, c\n\n self.assertEqual(run_loop(), (1, 1))\n self.assertEqual(run_loop(), (2, 1))\n self.assertEqual(run_loop(), (3, 1))\n\n self.assertEqual(next(gen), 4)\n\n def test_python_generator_with_extra_test_no_iterations(self):\n def new_generator():\n for i in range(5):\n yield i\n\n gen = new_generator()\n def run_loop():\n s = 0\n\n def body(i):\n nonlocal s\n s = s * 10 + i\n\n control_flow.for_stmt(\n gen,\n extra_test=lambda: False, # Break before loop\n body=body,\n get_state=None,\n set_state=None,\n symbol_names=('s',),\n opts={})\n return s\n\n self.assertEqual(run_loop(), 0)\n self.assertEqual(run_loop(), 0)\n\n self.assertEqual(next(gen), 0)\n\n def test_tf_dataset(self):\n def body(i):\n nonlocal s\n s = s * 10 + i\n\n def set_state(loop_vars):\n nonlocal s\n s, = loop_vars\n\n s = constant_op.constant(0, dtype=dtypes.int64)\n control_flow.for_stmt(\n dataset_ops.Dataset.range(5),\n extra_test=None,\n body=body,\n get_state=lambda: (s,),\n set_state=set_state,\n symbol_names=('s',),\n opts={})\n self.assertEqual(self.evaluate(s), (1234,))\n\n def test_dataset_with_extra_test(self):\n def body(i):\n nonlocal s\n s = s * 10 + i\n\n def set_state(loop_vars):\n nonlocal s\n s, = loop_vars\n\n s = constant_op.constant(0, dtype=dtypes.int64)\n control_flow.for_stmt(\n dataset_ops.Dataset.range(5),\n extra_test=lambda: s < 3,\n body=body,\n get_state=lambda: (s,),\n set_state=set_state,\n symbol_names=('s',),\n opts={})\n self.assertEqual(self.evaluate(s), (12,))\n\n def test_dataset_with_extra_test_collection_vars(self):\n def body(i):\n nonlocal s\n l[0] += i\n s += i\n\n def set_state(loop_vars):\n nonlocal s\n l[0], s = loop_vars\n\n s = constant_op.constant(0, dtype=dtypes.int64)\n l = [constant_op.constant(0, dtype=dtypes.int64)]\n control_flow.for_stmt(\n dataset_ops.Dataset.range(5),\n extra_test=lambda: s < 3,\n body=body,\n get_state=lambda: (l[0], s),\n set_state=set_state,\n symbol_names=('l[0]', 's'),\n opts={})\n self.assertEqual(self.evaluate((l[0], s)), (3, 3))\n\n def test_dataset_with_extra_test_iteration_limiting(self):\n def body(it):\n nonlocal i\n with ops.control_dependencies((control_flow_ops.Assert(i < 3, (i,)),)):\n i = it\n\n def set_state(loop_vars):\n nonlocal i\n i, = loop_vars\n\n i = constant_op.constant(0, dtype=dtypes.int64)\n control_flow.for_stmt(\n dataset_ops.Dataset.range(5),\n extra_test=lambda: i < 3,\n body=body,\n get_state=lambda: (i,),\n set_state=set_state,\n symbol_names=('i',),\n opts={})\n self.assertEqual(self.evaluate(i), (3,))\n\n def test_tf_dataset_no_loop_vars(self):\n def body(i):\n v.assign(v.read_value() * 10 + i)\n\n v = variables.Variable(0, dtype=dtypes.int64)\n self.evaluate(v.initializer)\n\n # tf.function required for the automatic control dependencies, and because\n # ops test for its presence.\n @def_function.function\n def test_fn():\n control_flow.for_stmt(\n dataset_ops.Dataset.range(5),\n extra_test=None,\n body=body,\n get_state=lambda: (),\n set_state=lambda _: None,\n symbol_names=(),\n opts={})\n\n self.evaluate(test_fn())\n self.assertEqual(self.evaluate(v.read_value()), 1234)\n\n def test_tf_iterator(self):\n # graph-mode iterators are only supported inside tf.function.\n @def_function.function\n def test_fn():\n def body(i):\n nonlocal s\n s = s * 10 + i\n\n def set_state(loop_vars):\n nonlocal s\n s, = loop_vars\n\n s = constant_op.constant(0, dtype=dtypes.int64)\n control_flow.for_stmt(\n iter(dataset_ops.Dataset.range(5)),\n extra_test=None,\n body=body,\n get_state=lambda: (s,),\n set_state=set_state,\n symbol_names=('s',),\n opts={})\n return s\n self.assertAllEqual(test_fn(), 1234)\n\n def test_tf_iterator_shape_invariants(self):\n # graph-mode iterators are only supported inside tf.function.\n @def_function.function\n def test_fn():\n def body(i):\n nonlocal s\n s = array_ops.concat([s, [i]], 0)\n\n def set_state(loop_vars):\n nonlocal s\n s, = loop_vars\n\n s = constant_op.constant([], dtype=dtypes.int64)\n control_flow.for_stmt(\n iter(dataset_ops.Dataset.range(5)),\n extra_test=None,\n body=body,\n get_state=lambda: (s,),\n set_state=set_state,\n symbol_names=('s',),\n opts={'shape_invariants': [(s, tensor_shape.TensorShape([None]))]})\n return s\n self.assertAllEqual(test_fn(), [0, 1, 2, 3, 4])\n\n def test_tf_iterator_no_loop_vars(self):\n def body(i):\n v.assign(v.read_value() * 10 + i)\n\n v = variables.Variable(0, dtype=dtypes.int64)\n self.evaluate(v.initializer)\n\n # tf.function required for the automatic control dependencies.\n @def_function.function\n def test_fn():\n control_flow.for_stmt(\n iter(dataset_ops.Dataset.range(5)),\n extra_test=None,\n body=body,\n get_state=lambda: (),\n set_state=lambda _: None,\n symbol_names=(),\n opts={})\n\n self.evaluate(test_fn())\n self.assertEqual(self.evaluate(v.read_value()), 1234)\n\n def test_tf_ragged_tensor(self):\n def body(i):\n nonlocal s\n s = s * 10 + i[0]\n\n def set_state(loop_vars):\n nonlocal s\n s, = loop_vars\n\n s = 0\n control_flow.for_stmt(\n ragged_factory_ops.constant([[1], [2, 4], [3]]),\n extra_test=None,\n body=body,\n get_state=lambda: (s,),\n set_state=set_state,\n symbol_names=('s',),\n opts={})\n self.assertEqual(self.evaluate(s), (123,))\n\n def test_tf_ragged_tensor_higher_dimensional(self):\n def body(i):\n nonlocal s\n s = s * 10 + i[0][0]\n\n def set_state(loop_vars):\n nonlocal s\n s, = loop_vars\n\n s = 0\n ragged_3d = [\n [[1], [1, 1], [1]],\n [[2], [2]],\n ]\n control_flow.for_stmt(\n ragged_factory_ops.constant(ragged_3d),\n extra_test=None,\n body=body,\n get_state=lambda: (s,),\n set_state=set_state,\n symbol_names=('s',),\n opts={})\n self.assertEqual(self.evaluate(s), (12,))\n\n def test_tf_ragged_tensor_no_loop_vars(self):\n v = variables.Variable(0, dtype=dtypes.int32)\n self.evaluate(v.initializer)\n\n def body(i):\n v.assign(v.read_value() * 10 + i[0])\n\n # tf.function required for the automatic control dependencies.\n @def_function.function(autograph=False)\n def test_fn():\n control_flow.for_stmt(\n ragged_factory_ops.constant([[1], [2, 4], [3]]),\n extra_test=None,\n body=body,\n get_state=lambda: (),\n set_state=lambda _: None,\n symbol_names=(),\n opts={})\n\n self.evaluate(test_fn())\n # Note: 123 = ((0*10 + 1)*10+2)*10+3 (first element of each row).\n self.assertEqual(self.evaluate(v.read_value()), 123)\n\n def _basic_loop(self, init_value, body_fn):\n def body(i):\n nonlocal s\n s = body_fn(i, s)\n\n def set_state(loop_vars):\n nonlocal s\n s, = loop_vars\n\n s = init_value\n control_flow.for_stmt(\n constant_op.constant([1, 2, 3, 4]),\n extra_test=lambda: True,\n body=body,\n get_state=lambda: (s,),\n set_state=set_state,\n symbol_names=('s',),\n opts={})\n return s\n\n def test_tensor_illegal_input(self):\n with self.assertRaisesRegex(ValueError, '\"s\" may not be None'):\n self._basic_loop(None, lambda i, s: s)\n with self.assertRaisesRegex(ValueError, '\"s\" must be defined'):\n self._basic_loop(variable_operators.Undefined(''), lambda i, s: s)\n\n def test_tensor_none_output(self):\n with self.assertRaisesRegex(ValueError, '\"s\" is None at the end'):\n self._basic_loop(0, lambda i, s: None)\n\n def test_tensor_dtype_change(self):\n with self.assertRaisesRegex(TypeError, '\"s\".* dtype float32 after'):\n self._basic_loop(0, lambda i, s: 1.0)\n\n def test_tensor_shape_change(self):\n with self.assertRaisesRegex(ValueError, r'\"s\".* shape \\(1,\\) after'):\n self._basic_loop(0, lambda i, s: np.array([1], dtype=np.int32))\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass WhileLoopTest(test.TestCase):\n\n def test_tensor(self):\n def body():\n nonlocal i, s\n s = s * 10 + i\n i += 1\n\n def set_state(loop_vars):\n nonlocal i, s\n i, s = loop_vars\n\n i = 0\n n = constant_op.constant(5)\n s = 0\n control_flow.while_stmt(\n test=lambda: i < n,\n body=body,\n get_state=lambda: (i, s),\n set_state=set_state,\n symbol_names=('i', 's'),\n opts={})\n self.assertEqual(self.evaluate((i, s)), (5, 1234))\n\n def test_tensor_with_side_effecting_condition(self):\n v = variables.Variable(0)\n\n # tf.function required for the automatic control dependencies.\n @def_function.function\n def test_fn():\n def cond():\n v.assign(v.read_value() * 10 + i)\n return i < n\n\n def body():\n nonlocal i\n i += 1\n\n def set_state(loop_vars):\n nonlocal i\n i, = loop_vars\n\n i = 0\n n = constant_op.constant(5)\n control_flow.while_stmt(\n test=cond,\n body=body,\n get_state=lambda: (i,),\n set_state=set_state,\n symbol_names=('i',),\n opts={})\n return i\n\n self.evaluate(v.initializer)\n self.assertEqual(self.evaluate(test_fn()), (5,))\n self.assertEqual(self.evaluate(v), (12345,))\n\n def test_tensor_with_python_state(self):\n class MutableObject(object):\n field = constant_op.constant(0, dtype=dtypes.int32)\n state = MutableObject()\n\n def body():\n nonlocal i\n state.field = state.field * 10 + i\n i += 1\n\n def set_state(loop_vars):\n nonlocal i\n i, state.field = loop_vars\n\n i = 0\n n = constant_op.constant(5)\n control_flow.while_stmt(\n test=lambda: i < n,\n body=body,\n get_state=lambda: (i, state.field),\n set_state=set_state,\n symbol_names=('i', 'state.field'),\n opts={})\n self.assertEqual(self.evaluate((i, state.field)), (5, 1234))\n\n def test_python(self):\n def body():\n nonlocal i, s\n s = s * 10 + i\n i += 1\n\n i = 0\n s = 0\n n = 5\n control_flow.while_stmt(\n test=lambda: i < n,\n body=body,\n get_state=None,\n set_state=None,\n symbol_names=('i', 's'),\n opts={})\n self.assertEqual(s, 1234)\n\n def test_python_with_tensor_state(self):\n def body():\n nonlocal i, s\n s = s * 10 + i\n i += 1\n\n i = 0\n s = constant_op.constant(0)\n n = 5\n control_flow.while_stmt(\n test=lambda: i < n,\n body=body,\n get_state=None,\n set_state=None,\n symbol_names=('i', 's'),\n opts={})\n self.assertEqual(i, 5)\n self.assertEqual(self.evaluate(s), 1234)\n\n def test_python_while_infinite(self):\n if not __debug__:\n self.skipTest('Feature disabled in optimized mode.')\n with test.mock.patch.object(control_flow, 'PYTHON_MAX_ITERATIONS', 100):\n with self.assertRaisesRegexp(ValueError, 'iteration limit'):\n control_flow.while_stmt(\n test=lambda: True,\n body=lambda: None,\n get_state=None,\n set_state=None,\n symbol_names=(),\n opts={})\n\n def test_python_for_infinite(self):\n if not __debug__:\n self.skipTest('Feature disabled in optimized mode.')\n with test.mock.patch.object(control_flow, 'PYTHON_MAX_ITERATIONS', 100):\n with self.assertRaisesRegexp(ValueError, 'iteration limit'):\n control_flow.for_stmt(\n iter_=range(101),\n extra_test=None,\n body=lambda i: None,\n get_state=None,\n set_state=None,\n symbol_names=(),\n opts={})\n\n def test_python_while_large_unroll_warning(self):\n if not __debug__:\n self.skipTest('Feature disabled in optimized mode.')\n with test.mock.patch.object(\n control_flow, 'INEFFICIENT_UNROLL_MIN_ITERATIONS', 10):\n with ops.Graph().as_default():\n out_capturer = six.StringIO()\n with test.mock.patch.object(sys, 'stdout', out_capturer):\n with test.mock.patch.object(ag_logging, 'echo_log_to_stdout', True):\n def custom_iterator():\n for i in range(11):\n c = constant_op.constant(i)\n yield c\n\n i = 0\n control_flow.for_stmt(\n iter_=custom_iterator(),\n extra_test=None,\n body=lambda i: None,\n get_state=None,\n set_state=None,\n symbol_names=(),\n opts={})\n self.assertTrue(re.match(\n r'.* Large unrolled loop.*Const.*', out_capturer.getvalue()))\n\n def test_python_for_large_unroll_warning(self):\n if not __debug__:\n self.skipTest('Feature disabled in optimized mode.')\n with test.mock.patch.object(\n control_flow, 'INEFFICIENT_UNROLL_MIN_ITERATIONS', 10):\n with ops.Graph().as_default():\n out_capturer = six.StringIO()\n with test.mock.patch.object(sys, 'stdout', out_capturer):\n with test.mock.patch.object(ag_logging, 'echo_log_to_stdout', True):\n def body():\n nonlocal i\n gen_math_ops.add(i, 1)\n i += 1\n\n i = 0\n control_flow.while_stmt(\n test=lambda: i < 100,\n body=body,\n get_state=None,\n set_state=None,\n symbol_names=('i',),\n opts={})\n self.assertTrue(re.match(\n r'.* Large unrolled loop.*Add.*', out_capturer.getvalue()))\n\n def _basic_loop(self, init_value, body_fn):\n def body():\n nonlocal i, s\n s = body_fn(i, s)\n i += 1\n\n def set_state(loop_vars):\n nonlocal i, s\n i, s = loop_vars\n\n i = 0\n n = constant_op.constant(5)\n s = init_value\n control_flow.while_stmt(\n test=lambda: i < n,\n body=body,\n get_state=lambda: (i, s),\n set_state=set_state,\n symbol_names=('i', 's'),\n opts={})\n return s\n\n def test_tensor_illegal_input(self):\n with self.assertRaisesRegex(ValueError, '\"s\" may not be None'):\n self._basic_loop(None, lambda i, s: s)\n with self.assertRaisesRegex(ValueError, '\"s\" must be defined'):\n self._basic_loop(variable_operators.Undefined(''), lambda i, s: s)\n\n def test_tensor_none_output(self):\n with self.assertRaisesRegex(ValueError, '\"s\" is None at the end'):\n self._basic_loop(0, lambda i, s: None)\n\n def test_tensor_dtype_change(self):\n with self.assertRaisesRegex(TypeError, '\"s\".* dtype float32 after'):\n self._basic_loop(0, lambda i, s: 1.0)\n\n def test_tensor_shape_change(self):\n with self.assertRaisesRegex(ValueError, r'\"s\".* shape \\(1,\\) after'):\n self._basic_loop(0, lambda i, s: np.array([1], dtype=np.int32))\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass IfStmtTest(test.TestCase):\n\n def test_tensor(self):\n\n def test_fn(cond):\n return control_flow.if_stmt(\n cond=cond,\n body=lambda: constant_op.constant(1),\n orelse=lambda: constant_op.constant(-1),\n get_state=lambda: (),\n set_state=lambda _: None,\n basic_symbol_names=('_',),\n composite_symbol_names=())\n\n self.assertEqual(1, self.evaluate(test_fn(constant_op.constant(True))))\n self.assertEqual(-1, self.evaluate(test_fn(constant_op.constant(False))))\n\n def test_tensor_multiple_returns(self):\n\n def test_fn(cond):\n return control_flow.if_stmt(\n cond=cond,\n body=lambda: (constant_op.constant(1), constant_op.constant(2)),\n orelse=lambda: (constant_op.constant(-1), constant_op.constant(-2)),\n get_state=lambda: (),\n set_state=lambda _: None,\n basic_symbol_names=('_',),\n composite_symbol_names=())\n\n self.assertEqual((1, 2), self.evaluate(test_fn(constant_op.constant(True))))\n self.assertEqual((-1, -2),\n self.evaluate(test_fn(constant_op.constant(False))))\n\n def test_python(self):\n\n def test_fn(cond):\n return control_flow.if_stmt(\n cond=cond,\n body=lambda: 1,\n orelse=lambda: -1,\n get_state=lambda: (),\n set_state=lambda _: None,\n basic_symbol_names=('_',),\n composite_symbol_names=())\n\n self.assertEqual(1, test_fn(True))\n self.assertEqual(-1, test_fn(False))\n\n def test_python_multiple_returns(self):\n\n def test_fn(cond):\n return control_flow.if_stmt(\n cond=cond,\n body=lambda: (1, 2),\n orelse=lambda: (-1, -2),\n get_state=lambda: (),\n set_state=lambda _: None,\n basic_symbol_names=('_',),\n composite_symbol_names=())\n\n self.assertEqual((1, 2), test_fn(True))\n self.assertEqual((-1, -2), test_fn(False))\n\n def _basic_cond(self, true_value, false_value):\n # Eager cond had different semantics, we don't test those here.\n with func_graph.FuncGraph('tmp').as_default():\n return control_flow.if_stmt(\n cond=constant_op.constant(True),\n body=true_value,\n orelse=false_value,\n get_state=lambda: (),\n set_state=lambda _: None,\n basic_symbol_names=('s',),\n composite_symbol_names=())\n\n def test_tensor_none_output(self):\n with self.assertRaisesRegex(\n ValueError, '\"s\" is None at the end of the TRUE branch'):\n self._basic_cond(lambda: None, lambda: 1)\n with self.assertRaisesRegex(\n ValueError, '\"s\" is None at the end of the FALSE branch'):\n self._basic_cond(lambda: 1, lambda: None)\n\n def test_tensor_undefined_output(self):\n with self.assertRaisesRegex(\n ValueError, \"must also be initialized in the if.*'s'\"):\n self._basic_cond(lambda: variable_operators.Undefined('s'), lambda: 1)\n with self.assertRaisesRegex(\n ValueError, \"must also be initialized in the else.*'s'\"):\n self._basic_cond(lambda: 1, lambda: variable_operators.Undefined('s'))\n\n def test_tensor_dtype_change(self):\n with self.assertRaisesRegex(TypeError, '\"s\" has dtype int32.*but.*float32'):\n self._basic_cond(lambda: 1, lambda: 1.0)\n\n\nif __name__ == '__main__':\n test.main()\n" ]
[ [ "tensorflow.core.protobuf.config_pb2.RunMetadata", "numpy.asarray", "tensorflow.python.ops.state_ops.assign_add", "tensorflow.core.protobuf.config_pb2.GraphOptions", "tensorflow.python.ops.control_flow_ops.while_loop", "tensorflow.core.protobuf.config_pb2.RunOptions", "tensorflow.python.client.session.InteractiveSession", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.ops.variables.Variable", "tensorflow.python.ops.array_ops.sparse_placeholder", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.framework.device.DeviceSpec.from_string", "numpy.iinfo", "tensorflow.python.framework.ops.device", "tensorflow.python.ops.state_ops.assign", "tensorflow.python.ops.control_flow_ops.no_op", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.ops.gradients_impl.gradients", "numpy.random.randint", "tensorflow.python.framework.sparse_tensor.SparseTensorValue", "tensorflow.python.framework.ops.IndexedSlicesValue", "tensorflow.python.framework.ops._default_session_stack.reset", "tensorflow.python.framework.test_util.run_v1_only", "tensorflow.python.framework.function.Defun", "tensorflow.python.framework.ops.IndexedSlices", "tensorflow.python.ops.gen_control_flow_ops.enter", "tensorflow.python.ops.math_ops.add", "tensorflow.python.framework.sparse_tensor.SparseTensor", "tensorflow.python.framework.tensor_util.constant_value", "tensorflow.python.platform.googletest.main", "numpy.float32", "tensorflow.python.util.compat.as_str", "tensorflow.python.ops.math_ops.matmul", "tensorflow.python.framework.importer.import_graph_def", "tensorflow.python.ops.math_ops.square", "tensorflow.python.framework.ops.colocate_with", "tensorflow.python.client.session.Session", "tensorflow.python.training.server_lib.Server.create_local_server", "tensorflow.python.ops.variables.VariableV1", "tensorflow.core.framework.attr_value_pb2.AttrValue", "numpy.array", "tensorflow.python.ops.data_flow_ops.FIFOQueue", "tensorflow.core.protobuf.config_pb2.CallableOptions", "tensorflow.python.eager.context.set_log_device_placement", "tensorflow.python.ops.control_flow_ops.group", "tensorflow.python.framework.ops._default_session_stack.get_default", "tensorflow.python.framework.ops.Graph", "tensorflow.python.client.session._DeviceAttributes", "numpy.ones", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.ops.array_ops.reshape", "tensorflow.python.ops.math_ops.multiply", "numpy.float64", "tensorflow.python.framework.config.set_optimizer_experimental_options", "tensorflow.python.framework.constant_op.constant", "tensorflow.core.protobuf.config_pb2.ConfigProto", "tensorflow.python.client.session.register_session_run_conversion_functions" ], [ "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.ops.variables.Variable", "tensorflow.python.autograph.operators.control_flow.if_stmt", "tensorflow.python.data.ops.dataset_ops.Dataset.range", "tensorflow.python.ops.control_flow_ops.Assert", "tensorflow.python.autograph.operators.control_flow.for_stmt", "tensorflow.python.autograph.operators.variables.Undefined", "tensorflow.python.platform.test.main", "tensorflow.python.autograph.operators.control_flow.while_stmt", "tensorflow.python.framework.func_graph.FuncGraph", "tensorflow.python.eager.def_function.function", "tensorflow.python.ops.ragged.ragged_factory_ops.constant", "tensorflow.python.ops.gen_math_ops.add", "numpy.array", "tensorflow.python.ops.math_ops.range", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.framework.ops.Graph", "tensorflow.python.platform.test.mock.patch.object", "tensorflow.python.ops.random_ops.random_uniform", "tensorflow.python.framework.constant_op.constant" ] ]
lukassnoek/3DDFA_V2
[ "4a37541cb1d21480aa4a70c82416fcfdc95eacd9" ]
[ "tddfa/utils/uv.py" ]
[ "# coding: utf-8\n\n__author__ = 'cleardusk'\n\nimport cv2\nimport numpy as np\nimport os.path as osp\nimport scipy.io as sio\n\nfrom ..Sim3DR import rasterize\nfrom .functions import plot_image\nfrom .io import _load\nfrom .tddfa_util import _to_ctype\n\nmake_abs_path = lambda fn: osp.join(osp.dirname(osp.realpath(__file__)), fn)\n\n\ndef load_uv_coords(fp):\n C = sio.loadmat(fp)\n uv_coords = C['UV'].copy(order='C').astype(np.float32)\n return uv_coords\n\n\ndef process_uv(uv_coords, uv_h=256, uv_w=256):\n uv_coords[:, 0] = uv_coords[:, 0] * (uv_w - 1)\n uv_coords[:, 1] = uv_coords[:, 1] * (uv_h - 1)\n uv_coords[:, 1] = uv_h - uv_coords[:, 1] - 1\n uv_coords = np.hstack((uv_coords, np.zeros((uv_coords.shape[0], 1), dtype=np.float32))) # add z\n return uv_coords\n\n\ng_uv_coords = load_uv_coords(make_abs_path('../configs/BFM_UV.mat'))\nindices = _load(make_abs_path('../configs/indices.npy')) # todo: handle bfm_slim\ng_uv_coords = g_uv_coords[indices, :]\n\n\ndef get_colors(img, ver):\n # nearest-neighbor sampling\n [h, w, _] = img.shape\n ver[0, :] = np.minimum(np.maximum(ver[0, :], 0), w - 1) # x\n ver[1, :] = np.minimum(np.maximum(ver[1, :], 0), h - 1) # y\n ind = np.round(ver).astype(np.int32)\n colors = img[ind[1, :], ind[0, :], :] # n x 3\n\n return colors\n\n\ndef bilinear_interpolate(img, x, y):\n \"\"\"\n https://stackoverflow.com/questions/12729228/simple-efficient-bilinear-interpolation-of-images-in-numpy-and-python\n \"\"\"\n x0 = np.floor(x).astype(np.int32)\n x1 = x0 + 1\n y0 = np.floor(y).astype(np.int32)\n y1 = y0 + 1\n\n x0 = np.clip(x0, 0, img.shape[1] - 1)\n x1 = np.clip(x1, 0, img.shape[1] - 1)\n y0 = np.clip(y0, 0, img.shape[0] - 1)\n y1 = np.clip(y1, 0, img.shape[0] - 1)\n\n i_a = img[y0, x0]\n i_b = img[y1, x0]\n i_c = img[y0, x1]\n i_d = img[y1, x1]\n\n wa = (x1 - x) * (y1 - y)\n wb = (x1 - x) * (y - y0)\n wc = (x - x0) * (y1 - y)\n wd = (x - x0) * (y - y0)\n\n return wa[..., np.newaxis] * i_a + wb[..., np.newaxis] * i_b + wc[..., np.newaxis] * i_c + wd[..., np.newaxis] * i_d\n\n\ndef uv_tex(img, ver_lst, tri, uv_h=256, uv_w=256, uv_c=3, show_flag=False, wfp=None):\n uv_coords = process_uv(g_uv_coords.copy(), uv_h=uv_h, uv_w=uv_w)\n\n res_lst = []\n for ver_ in ver_lst:\n ver = _to_ctype(ver_.T) # transpose to m x 3\n colors = bilinear_interpolate(img, ver[:, 0], ver[:, 1]) / 255.\n # `rasterize` here serves as texture sampling, may need to optimization\n res = rasterize(uv_coords, tri, colors, height=uv_h, width=uv_w, channel=uv_c)\n res_lst.append(res)\n\n # concat if there more than one image\n res = np.concatenate(res_lst, axis=1) if len(res_lst) > 1 else res_lst[0]\n\n if wfp is not None:\n cv2.imwrite(wfp, res)\n print(f'Save visualization result to {wfp}')\n\n if show_flag:\n plot_image(res)\n\n return res\n" ]
[ [ "numpy.maximum", "numpy.clip", "scipy.io.loadmat", "numpy.concatenate", "numpy.round", "numpy.floor", "numpy.zeros" ] ]
sdpython/pyensae
[ "ada4dbb0b9901bf481eff2ea239e74ed964d93b0" ]
[ "_unittests/ut_sql/test_database_df.py" ]
[ "\"\"\"\n@brief test log(time=10s)\n\nYou should indicate a time in seconds. The program ``run_unittests.py``\nwill sort all test files by increasing time and run them.\n\"\"\"\nimport os\nimport unittest\nimport pandas\nfrom pyquickhelper.loghelper import fLOG\nfrom pyensae.sql.database_main import Database\n\n\nclass TestDatabaseDF (unittest.TestCase):\n\n def test_import_df(self):\n fLOG(\n __file__,\n self._testMethodName,\n OutputPrint=__name__ == \"__main__\")\n dbf = os.path.join(\n os.path.abspath(\n os.path.split(__file__)[0]),\n \"temp_database_df.db3\")\n if os.path.exists(dbf):\n os.remove(dbf)\n\n values = [{\"name\": \"A\", \"age\": 10, \"score\": 34.5},\n {\"name\": \"B\", \"age\": 20, \"score\": -34.5}, ]\n df = pandas.DataFrame(values)\n df = df[['age', 'name', 'score']]\n db = Database.fill_sql_table(df, dbf, \"newtable\")\n db.execute_view(\"SELECT * FROM newtable\")\n df2 = db.to_df(\"SELECT * FROM newtable\")\n df3 = df2[[\"age\", \"name\", \"score\"]]\n self.assertGreater(len(df), 0)\n self.assertEqual(len(df3), len(df))\n for a, b in zip(df.values, df3.values):\n self.assertGreater(len(a), 0)\n self.assertEqual(len(a), len(b))\n for c, d in zip(a, b):\n self.assertEqual(c, d)\n db.close()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "pandas.DataFrame" ] ]
DanielKotik/Optical-beams-MEEP
[ "ca145119e5bd0f0804d846ea42e35e4c3daa91de" ]
[ "optbeam/_3d/helpers.py" ]
[ "\nimport sys\n\ntry:\n import cython\n cython_imported = True\nexcept ModuleNotFoundError:\n cython_imported = False\n\nif cython_imported:\n if cython.compiled:\n from scipy import LowLevelCallable\n else:\n print(\"\\nPlease consider compiling `%s.py` via Cython: \"\n \"`$ cythonize -3 -i %s.py`\\n\" % (__name__, __name__))\n\nfrom scipy.integrate import dblquad\nfrom types import MappingProxyType\n\n\ndef _real_2d_func(x, y, func):\n \"\"\"Return real part of a 2d function.\"\"\"\n return func(x, y).real\n\n\ndef _imag_2d_func(x, y, func):\n \"\"\"Return imag part of a 2d function.\"\"\"\n return func(x, y).imag\n\n\ndef _imag_2d_func_c(n, arr, func_ptr):\n \"\"\"Return imag part of a 2d function.\n\n Cython implementation.\n \"\"\"\n # pure python formulation of:\n # return (<Beam3d>func_ptr)(arr[0], arr[1]).imag\n return cython.cast(Beam3d, func_ptr)._integrand(arr[0], arr[1]).imag\n\n\ndef _real_2d_func_c(n, arr, func_ptr):\n \"\"\"Return real part of a 2d function.\n\n Cython implementation.\n \"\"\"\n # pure python formulation of:\n # return (<Beam3d>func_ptr)(arr[0], arr[1]).real\n return cython.cast(Beam3d, func_ptr)._integrand(arr[0], arr[1]).real\n\n\ndef _complex_dblquad(func, a, b, gfun, hfun, kwargs={}):\n \"\"\"Integrate real and imaginary part of the given function.\"\"\"\n if cython_imported and cython.compiled:\n # pure python formulation of: cdef void *f_ptr = <void*>func\n f_ptr = cython.declare(cython.p_void, cython.cast(cython.p_void, func))\n\n func_capsule = PyCapsule_New(f_ptr, cython.NULL, cython.NULL)\n\n current_module = sys.modules[__name__]\n\n ll_real_2d_func_c = LowLevelCallable.from_cython(current_module,\n '_real_2d_func_c',\n func_capsule)\n ll_imag_2d_func_c = LowLevelCallable.from_cython(current_module,\n '_imag_2d_func_c',\n func_capsule)\n real, real_tol = dblquad(ll_real_2d_func_c, a, b, gfun, hfun, **kwargs)\n imag, imag_tol = dblquad(ll_imag_2d_func_c, a, b, gfun, hfun, **kwargs)\n else:\n real, real_tol = dblquad(\n _real_2d_func, a, b, gfun, hfun, (func,), **kwargs)\n imag, imag_tol = dblquad(\n _imag_2d_func, a, b, gfun, hfun, (func,), **kwargs)\n\n return real + 1j*imag, real_tol, imag_tol\n\n\nclass Beam3d:\n \"\"\"Abstract base class.\"\"\"\n\n def __init__(self, x, params, called=False):\n \"\"\"...\"\"\"\n self.x = x # TODO: rename x to x_shift\n self._k = params['k']\n self._params = MappingProxyType(params) # read-only view of a dict\n self.called = called\n\n @property\n def params(self):\n \"\"\"Beam specific parameters.\n\n This is a read-only property.\n \"\"\"\n return self._params\n\n def _integrand(self, x, y):\n \"\"\"Integrand function over two coordinates x and y.\"\"\"\n raise NotImplementedError\n" ]
[ [ "scipy.LowLevelCallable.from_cython", "scipy.integrate.dblquad" ] ]
t3hseus/ariadne
[ "b4471a37741000e22281c4d6ff647d65ab9e1914", "b4471a37741000e22281c4d6ff647d65ab9e1914" ]
[ "ariadne/tracknet_v2/processor.py", "ariadne_v2/data_chunk.py" ]
[ "import logging\nimport os\nfrom typing import List, Tuple, Optional, Iterable\n\nimport gin\nimport pandas as pd\nimport numpy as np\n\nfrom ariadne.preprocessing import (\n BaseTransformer,\n DataProcessor,\n DataChunk,\n ProcessedDataChunk,\n ProcessedData\n)\n\nLOGGER = logging.getLogger('ariadne.prepare')\n\n\[email protected](denylist=['df_chunk_data'])\nclass TracknetDataChunk(DataChunk):\n def __init__(self, df_chunk_data: pd.DataFrame):\n super().__init__(df_chunk_data)\n\nclass ProcessedTracknetData(ProcessedData):\n def __init__(self,\n output_name: str,\n processed_data: List[ProcessedDataChunk]\n ):\n super().__init__(processed_data)\n self.processed_data = processed_data\n self.output_name = output_name\n\nclass ProcessedTracknetDataChunk(ProcessedDataChunk):\n def __init__(self,\n processed_object: Optional,\n output_name: str):\n super().__init__(processed_object)\n self.processed_object = processed_object\n self.output_name = output_name\n\[email protected](denylist=['data_df'])\nclass TrackNetProcessor(DataProcessor):\n def __init__(self,\n output_dir: str,\n data_df: pd.DataFrame,\n name_suffix: str,\n transforms: List[BaseTransformer] = None):\n super().__init__(\n processor_name='TrackNet_v2_Processor',\n output_dir=output_dir,\n data_df=data_df,\n transforms=transforms)\n self.output_name = os.path.join(self.output_dir, f'tracknet_{name_suffix}')\n\n def generate_chunks_iterable(self) -> Iterable[TracknetDataChunk]:\n return self.data_df.groupby('event')\n\n def construct_chunk(self,\n chunk_df: pd.DataFrame) -> TracknetDataChunk:\n processed = self.transformer(chunk_df)\n return TracknetDataChunk(processed)\n\n def preprocess_chunk(self,\n chunk: TracknetDataChunk,\n idx: str) -> ProcessedTracknetDataChunk:\n chunk_df = chunk.df_chunk_data\n\n if chunk_df.empty:\n return ProcessedTracknetDataChunk(None, '')\n\n chunk_id = int(chunk_df.event.values[0])\n output_name = f'{self.output_dir}/tracknet_{idx.replace(\".txt\", \"\")}'\n return ProcessedTracknetDataChunk(chunk_df, output_name)\n\n\n def postprocess_chunks(self,\n chunks: List[ProcessedTracknetDataChunk]) -> ProcessedTracknetData:\n for chunk in chunks:\n if chunk.processed_object is None:\n continue\n chunk_data_x = []\n chunk_data_y = []\n chunk_data_len = []\n df = chunk.processed_object\n grouped_df = df[df['track'] != -1].groupby('track')\n for i, data in grouped_df:\n chunk_data_x.append(data[['r', 'phi', 'z']].values[:-1])\n chunk_data_y.append(data[['phi', 'z']].values[-1])\n chunk_data_len.append(2)\n chunk_data_x = np.stack(chunk_data_x, axis=0)\n chunk_data_y = np.stack(chunk_data_y, axis=0)\n chunk_data = {\n 'x': {\n 'inputs': chunk_data_x,\n 'input_lengths': chunk_data_len},\n 'y': chunk_data_y}\n chunk.processed_object = chunk_data\n return ProcessedTracknetData(chunks[0].output_name,chunks)\n\n def save_on_disk(self,\n processed_data: ProcessedTracknetData):\n all_data_inputs = []\n all_data_y = []\n all_data_len = []\n for data_chunk in processed_data.processed_data:\n if data_chunk.processed_object is None:\n continue\n all_data_inputs.append(data_chunk.processed_object['x']['inputs'])\n all_data_len.append(data_chunk.processed_object['x']['input_lengths'])\n all_data_y.append(data_chunk.processed_object['y'])\n all_data_inputs = np.concatenate(all_data_inputs).astype('float32')\n all_data_y = np.concatenate(all_data_y).astype('float32')\n all_data_len = np.concatenate(all_data_len)\n np.savez(\n processed_data.output_name,\n inputs=all_data_inputs,\n input_lengths=all_data_len, y=all_data_y\n )\n LOGGER.info(f'Saved to: {processed_data.output_name}.npz')\n\[email protected](denylist=['data_df'])\nclass TrackNetProcessorWithMask(DataProcessor):\n def __init__(self,\n output_dir: str,\n data_df: pd.DataFrame,\n name_suffix: str,\n transforms: List[BaseTransformer] = None,\n columns=('x', 'y', 'z'),\n det_indices=(0,1),\n min_track_len=4,\n balance=True,\n filter_first_n=0):\n super().__init__(\n processor_name='TrackNet_v2_Processor',\n output_dir=output_dir,\n data_df=data_df,\n transforms=transforms)\n self.output_name = os.path.join(self.output_dir, f'masked_tracknet_{name_suffix}')\n self.columns = columns\n self.det_indices = det_indices\n self.filter_first_stations = filter_first_n\n self.min_track_len=min_track_len - 1\n self.balance=balance\n\n def generate_chunks_iterable(self) -> Iterable[TracknetDataChunk]:\n if len(self.det_indices) > 1:\n self.data_df.loc[self.data_df.det == 1, 'station'] = self.data_df.loc[self.data_df.det == 1, 'station'].values + 3\n if self.filter_first_stations > 0:\n self.data_df = self.data_df.loc[self.data_df['station'] >= self.filter_first_stations, :]\n self.data_df.loc[:, 'station'] = self.data_df.loc[:, 'station'].values - self.filter_first_stations\n return self.data_df.groupby('event')\n\n def construct_chunk(self,\n chunk_df: pd.DataFrame) -> TracknetDataChunk:\n processed = self.transformer(chunk_df)\n return TracknetDataChunk(processed)\n\n def preprocess_chunk(self,\n chunk: TracknetDataChunk,\n idx: str) -> ProcessedTracknetDataChunk:\n df = chunk.df_chunk_data\n if df.empty:\n return ProcessedTracknetDataChunk(None, '')\n chunk_data_xs = {}\n stations = df.groupby('station').size().max()\n # max_station = max(stations)\n if stations > 1000:\n return ProcessedTracknetDataChunk(None, '')\n grouped_df = df[df['track'] != -1].groupby('track')\n for i, data in grouped_df:\n track = data[list(self.columns)].values\n track_len = len(track)\n if track_len > self.min_track_len:\n if track_len not in chunk_data_xs.keys():\n chunk_data_xs[track_len] = []\n chunk_data_xs[track_len].append(track)\n if len(chunk_data_xs.keys()) == 0:\n return ProcessedTracknetDataChunk(None, '')\n if self.balance:\n nums = [len(i) for i in chunk_data_xs.items()]\n min_num = min(nums)\n chunk_data_xs = {k: v[:min_num] for k,v in chunk_data_xs.items()}\n return ProcessedTracknetDataChunk(chunk_data_xs, self.output_name)\n\n\n def postprocess_chunks(self,\n chunks: List[ProcessedTracknetDataChunk]) -> ProcessedTracknetData:\n return ProcessedTracknetData(self.output_name, chunks)\n\n\n def save_on_disk(self,\n processed_data: ProcessedTracknetData):\n chunk_data_xs = []\n for chunk in processed_data.processed_data:\n if chunk.processed_object is None:\n continue\n for items in chunk.processed_object.values():\n chunk_data_xs.extend(items)\n all_data_inputs = np.array(chunk_data_xs, dtype=object)\n LOGGER.info(f'Get {len(all_data_inputs)} tracks')\n try:\n temp_inputs = np.load(self.output_name+'.npy', allow_pickle=True)\n all_data_inputs = np.concatenate((temp_inputs, all_data_inputs))\n except:\n LOGGER.info('new array is created')\n np.save(self.output_name, all_data_inputs, allow_pickle=True)\n temp_inputs = np.load(self.output_name+'.npy', allow_pickle=True)\n LOGGER.info(f'now have {len(temp_inputs)} tracks')\n LOGGER.info(f'Saved to: {self.output_name}.npy as object-pickle')\n", "import multiprocessing\nfrom abc import abstractmethod, ABCMeta\nfrom contextlib import contextmanager\nfrom typing import List, Union, Callable, Any, Dict\n\nimport numpy as np\nimport pandas as pd\n\nclass HDF5Serializable:\n @abstractmethod\n def to_hdf5(self, db, hash, path):\n pass\n\n @staticmethod\n def from_hdf5(db, hash, path):\n pass\n\n\nclass DataChunk(HDF5Serializable):\n def __init__(self, np_ndarr: np.ndarray, source=None):\n self.np_arr = np_ndarr\n self.__source = source\n\n def jit_hash(self):\n assert self.__source is not None\n return self.__source\n\n def cachable(self):\n return self.__source is not None\n\n\nclass DFDataChunk(DataChunk):\n def __init__(self,\n np_index: np.ndarray,\n np_chunk_data: np.ndarray,\n columns: List[str],\n dtypes: List,\n source=None):\n super(DFDataChunk, self).__init__(np_ndarr=np_chunk_data,\n source=source)\n self.index = np_index\n self.columns = columns\n self.dtypes = dtypes\n\n @staticmethod\n def from_df(df: pd.DataFrame, hash_source=None):\n return DFDataChunk(np_chunk_data=df.values, np_index=df.index.values, columns=list(df.columns),\n dtypes=[dt.str for dt in df.dtypes], source=hash_source)\n\n def as_df(self):\n return pd.DataFrame({\n column: self.np_arr[:, idx].astype(self.dtypes[idx] if self.dtypes[idx] != '|O' else 'str')\n for idx, column in enumerate(self.columns)},\n index=self.index)\n\n def to_hdf5(self, db, hash, path):\n columns = list(self.columns)\n ndarr = self.np_arr\n idx = self.index\n if f\"{path}\" in db:\n del db[f\"{path}\"]\n\n db.create_dataset(f\"{path}/idx\", data=idx, compression='gzip')\n db[f\"{path}\"].attrs[\"col\"] = columns\n db[f\"{path}\"].attrs[\"dtype\"] = self.dtypes\n for idx, col in enumerate(columns):\n tgt = ndarr[:, idx].astype(self.dtypes[idx])\n db.create_dataset(f\"{path}/objs/{idx}/{columns[idx]}\", data=tgt, shape=tgt.shape, compression=\"gzip\")\n\n\n @staticmethod\n def from_hdf5(db, hash, path):\n index = db[f\"{path}/idx\"][()]\n vals = {}\n for idx, col in enumerate(db[path].attrs['col']):\n vals[col] = db[f\"{path}/objs/{idx}/{col}\"][()]\n return DFDataChunk(index, pd.DataFrame.from_dict(vals).values, db[path].attrs['col'], db[path].attrs['dtype'], source=hash)\n" ]
[ [ "numpy.savez", "numpy.save", "numpy.stack", "numpy.concatenate", "numpy.load", "numpy.array" ], [ "pandas.DataFrame.from_dict" ] ]
lllcho/tensorlayer
[ "87591b4945a6a67dfb4ea797a575efae997fd9d2", "87591b4945a6a67dfb4ea797a575efae997fd9d2" ]
[ "tests/test_layers_basic.py", "tensorlayer/layers/convolution.py" ]
[ "import tensorflow as tf\nimport tensorlayer as tl\n\nx = tf.placeholder(tf.float32, [None, 100])\nn = tl.layers.InputLayer(x, name='in')\nn = tl.layers.DenseLayer(n, 80, name='d1')\nn = tl.layers.DenseLayer(n, 80, name='d2')\nprint(n)\nn.print_layers()\nn.print_params(False)\nprint(n.count_params())\n\nif n.count_params() != 14560:\n raise Exception(\"params dont match\")\n\nshape = n.outputs.get_shape().as_list()\nif shape[-1] != 80:\n raise Exception(\"shape dont match\")\n\nif len(n.all_layers) != 2:\n raise Exception(\"layers dont match\")\n\nif len(n.all_params) != 4:\n raise Exception(\"params dont match\")\n\nfor l in n:\n print(l)\n\nn2 = n[:, :30]\nprint(n2)\nn2.print_layers()\n\nshape = n2.outputs.get_shape().as_list()\nif shape[-1] != 30:\n raise Exception(\"shape dont match\")\n\nfor l in n2:\n print(l)\n", "# -*- coding: utf-8 -*-\n\nimport tensorflow as tf\nfrom .. import _logging as logging\nfrom .core import *\n\n__all__ = [\n 'Conv1dLayer',\n 'Conv2dLayer',\n 'DeConv2dLayer',\n 'Conv3dLayer',\n 'DeConv3dLayer',\n 'UpSampling2dLayer',\n 'DownSampling2dLayer',\n 'DeformableConv2d',\n 'AtrousConv1dLayer',\n 'AtrousConv2dLayer',\n 'deconv2d_bilinear_upsampling_initializer',\n 'Conv1d',\n 'Conv2d',\n 'DeConv2d',\n 'DeConv3d',\n 'DepthwiseConv2d',\n 'SeparableConv2d',\n 'GroupConv2d',\n]\n\n\nclass Conv1dLayer(Layer):\n \"\"\"\n The :class:`Conv1dLayer` class is a 1D CNN layer, see `tf.nn.convolution <https://www.tensorflow.org/api_docs/python/tf/nn/convolution>`__.\n\n Parameters\n ----------\n layer : :class:`Layer`\n Previous layer.\n act : activation function\n The activation function of this layer.\n shape : tuple of int\n The shape of the filters: (filter_length, in_channels, out_channels).\n stride : int\n The number of entries by which the filter is moved right at a step.\n dilation_rate : int\n Filter up-sampling/input down-sampling rate.\n padding : str\n The padding algorithm type: \"SAME\" or \"VALID\".\n data_format : str\n Default is 'NWC' as it is a 1D CNN.\n W_init : initializer\n The initializer for the weight matrix.\n b_init : initializer or None\n The initializer for the bias vector. If None, skip biases.\n W_init_args : dictionary\n The arguments for the weight matrix initializer.\n b_init_args : dictionary\n The arguments for the bias vector initializer.\n name : str\n A unique layer name\n\n \"\"\"\n\n def __init__(\n self,\n prev_layer,\n act=tf.identity,\n shape=(5, 1, 5),\n stride=1,\n dilation_rate=1,\n padding='SAME',\n data_format='NWC',\n W_init=tf.truncated_normal_initializer(stddev=0.02),\n b_init=tf.constant_initializer(value=0.0),\n W_init_args=None,\n b_init_args=None,\n name='cnn1d',\n ):\n if act is None:\n act = tf.identity\n if W_init_args is None:\n W_init_args = {}\n if b_init_args is None:\n b_init_args = {}\n\n Layer.__init__(self, prev_layer=prev_layer, name=name)\n self.inputs = prev_layer.outputs\n logging.info(\"Conv1dLayer %s: shape:%s stride:%s pad:%s act:%s\" % (self.name, str(shape), str(stride), padding, act.__name__))\n\n with tf.variable_scope(name):\n W = tf.get_variable(name='W_conv1d', shape=shape, initializer=W_init, dtype=LayersConfig.tf_dtype, **W_init_args)\n self.outputs = tf.nn.convolution(\n self.inputs, W, strides=(stride, ), padding=padding, dilation_rate=(dilation_rate, ), data_format=data_format) # 1.2\n if b_init:\n b = tf.get_variable(name='b_conv1d', shape=(shape[-1]), initializer=b_init, dtype=LayersConfig.tf_dtype, **b_init_args)\n self.outputs = self.outputs + b\n\n self.outputs = act(self.outputs)\n\n # self.all_layers = list(layer.all_layers)\n # self.all_params = list(layer.all_params)\n # self.all_drop = dict(layer.all_drop)\n self.all_layers.append(self.outputs)\n if b_init:\n self.all_params.extend([W, b])\n else:\n self.all_params.append(W)\n\n\nclass Conv2dLayer(Layer):\n \"\"\"\n The :class:`Conv2dLayer` class is a 2D CNN layer, see `tf.nn.conv2d <https://www.tensorflow.org/versions/master/api_docs/python/nn.html#conv2d>`__.\n\n Parameters\n ----------\n layer : :class:`Layer`\n Previous layer.\n act : activation function\n The activation function of this layer.\n shape : tuple of int\n The shape of the filters: (filter_height, filter_width, in_channels, out_channels).\n strides : tuple of int\n The sliding window strides of corresponding input dimensions.\n It must be in the same order as the ``shape`` parameter.\n padding : str\n The padding algorithm type: \"SAME\" or \"VALID\".\n W_init : initializer\n The initializer for the weight matrix.\n b_init : initializer or None\n The initializer for the bias vector. If None, skip biases.\n W_init_args : dictionary\n The arguments for the weight matrix initializer.\n b_init_args : dictionary\n The arguments for the bias vector initializer.\n use_cudnn_on_gpu : bool\n Default is False.\n data_format : str\n \"NHWC\" or \"NCHW\", default is \"NHWC\".\n name : str\n A unique layer name.\n\n Notes\n -----\n - shape = [h, w, the number of output channel of previous layer, the number of output channels]\n - the number of output channel of a layer is its last dimension.\n\n Examples\n --------\n With TensorLayer\n\n >>> x = tf.placeholder(tf.float32, shape=(None, 28, 28, 1))\n >>> net = tl.layers.InputLayer(x, name='input_layer')\n >>> net = tl.layers.Conv2dLayer(net,\n ... act = tf.nn.relu,\n ... shape = (5, 5, 1, 32), # 32 features for each 5x5 patch\n ... strides = (1, 1, 1, 1),\n ... padding='SAME',\n ... W_init=tf.truncated_normal_initializer(stddev=5e-2),\n ... b_init = tf.constant_initializer(value=0.0),\n ... name ='cnn_layer1') # output: (?, 28, 28, 32)\n >>> net = tl.layers.PoolLayer(net,\n ... ksize=(1, 2, 2, 1),\n ... strides=(1, 2, 2, 1),\n ... padding='SAME',\n ... pool = tf.nn.max_pool,\n ... name ='pool_layer1',) # output: (?, 14, 14, 32)\n\n Without TensorLayer, you can implement 2D convolution as follow.\n\n >>> W = tf.Variable(W_init(shape=[5, 5, 1, 32], ), name='W_conv')\n >>> b = tf.Variable(b_init(shape=[32], ), name='b_conv')\n >>> outputs = tf.nn.relu( tf.nn.conv2d(inputs, W,\n ... strides=[1, 1, 1, 1],\n ... padding='SAME') + b )\n\n \"\"\"\n\n def __init__(\n self,\n prev_layer,\n act=tf.identity,\n shape=(5, 5, 1, 100),\n strides=(1, 1, 1, 1),\n padding='SAME',\n W_init=tf.truncated_normal_initializer(stddev=0.02),\n b_init=tf.constant_initializer(value=0.0),\n W_init_args=None,\n b_init_args=None,\n use_cudnn_on_gpu=None,\n data_format=None,\n name='cnn_layer',\n ):\n if W_init_args is None:\n W_init_args = {}\n if b_init_args is None:\n b_init_args = {}\n\n Layer.__init__(self, prev_layer=prev_layer, name=name)\n self.inputs = prev_layer.outputs\n if act is None:\n act = tf.identity\n logging.info(\"Conv2dLayer %s: shape:%s strides:%s pad:%s act:%s\" % (self.name, str(shape), str(strides), padding, act.__name__))\n\n with tf.variable_scope(name):\n W = tf.get_variable(name='W_conv2d', shape=shape, initializer=W_init, dtype=LayersConfig.tf_dtype, **W_init_args)\n if b_init:\n b = tf.get_variable(name='b_conv2d', shape=(shape[-1]), initializer=b_init, dtype=LayersConfig.tf_dtype, **b_init_args)\n self.outputs = act(\n tf.nn.conv2d(self.inputs, W, strides=strides, padding=padding, use_cudnn_on_gpu=use_cudnn_on_gpu, data_format=data_format) + b)\n else:\n self.outputs = act(tf.nn.conv2d(self.inputs, W, strides=strides, padding=padding, use_cudnn_on_gpu=use_cudnn_on_gpu, data_format=data_format))\n\n # self.all_layers = list(layer.all_layers)\n # self.all_params = list(layer.all_params)\n # self.all_drop = dict(layer.all_drop)\n self.all_layers.append(self.outputs)\n if b_init:\n self.all_params.extend([W, b])\n else:\n self.all_params.append(W)\n\n\nclass DeConv2dLayer(Layer):\n \"\"\"A de-convolution 2D layer.\n\n See `tf.nn.conv2d_transpose <https://www.tensorflow.org/versions/master/api_docs/python/nn.html#conv2d_transpose>`__.\n\n Parameters\n ----------\n layer : :class:`Layer`\n Previous layer.\n act : activation function\n The activation function of this layer.\n shape : tuple of int\n Shape of the filters: (height, width, output_channels, in_channels).\n The filter's ``in_channels`` dimension must match that of value.\n output_shape : tuple of int\n Output shape of the deconvolution,\n strides : tuple of int\n The sliding window strides for corresponding input dimensions.\n padding : str\n The padding algorithm type: \"SAME\" or \"VALID\".\n W_init : initializer\n The initializer for the weight matrix.\n b_init : initializer or None\n The initializer for the bias vector. If None, skip biases.\n W_init_args : dictionary\n The arguments for initializing the weight matrix.\n b_init_args : dictionary\n The arguments for initializing the bias vector.\n name : str\n A unique layer name.\n\n Notes\n -----\n - We recommend to use `DeConv2d` with TensorFlow version higher than 1.3.\n - shape = [h, w, the number of output channels of this layer, the number of output channel of the previous layer].\n - output_shape = [batch_size, any, any, the number of output channels of this layer].\n - the number of output channel of a layer is its last dimension.\n\n Examples\n --------\n A part of the generator in DCGAN example\n\n >>> batch_size = 64\n >>> inputs = tf.placeholder(tf.float32, [batch_size, 100], name='z_noise')\n >>> net_in = tl.layers.InputLayer(inputs, name='g/in')\n >>> net_h0 = tl.layers.DenseLayer(net_in, n_units = 8192,\n ... W_init = tf.random_normal_initializer(stddev=0.02),\n ... act = tf.identity, name='g/h0/lin')\n >>> print(net_h0.outputs._shape)\n ... (64, 8192)\n >>> net_h0 = tl.layers.ReshapeLayer(net_h0, shape=(-1, 4, 4, 512), name='g/h0/reshape')\n >>> net_h0 = tl.layers.BatchNormLayer(net_h0, act=tf.nn.relu, is_train=is_train, name='g/h0/batch_norm')\n >>> print(net_h0.outputs._shape)\n ... (64, 4, 4, 512)\n >>> net_h1 = tl.layers.DeConv2dLayer(net_h0,\n ... shape=(5, 5, 256, 512),\n ... output_shape=(batch_size, 8, 8, 256),\n ... strides=(1, 2, 2, 1),\n ... act=tf.identity, name='g/h1/decon2d')\n >>> net_h1 = tl.layers.BatchNormLayer(net_h1, act=tf.nn.relu, is_train=is_train, name='g/h1/batch_norm')\n >>> print(net_h1.outputs._shape)\n ... (64, 8, 8, 256)\n\n U-Net\n\n >>> ....\n >>> conv10 = tl.layers.Conv2dLayer(conv9, act=tf.nn.relu,\n ... shape=(3,3,1024,1024), strides=(1,1,1,1), padding='SAME',\n ... W_init=w_init, b_init=b_init, name='conv10')\n >>> print(conv10.outputs)\n ... (batch_size, 32, 32, 1024)\n >>> deconv1 = tl.layers.DeConv2dLayer(conv10, act=tf.nn.relu,\n ... shape=(3,3,512,1024), strides=(1,2,2,1), output_shape=(batch_size,64,64,512),\n ... padding='SAME', W_init=w_init, b_init=b_init, name='devcon1_1')\n\n \"\"\"\n\n def __init__(\n self,\n prev_layer,\n act=tf.identity,\n shape=(3, 3, 128, 256),\n output_shape=(1, 256, 256, 128),\n strides=(1, 2, 2, 1),\n padding='SAME',\n W_init=tf.truncated_normal_initializer(stddev=0.02),\n b_init=tf.constant_initializer(value=0.0),\n W_init_args=None,\n b_init_args=None,\n name='decnn2d_layer',\n ):\n if W_init_args is None:\n W_init_args = {}\n if b_init_args is None:\n b_init_args = {}\n\n Layer.__init__(self, prev_layer=prev_layer, name=name)\n self.inputs = prev_layer.outputs\n if act is None:\n act = tf.identity\n logging.info(\"DeConv2dLayer %s: shape:%s out_shape:%s strides:%s pad:%s act:%s\" % (self.name, str(shape), str(output_shape), str(strides), padding,\n act.__name__))\n # logging.info(\" DeConv2dLayer: Untested\")\n with tf.variable_scope(name):\n W = tf.get_variable(name='W_deconv2d', shape=shape, initializer=W_init, dtype=LayersConfig.tf_dtype, **W_init_args)\n if b_init:\n b = tf.get_variable(name='b_deconv2d', shape=(shape[-2]), initializer=b_init, dtype=LayersConfig.tf_dtype, **b_init_args)\n self.outputs = act(tf.nn.conv2d_transpose(self.inputs, W, output_shape=output_shape, strides=strides, padding=padding) + b)\n else:\n self.outputs = act(tf.nn.conv2d_transpose(self.inputs, W, output_shape=output_shape, strides=strides, padding=padding))\n\n # self.all_layers = list(layer.all_layers)\n # self.all_params = list(layer.all_params)\n # self.all_drop = dict(layer.all_drop)\n self.all_layers.append(self.outputs)\n if b_init:\n self.all_params.extend([W, b])\n else:\n self.all_params.append(W)\n\n\nclass Conv3dLayer(Layer):\n \"\"\"\n The :class:`Conv3dLayer` class is a 3D CNN layer, see `tf.nn.conv3d <https://www.tensorflow.org/versions/master/api_docs/python/nn.html#conv3d>`__.\n\n Parameters\n ----------\n layer : :class:`Layer`\n Previous layer.\n act : activation function\n The activation function of this layer.\n shape : tuple of int\n Shape of the filters: (filter_depth, filter_height, filter_width, in_channels, out_channels).\n strides : tuple of int\n The sliding window strides for corresponding input dimensions.\n Must be in the same order as the shape dimension.\n padding : str\n The padding algorithm type: \"SAME\" or \"VALID\".\n W_init : initializer\n The initializer for the weight matrix.\n b_init : initializer or None\n The initializer for the bias vector. If None, skip biases.\n W_init_args : dictionary\n The arguments for the weight matrix initializer.\n b_init_args : dictionary\n The arguments for the bias vector initializer.\n name : str\n A unique layer name.\n\n Examples\n ---------\n >>> x = tf.placeholder(tf.float32, (None, 100, 100, 100, 3))\n >>> n = tl.layers.InputLayer(x, name='in3')\n >>> n = tl.layers.Conv3dLayer(n, shape=(2, 2, 2, 3, 32), strides=(1, 2, 2, 2, 1))\n ... [None, 50, 50, 50, 32]\n \"\"\"\n\n def __init__(\n self,\n prev_layer,\n act=tf.identity,\n shape=(2, 2, 2, 3, 32),\n strides=(1, 2, 2, 2, 1),\n padding='SAME',\n W_init=tf.truncated_normal_initializer(stddev=0.02),\n b_init=tf.constant_initializer(value=0.0),\n W_init_args=None,\n b_init_args=None,\n name='cnn3d_layer',\n ):\n if W_init_args is None:\n W_init_args = {}\n if b_init_args is None:\n b_init_args = {}\n\n Layer.__init__(self, prev_layer=prev_layer, name=name)\n self.inputs = prev_layer.outputs\n if act is None:\n act = tf.identity\n logging.info(\"Conv3dLayer %s: shape:%s strides:%s pad:%s act:%s\" % (self.name, str(shape), str(strides), padding, act.__name__))\n\n with tf.variable_scope(name):\n # W = tf.Variable(W_init(shape=shape, **W_init_args), name='W_conv')\n # b = tf.Variable(b_init(shape=[shape[-1]], **b_init_args), name='b_conv')\n W = tf.get_variable(name='W_conv3d', shape=shape, initializer=W_init, dtype=LayersConfig.tf_dtype, **W_init_args)\n if b_init:\n b = tf.get_variable(name='b_conv3d', shape=(shape[-1]), initializer=b_init, dtype=LayersConfig.tf_dtype, **b_init_args)\n self.outputs = act(tf.nn.conv3d(self.inputs, W, strides=strides, padding=padding, name=None) + b)\n else:\n self.outputs = act(tf.nn.conv3d(self.inputs, W, strides=strides, padding=padding, name=None))\n\n # self.outputs = act( tf.nn.conv3d(self.inputs, W, strides=strides, padding=padding, name=None) + b )\n\n # self.all_layers = list(layer.all_layers)\n # self.all_params = list(layer.all_params)\n # self.all_drop = dict(layer.all_drop)\n self.all_layers.append(self.outputs)\n if b_init:\n self.all_params.extend([W, b])\n else:\n self.all_params.extend([W])\n\n\nclass DeConv3dLayer(Layer):\n \"\"\"The :class:`DeConv3dLayer` class is deconvolutional 3D layer, see `tf.nn.conv3d_transpose <https://www.tensorflow.org/versions/master/api_docs/python/nn.html#conv3d_transpose>`__.\n\n Parameters\n ----------\n layer : :class:`Layer`\n Previous layer.\n act : activation function\n The activation function of this layer.\n shape : tuple of int\n The shape of the filters: (depth, height, width, output_channels, in_channels).\n The filter's in_channels dimension must match that of value.\n output_shape : tuple of int\n The output shape of the deconvolution.\n strides : tuple of int\n The sliding window strides for corresponding input dimensions.\n padding : str\n The padding algorithm type: \"SAME\" or \"VALID\".\n W_init : initializer\n The initializer for the weight matrix.\n b_init : initializer or None\n The initializer for the bias vector. If None, skip biases.\n W_init_args : dictionary\n The arguments for the weight matrix initializer.\n b_init_args : dictionary\n The arguments for the bias vector initializer.\n name : str\n A unique layer name.\n\n \"\"\"\n\n def __init__(\n self,\n prev_layer,\n act=tf.identity,\n shape=(2, 2, 2, 128, 256),\n output_shape=(1, 12, 32, 32, 128),\n strides=(1, 2, 2, 2, 1),\n padding='SAME',\n W_init=tf.truncated_normal_initializer(stddev=0.02),\n b_init=tf.constant_initializer(value=0.0),\n W_init_args=None,\n b_init_args=None,\n name='decnn3d_layer',\n ):\n if W_init_args is None:\n W_init_args = {}\n if b_init_args is None:\n b_init_args = {}\n\n Layer.__init__(self, prev_layer=prev_layer, name=name)\n self.inputs = prev_layer.outputs\n if act is None:\n act = tf.identity\n logging.info(\"DeConv3dLayer %s: shape:%s out_shape:%s strides:%s pad:%s act:%s\" % (self.name, str(shape), str(output_shape), str(strides), padding,\n act.__name__))\n\n with tf.variable_scope(name):\n W = tf.get_variable(name='W_deconv3d', shape=shape, initializer=W_init, dtype=LayersConfig.tf_dtype, **W_init_args)\n if b_init:\n b = tf.get_variable(name='b_deconv3d', shape=(shape[-2]), initializer=b_init, dtype=LayersConfig.tf_dtype, **b_init_args)\n self.outputs = act(tf.nn.conv3d_transpose(self.inputs, W, output_shape=output_shape, strides=strides, padding=padding) + b)\n else:\n self.outputs = act(tf.nn.conv3d_transpose(self.inputs, W, output_shape=output_shape, strides=strides, padding=padding))\n\n # self.all_layers = list(layer.all_layers)\n # self.all_params = list(layer.all_params)\n # self.all_drop = dict(layer.all_drop)\n self.all_layers.append(self.outputs)\n if b_init:\n self.all_params.extend([W, b])\n else:\n self.all_params.extend([W])\n\n\nclass UpSampling2dLayer(Layer):\n \"\"\"The :class:`UpSampling2dLayer` class is a up-sampling 2D layer, see `tf.image.resize_images <https://www.tensorflow.org/versions/master/api_docs/python/image/resizing#resize_images>`__.\n\n Parameters\n ----------\n layer : :class:`Layer`\n Previous layer with 4-D Tensor of the shape (batch, height, width, channels) or 3-D Tensor of the shape (height, width, channels).\n size : tuple of int/float\n (height, width) scale factor or new size of height and width.\n is_scale : boolean\n If True (default), the `size` is a scale factor; otherwise, the `size` is the numbers of pixels of height and width.\n method : int\n The resize method selected through the index. Defaults index is 0 which is ResizeMethod.BILINEAR.\n - Index 0 is ResizeMethod.BILINEAR, Bilinear interpolation.\n - Index 1 is ResizeMethod.NEAREST_NEIGHBOR, Nearest neighbor interpolation.\n - Index 2 is ResizeMethod.BICUBIC, Bicubic interpolation.\n - Index 3 ResizeMethod.AREA, Area interpolation.\n align_corners : boolean\n If True, align the corners of the input and output. Default is False.\n name : str\n A unique layer name.\n\n \"\"\"\n\n def __init__(\n self,\n prev_layer,\n size,\n is_scale=True,\n method=0,\n align_corners=False,\n name='upsample2d_layer',\n ):\n Layer.__init__(self, prev_layer=prev_layer, name=name)\n self.inputs = prev_layer.outputs\n if len(self.inputs.get_shape()) == 3:\n if is_scale:\n size_h = size[0] * int(self.inputs.get_shape()[0])\n size_w = size[1] * int(self.inputs.get_shape()[1])\n size = [int(size_h), int(size_w)]\n elif len(self.inputs.get_shape()) == 4:\n if is_scale:\n size_h = size[0] * int(self.inputs.get_shape()[1])\n size_w = size[1] * int(self.inputs.get_shape()[2])\n size = [int(size_h), int(size_w)]\n else:\n raise Exception(\"Donot support shape %s\" % self.inputs.get_shape())\n logging.info(\"UpSampling2dLayer %s: is_scale:%s size:%s method:%d align_corners:%s\" % (name, is_scale, size, method, align_corners))\n with tf.variable_scope(name):\n try:\n self.outputs = tf.image.resize_images(self.inputs, size=size, method=method, align_corners=align_corners)\n except Exception: # for TF 0.10\n self.outputs = tf.image.resize_images(self.inputs, new_height=size[0], new_width=size[1], method=method, align_corners=align_corners)\n\n # self.all_layers = list(layer.all_layers)\n # self.all_params = list(layer.all_params)\n # self.all_drop = dict(layer.all_drop)\n self.all_layers.append(self.outputs)\n\n\nclass DownSampling2dLayer(Layer):\n \"\"\"The :class:`DownSampling2dLayer` class is down-sampling 2D layer, see `tf.image.resize_images <https://www.tensorflow.org/versions/master/api_docs/python/image/resizing#resize_images>`__.\n\n Parameters\n ----------\n layer : :class:`Layer`\n Previous layer with 4-D Tensor in the shape of (batch, height, width, channels) or 3-D Tensor in the shape of (height, width, channels).\n size : tuple of int/float\n (height, width) scale factor or new size of height and width.\n is_scale : boolean\n If True (default), the `size` is the scale factor; otherwise, the `size` are numbers of pixels of height and width.\n method : int\n The resize method selected through the index. Defaults index is 0 which is ResizeMethod.BILINEAR.\n - Index 0 is ResizeMethod.BILINEAR, Bilinear interpolation.\n - Index 1 is ResizeMethod.NEAREST_NEIGHBOR, Nearest neighbor interpolation.\n - Index 2 is ResizeMethod.BICUBIC, Bicubic interpolation.\n - Index 3 ResizeMethod.AREA, Area interpolation.\n align_corners : boolean\n If True, exactly align all 4 corners of the input and output. Default is False.\n name : str\n A unique layer name.\n\n \"\"\"\n\n def __init__(\n self,\n prev_layer,\n size,\n is_scale=True,\n method=0,\n align_corners=False,\n name='downsample2d_layer',\n ):\n Layer.__init__(self, prev_layer=prev_layer, name=name)\n self.inputs = prev_layer.outputs\n if len(self.inputs.get_shape()) == 3:\n if is_scale:\n size_h = size[0] * int(self.inputs.get_shape()[0])\n size_w = size[1] * int(self.inputs.get_shape()[1])\n size = [int(size_h), int(size_w)]\n elif len(self.inputs.get_shape()) == 4:\n if is_scale:\n size_h = size[0] * int(self.inputs.get_shape()[1])\n size_w = size[1] * int(self.inputs.get_shape()[2])\n size = [int(size_h), int(size_w)]\n else:\n raise Exception(\"Donot support shape %s\" % self.inputs.get_shape())\n logging.info(\"DownSampling2dLayer %s: is_scale:%s size:%s method:%d, align_corners:%s\" % (name, is_scale, size, method, align_corners))\n with tf.variable_scope(name):\n try:\n self.outputs = tf.image.resize_images(self.inputs, size=size, method=method, align_corners=align_corners)\n except Exception: # for TF 0.10\n self.outputs = tf.image.resize_images(self.inputs, new_height=size[0], new_width=size[1], method=method, align_corners=align_corners)\n\n # self.all_layers = list(layer.all_layers)\n # self.all_params = list(layer.all_params)\n # self.all_drop = dict(layer.all_drop)\n self.all_layers.append(self.outputs)\n\n\nclass DeformableConv2d(Layer):\n \"\"\"The :class:`DeformableConv2d` class is a 2D\n `Deformable Convolutional Networks <https://arxiv.org/abs/1703.06211>`__.\n\n Parameters\n ----------\n layer : :class:`Layer`\n Previous layer.\n offset_layer : :class:`Layer`\n To predict the offset of convolution operations.\n The output shape is (batchsize, input height, input width, 2*(number of element in the convolution kernel))\n e.g. if apply a 3*3 kernel, the number of the last dimension should be 18 (2*3*3)\n n_filter : int\n The number of filters.\n filter_size : tuple of int\n The filter size (height, width).\n act : activation function\n The activation function of this layer.\n W_init : initializer\n The initializer for the weight matrix.\n b_init : initializer or None\n The initializer for the bias vector. If None, skip biases.\n W_init_args : dictionary\n The arguments for the weight matrix initializer.\n b_init_args : dictionary\n The arguments for the bias vector initializer.\n name : str\n A unique layer name.\n\n Examples\n --------\n >>> net = tl.layers.InputLayer(x, name='input_layer')\n >>> offset1 = tl.layers.Conv2d(net, 18, (3, 3), (1, 1), act=act, padding='SAME', name='offset1')\n >>> net = tl.layers.DeformableConv2d(net, offset1, 32, (3, 3), act=act, name='deformable1')\n >>> offset2 = tl.layers.Conv2d(net, 18, (3, 3), (1, 1), act=act, padding='SAME', name='offset2')\n >>> net = tl.layers.DeformableConv2d(net, offset2, 64, (3, 3), act=act, name='deformable2')\n\n References\n ----------\n - The deformation operation was adapted from the implementation in `here <https://github.com/felixlaumon/deform-conv>`__\n\n Notes\n -----\n - The padding is fixed to 'SAME'.\n - The current implementation is not optimized for memory usgae. Please use it carefully.\n\n \"\"\"\n\n def __init__(\n self,\n prev_layer,\n offset_layer=None,\n # shape=(3, 3, 1, 100),\n n_filter=32,\n filter_size=(3, 3),\n act=tf.identity,\n name='deformable_conv_2d',\n W_init=tf.truncated_normal_initializer(stddev=0.02),\n b_init=tf.constant_initializer(value=0.0),\n W_init_args=None,\n b_init_args=None):\n if tf.__version__ < \"1.4\":\n raise Exception(\"Deformable CNN layer requires tensrflow 1.4 or higher version | current version %s\" % tf.__version__)\n\n if W_init_args is None:\n W_init_args = {}\n if b_init_args is None:\n b_init_args = {}\n\n def _to_bc_h_w(x, x_shape):\n \"\"\"(b, h, w, c) -> (b*c, h, w)\"\"\"\n x = tf.transpose(x, [0, 3, 1, 2])\n x = tf.reshape(x, (-1, x_shape[1], x_shape[2]))\n return x\n\n def _to_b_h_w_n_c(x, x_shape):\n \"\"\"(b*c, h, w, n) -> (b, h, w, n, c)\"\"\"\n x = tf.reshape(x, (-1, x_shape[4], x_shape[1], x_shape[2], x_shape[3]))\n x = tf.transpose(x, [0, 2, 3, 4, 1])\n return x\n\n def tf_flatten(a):\n \"\"\"Flatten tensor\"\"\"\n return tf.reshape(a, [-1])\n\n def _get_vals_by_coords(inputs, coords, idx, out_shape):\n indices = tf.stack([idx, tf_flatten(coords[:, :, :, :, 0]), tf_flatten(coords[:, :, :, :, 1])], axis=-1)\n vals = tf.gather_nd(inputs, indices)\n vals = tf.reshape(vals, out_shape)\n return vals\n\n def _tf_repeat(a, repeats):\n \"\"\"Tensorflow version of np.repeat for 1D\"\"\"\n # https://github.com/tensorflow/tensorflow/issues/8521\n assert len(a.get_shape()) == 1\n\n a = tf.expand_dims(a, -1)\n a = tf.tile(a, [1, repeats])\n a = tf_flatten(a)\n return a\n\n def _tf_batch_map_coordinates(inputs, coords):\n \"\"\"Batch version of tf_map_coordinates\n\n Only supports 2D feature maps\n\n Parameters\n ----------\n inputs : ``tf.Tensor``\n shape = (b*c, h, w)\n coords : ``tf.Tensor``\n shape = (b*c, h, w, n, 2)\n\n Returns\n -------\n ``tf.Tensor``\n A Tensor with the shape as (b*c, h, w, n)\n\n \"\"\"\n input_shape = inputs.get_shape()\n coords_shape = coords.get_shape()\n batch_channel = tf.shape(inputs)[0]\n input_h = int(input_shape[1])\n input_w = int(input_shape[2])\n kernel_n = int(coords_shape[3])\n n_coords = input_h * input_w * kernel_n\n\n coords_lt = tf.cast(tf.floor(coords), 'int32')\n coords_rb = tf.cast(tf.ceil(coords), 'int32')\n coords_lb = tf.stack([coords_lt[:, :, :, :, 0], coords_rb[:, :, :, :, 1]], axis=-1)\n coords_rt = tf.stack([coords_rb[:, :, :, :, 0], coords_lt[:, :, :, :, 1]], axis=-1)\n\n idx = _tf_repeat(tf.range(batch_channel), n_coords)\n\n vals_lt = _get_vals_by_coords(inputs, coords_lt, idx, (batch_channel, input_h, input_w, kernel_n))\n vals_rb = _get_vals_by_coords(inputs, coords_rb, idx, (batch_channel, input_h, input_w, kernel_n))\n vals_lb = _get_vals_by_coords(inputs, coords_lb, idx, (batch_channel, input_h, input_w, kernel_n))\n vals_rt = _get_vals_by_coords(inputs, coords_rt, idx, (batch_channel, input_h, input_w, kernel_n))\n\n coords_offset_lt = coords - tf.cast(coords_lt, 'float32')\n\n vals_t = vals_lt + (vals_rt - vals_lt) * coords_offset_lt[:, :, :, :, 0]\n vals_b = vals_lb + (vals_rb - vals_lb) * coords_offset_lt[:, :, :, :, 0]\n mapped_vals = vals_t + (vals_b - vals_t) * coords_offset_lt[:, :, :, :, 1]\n\n return mapped_vals\n\n def _tf_batch_map_offsets(inputs, offsets, grid_offset):\n \"\"\"Batch map offsets into input\n\n Parameters\n ------------\n inputs : ``tf.Tensor``\n shape = (b, h, w, c)\n offsets: ``tf.Tensor``\n shape = (b, h, w, 2*n)\n grid_offset: `tf.Tensor``\n Offset grids shape = (h, w, n, 2)\n\n Returns\n -------\n ``tf.Tensor``\n A Tensor with the shape as (b, h, w, c)\n\n \"\"\"\n input_shape = inputs.get_shape()\n batch_size = tf.shape(inputs)[0]\n kernel_n = int(int(offsets.get_shape()[3]) / 2)\n input_h = input_shape[1]\n input_w = input_shape[2]\n channel = input_shape[3]\n\n # inputs (b, h, w, c) --> (b*c, h, w)\n inputs = _to_bc_h_w(inputs, input_shape)\n\n # offsets (b, h, w, 2*n) --> (b, h, w, n, 2)\n offsets = tf.reshape(offsets, (batch_size, input_h, input_w, kernel_n, 2))\n # offsets (b, h, w, n, 2) --> (b*c, h, w, n, 2)\n # offsets = tf.tile(offsets, [channel, 1, 1, 1, 1])\n\n coords = tf.expand_dims(grid_offset, 0) # grid_offset --> (1, h, w, n, 2)\n coords = tf.tile(coords, [batch_size, 1, 1, 1, 1]) + offsets # grid_offset --> (b, h, w, n, 2)\n\n # clip out of bound\n coords = tf.stack(\n [\n tf.clip_by_value(coords[:, :, :, :, 0], 0.0, tf.cast(input_h - 1, 'float32')),\n tf.clip_by_value(coords[:, :, :, :, 1], 0.0, tf.cast(input_w - 1, 'float32'))\n ],\n axis=-1)\n coords = tf.tile(coords, [channel, 1, 1, 1, 1])\n\n mapped_vals = _tf_batch_map_coordinates(inputs, coords)\n # (b*c, h, w, n) --> (b, h, w, n, c)\n mapped_vals = _to_b_h_w_n_c(mapped_vals, [batch_size, input_h, input_w, kernel_n, channel])\n\n return mapped_vals\n\n Layer.__init__(self, prev_layer=[prev_layer, offset_layer], name=name)\n self.inputs = prev_layer.outputs\n self.offset_layer = offset_layer\n if act is None:\n act = tf.identity\n logging.info(\"DeformableConv2d %s: n_filter: %d, filter_size: %s act:%s\" % (self.name, n_filter, str(filter_size), act.__name__))\n\n try:\n pre_channel = int(prev_layer.outputs.get_shape()[-1])\n except Exception: # if pre_channel is ?, it happens when using Spatial Transformer Net\n pre_channel = 1\n logging.info(\"[warnings] unknow input channels, set to 1\")\n shape = (filter_size[0], filter_size[1], pre_channel, n_filter)\n\n with tf.variable_scope(name):\n offset = self.offset_layer.outputs\n assert offset.get_shape()[-1] == 2 * shape[0] * shape[1]\n\n # Grid initialisation\n input_h = int(self.inputs.get_shape()[1])\n input_w = int(self.inputs.get_shape()[2])\n kernel_n = shape[0] * shape[1]\n initial_offsets = tf.stack(tf.meshgrid(tf.range(shape[0]), tf.range(shape[1]), indexing='ij')) # initial_offsets --> (kh, kw, 2)\n initial_offsets = tf.reshape(initial_offsets, (-1, 2)) # initial_offsets --> (n, 2)\n initial_offsets = tf.expand_dims(initial_offsets, 0) # initial_offsets --> (1, n, 2)\n initial_offsets = tf.expand_dims(initial_offsets, 0) # initial_offsets --> (1, 1, n, 2)\n initial_offsets = tf.tile(initial_offsets, [input_h, input_w, 1, 1]) # initial_offsets --> (h, w, n, 2)\n initial_offsets = tf.cast(initial_offsets, 'float32')\n grid = tf.meshgrid(\n tf.range(-int((shape[0] - 1) / 2.0), int(input_h - int((shape[0] - 1) / 2.0)), 1),\n tf.range(-int((shape[1] - 1) / 2.0), int(input_w - int((shape[1] - 1) / 2.0)), 1),\n indexing='ij')\n\n grid = tf.stack(grid, axis=-1)\n grid = tf.cast(grid, 'float32') # grid --> (h, w, 2)\n grid = tf.expand_dims(grid, 2) # grid --> (h, w, 1, 2)\n grid = tf.tile(grid, [1, 1, kernel_n, 1]) # grid --> (h, w, n, 2)\n grid_offset = grid + initial_offsets # grid_offset --> (h, w, n, 2)\n\n input_deform = _tf_batch_map_offsets(self.inputs, offset, grid_offset)\n\n W = tf.get_variable(\n name='W_deformableconv2d',\n shape=[1, 1, shape[0] * shape[1], shape[-2], shape[-1]],\n initializer=W_init,\n dtype=LayersConfig.tf_dtype,\n **W_init_args)\n\n if b_init:\n b = tf.get_variable(name='b_deformableconv2d', shape=(shape[-1]), initializer=b_init, dtype=LayersConfig.tf_dtype, **b_init_args)\n self.outputs = tf.reshape(\n act(tf.nn.conv3d(input_deform, W, strides=[1, 1, 1, 1, 1], padding='VALID', name=None) + b),\n (tf.shape(self.inputs)[0], input_h, input_w, shape[-1]))\n else:\n self.outputs = tf.reshape(\n act(tf.nn.conv3d(input_deform, W, strides=[1, 1, 1, 1, 1], padding='VALID', name=None)),\n (tf.shape(self.inputs)[0], input_h, input_w, shape[-1]))\n\n # fixed\n # self.all_layers = list(layer.all_layers)\n # self.all_params = list(layer.all_params)\n # self.all_drop = dict(layer.all_drop)\n\n # add offset_layer properties\n # offset_params = [osparam for osparam in offset_layer.all_params if osparam not in layer.all_params]\n # offset_layers = [oslayer for oslayer in offset_layer.all_layers if oslayer not in layer.all_layers]\n #\n # self.all_params.extend(list(offset_params))\n # self.all_layers.extend(list(offset_layers))\n # self.all_drop.update(dict(offset_layer.all_drop))\n\n # this layer\n self.all_layers.append(self.outputs)\n if b_init:\n self.all_params.extend([W, b])\n else:\n self.all_params.append(W)\n\n\ndef atrous_conv1d(\n layer,\n n_filter=32,\n filter_size=2,\n stride=1,\n dilation=1,\n act=tf.identity,\n padding='SAME',\n data_format='NWC',\n W_init=tf.truncated_normal_initializer(stddev=0.02),\n b_init=tf.constant_initializer(value=0.0),\n W_init_args=None,\n b_init_args=None,\n name='conv1d',\n):\n \"\"\"Simplified version of :class:`AtrousConv1dLayer`.\n\n Parameters\n ----------\n layer : :class:`Layer`\n Previous layer.\n n_filter : int\n The number of filters.\n filter_size : int\n The filter size.\n stride : tuple of int\n The strides: (height, width).\n dilation : int\n The filter dilation size.\n act : activation function\n The activation function of this layer.\n padding : str\n The padding algorithm type: \"SAME\" or \"VALID\".\n data_format : str\n Default is 'NWC' as it is a 1D CNN.\n W_init : initializer\n The initializer for the weight matrix.\n b_init : initializer or None\n The initializer for the bias vector. If None, skip biases.\n W_init_args : dictionary\n The arguments for the weight matrix initializer.\n b_init_args : dictionary\n The arguments for the bias vector initializer.\n name : str\n A unique layer name.\n\n Returns\n -------\n :class:`Layer`\n A :class:`AtrousConv1dLayer` object\n\n \"\"\"\n\n if W_init_args is None:\n W_init_args = {}\n if b_init_args is None:\n b_init_args = {}\n\n return Conv1dLayer(\n prev_layer=layer,\n act=act,\n shape=(filter_size, int(layer.outputs.get_shape()[-1]), n_filter),\n stride=stride,\n padding=padding,\n dilation_rate=dilation,\n data_format=data_format,\n W_init=W_init,\n b_init=b_init,\n W_init_args=W_init_args,\n b_init_args=b_init_args,\n name=name,\n )\n\n\nclass AtrousConv2dLayer(Layer):\n \"\"\"The :class:`AtrousConv2dLayer` class is 2D atrous convolution (a.k.a. convolution with holes or dilated\n convolution) 2D layer, see `tf.nn.atrous_conv2d <https://www.tensorflow.org/versions/master/api_docs/python/nn.html#atrous_conv2d>`__.\n\n Parameters\n ----------\n layer : :class:`Layer`\n Previous layer with a 4D output tensor in the shape of (batch, height, width, channels).\n n_filter : int\n The number of filters.\n filter_size : tuple of int\n The filter size: (height, width).\n rate : int\n The stride that we sample input values in the height and width dimensions.\n This equals the rate that we up-sample the filters by inserting zeros across the height and width dimensions.\n In the literature, this parameter is sometimes mentioned as input stride or dilation.\n act : activation function\n The activation function of this layer.\n padding : str\n The padding algorithm type: \"SAME\" or \"VALID\".\n W_init : initializer\n The initializer for the weight matrix.\n b_init : initializer or None\n The initializer for the bias vector. If None, skip biases.\n W_init_args : dictionary\n The arguments for the weight matrix initializer.\n b_init_args : dictionary\n The arguments for the bias vector initializer.\n name : str\n A unique layer name.\n\n \"\"\"\n\n def __init__(self,\n prev_layer,\n n_filter=32,\n filter_size=(3, 3),\n rate=2,\n act=tf.identity,\n padding='SAME',\n W_init=tf.truncated_normal_initializer(stddev=0.02),\n b_init=tf.constant_initializer(value=0.0),\n W_init_args=None,\n b_init_args=None,\n name='atrou2d'):\n if W_init_args is None:\n W_init_args = {}\n if b_init_args is None:\n b_init_args = {}\n\n Layer.__init__(self, prev_layer=prev_layer, name=name)\n self.inputs = prev_layer.outputs\n if act is None:\n act = tf.identity\n logging.info(\"AtrousConv2dLayer %s: n_filter:%d filter_size:%s rate:%d pad:%s act:%s\" % (self.name, n_filter, filter_size, rate, padding, act.__name__))\n with tf.variable_scope(name):\n shape = [filter_size[0], filter_size[1], int(self.inputs.get_shape()[-1]), n_filter]\n filters = tf.get_variable(name='filter', shape=shape, initializer=W_init, dtype=LayersConfig.tf_dtype, **W_init_args)\n if b_init:\n b = tf.get_variable(name='b', shape=(n_filter), initializer=b_init, dtype=LayersConfig.tf_dtype, **b_init_args)\n self.outputs = act(tf.nn.atrous_conv2d(self.inputs, filters, rate, padding) + b)\n else:\n self.outputs = act(tf.nn.atrous_conv2d(self.inputs, filters, rate, padding))\n\n # self.all_layers = list(layer.all_layers)\n # self.all_params = list(layer.all_params)\n # self.all_drop = dict(layer.all_drop)\n self.all_layers.append(self.outputs)\n if b_init:\n self.all_params.extend([filters, b])\n else:\n self.all_params.append(filters)\n\n\nclass _SeparableConv2dLayer(Layer): # TODO\n \"\"\"The :class:`SeparableConv2dLayer` class is 2D convolution with separable filters, see `tf.layers.separable_conv2d <https://www.tensorflow.org/api_docs/python/tf/layers/separable_conv2d>`__.\n\n This layer has not been fully tested yet.\n\n Parameters\n ----------\n layer : :class:`Layer`\n Previous layer with a 4D output tensor in the shape of [batch, height, width, channels].\n n_filter : int\n The number of filters.\n filter_size : tuple of int\n The filter size (height, width).\n strides : tuple of int\n The strides (height, width).\n This can be a single integer if you want to specify the same value for all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1.\n padding : str\n The type of padding algorithm: \"SAME\" or \"VALID\"\n data_format : str\n One of channels_last (Default) or channels_first.\n The order must match the input dimensions.\n channels_last corresponds to inputs with shapedata_format = 'NWHC' (batch, width, height, channels) while\n channels_first corresponds to inputs with shape [batch, channels, width, height].\n dilation_rate : int or tuple of ints\n The dilation rate of the convolution.\n It can be a single integer if you want to specify the same value for all spatial dimensions.\n Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1.\n depth_multiplier : int\n The number of depthwise convolution output channels for each input channel.\n The total number of depthwise convolution output channels will be equal to num_filters_in * depth_multiplier.\n act : activation function\n The activation function of this layer.\n use_bias : boolean\n Whether the layer uses a bias\n depthwise_initializer : initializer\n The initializer for the depthwise convolution kernel.\n pointwise_initializer : initializer\n The initializer for the pointwise convolution kernel.\n bias_initializer : initializer\n The initializer for the bias vector. If None, skip bias.\n depthwise_regularizer : regularizer\n Optional regularizer for the depthwise convolution kernel.\n pointwise_regularizer : regularizer\n Optional regularizer for the pointwise convolution kernel.\n bias_regularizer : regularizer\n Optional regularizer for the bias vector.\n activity_regularizer : regularizer\n Regularizer function for the output.\n name : str\n A unique layer name.\n\n \"\"\"\n\n def __init__(self,\n prev_layer,\n n_filter,\n filter_size=5,\n strides=(1, 1),\n padding='valid',\n data_format='channels_last',\n dilation_rate=(1, 1),\n depth_multiplier=1,\n act=tf.identity,\n use_bias=True,\n depthwise_initializer=None,\n pointwise_initializer=None,\n bias_initializer=tf.zeros_initializer,\n depthwise_regularizer=None,\n pointwise_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n name='atrou2d'):\n Layer.__init__(self, prev_layer=prev_layer, name=name)\n self.inputs = prev_layer.outputs\n if tf.__version__ > \"0.12.1\":\n raise Exception(\"This layer only supports for TF 1.0+\")\n\n bias_initializer = bias_initializer()\n\n logging.info(\"SeparableConv2dLayer %s: n_filter:%d filter_size:%s strides:%s padding:%s dilation_rate:%s depth_multiplier:%s act:%s\" %\n (self.name, n_filter, filter_size, str(strides), padding, str(dilation_rate), str(depth_multiplier), act.__name__))\n\n with tf.variable_scope(name) as vs:\n self.outputs = tf.layers.separable_conv2d(\n self.inputs,\n filters=n_filter,\n kernel_size=filter_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n depth_multiplier=depth_multiplier,\n activation=act,\n use_bias=use_bias,\n depthwise_initializer=depthwise_initializer,\n pointwise_initializer=pointwise_initializer,\n bias_initializer=bias_initializer,\n depthwise_regularizer=depthwise_regularizer,\n pointwise_regularizer=pointwise_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n )\n # trainable=True, name=None, reuse=None)\n\n variables = tf.get_collection(TF_GRAPHKEYS_VARIABLES, scope=vs.name)\n\n # self.all_layers = list(layer.all_layers)\n # self.all_params = list(layer.all_params)\n # self.all_drop = dict(layer.all_drop)\n self.all_layers.append(self.outputs)\n self.all_params.extend(variables)\n\n\ndef deconv2d_bilinear_upsampling_initializer(shape):\n \"\"\"Returns the initializer that can be passed to DeConv2dLayer for initializ ingthe\n weights in correspondence to channel-wise bilinear up-sampling.\n Used in segmentation approaches such as [FCN](https://arxiv.org/abs/1605.06211)\n\n Parameters\n ----------\n shape : tuple of int\n The shape of the filters, [height, width, output_channels, in_channels].\n It must match the shape passed to DeConv2dLayer.\n\n Returns\n -------\n ``tf.constant_initializer``\n A constant initializer with weights set to correspond to per channel bilinear upsampling\n when passed as W_int in DeConv2dLayer\n\n Examples\n --------\n - Upsampling by a factor of 2, ie e.g 100->200\n >>> rescale_factor = 2\n >>> filter_size = (2 * rescale_factor - rescale_factor % 2) #Corresponding bilinear filter size\n >>> num_in_channels = 3\n >>> num_out_channels = 3\n >>> deconv_filter_shape = (filter_size, filter_size, num_out_channels, num_in_channels)\n >>> x = tf.placeholder(tf.float32, (1, imsize, imsize, num_channels))\n >>> net = tl.layers.InputLayer(x, name='input_layer')\n >>> bilinear_init = deconv2d_bilinear_upsampling_initializer(shape=filter_shape)\n >>> net = tl.layers.DeConv2dLayer(net,\n ... shape=filter_shape,\n ... output_shape=(1, imsize*rescale_factor, imsize*rescale_factor, num_out_channels),\n ... strides=(1, rescale_factor, rescale_factor, 1),\n ... W_init=bilinear_init,\n ... padding='SAME',\n ... act=tf.identity, name='g/h1/decon2d')\n\n \"\"\"\n if shape[0] != shape[1]:\n raise Exception('deconv2d_bilinear_upsampling_initializer only supports symmetrical filter sizes')\n if shape[3] < shape[2]:\n raise Exception('deconv2d_bilinear_upsampling_initializer behaviour is not defined for num_in_channels < num_out_channels ')\n\n filter_size = shape[0]\n num_out_channels = shape[2]\n num_in_channels = shape[3]\n\n # Create bilinear filter kernel as numpy array\n bilinear_kernel = np.zeros([filter_size, filter_size], dtype=np.float32)\n scale_factor = (filter_size + 1) // 2\n if filter_size % 2 == 1:\n center = scale_factor - 1\n else:\n center = scale_factor - 0.5\n for x in range(filter_size):\n for y in range(filter_size):\n bilinear_kernel[x, y] = (1 - abs(x - center) / scale_factor) * \\\n (1 - abs(y - center) / scale_factor)\n weights = np.zeros((filter_size, filter_size, num_out_channels, num_in_channels))\n for i in range(num_out_channels):\n weights[:, :, i, i] = bilinear_kernel\n\n # assign numpy array to constant_initalizer and pass to get_variable\n bilinear_weights_init = tf.constant_initializer(value=weights, dtype=LayersConfig.tf_dtype) # dtype=tf.float32)\n return bilinear_weights_init\n\n\ndef conv1d(\n layer,\n n_filter=32,\n filter_size=5,\n stride=1,\n dilation_rate=1,\n act=tf.identity,\n padding='SAME',\n data_format=\"NWC\",\n W_init=tf.truncated_normal_initializer(stddev=0.02),\n b_init=tf.constant_initializer(value=0.0),\n W_init_args=None,\n b_init_args=None,\n name='conv1d',\n):\n \"\"\"Simplified version of :class:`Conv1dLayer`.\n\n Parameters\n ----------\n layer : :class:`Layer`\n Previous layer\n n_filter : int\n The number of filters\n filter_size : int\n The filter size\n stride : int\n The stride step\n dilation_rate : int\n Specifying the dilation rate to use for dilated convolution.\n act : activation function\n The function that is applied to the layer activations\n padding : str\n The padding algorithm type: \"SAME\" or \"VALID\".\n data_format : str\n Default is 'NWC' as it is a 1D CNN.\n W_init : initializer\n The initializer for the weight matrix.\n b_init : initializer or None\n The initializer for the bias vector. If None, skip biases.\n W_init_args : dictionary\n The arguments for the weight matrix initializer.\n b_init_args : dictionary\n The arguments for the bias vector initializer.\n name : str\n A unique layer name\n\n Returns\n -------\n :class:`Layer`\n A :class:`Conv1dLayer` object.\n\n Examples\n ---------\n >>> x = tf.placeholder(tf.float32, (batch_size, width))\n >>> y_ = tf.placeholder(tf.int64, shape=(batch_size,))\n >>> n = InputLayer(x, name='in')\n >>> n = ReshapeLayer(n, (-1, width, 1), name='rs')\n >>> n = Conv1d(n, 64, 3, 1, act=tf.nn.relu, name='c1')\n >>> n = MaxPool1d(n, 2, 2, padding='valid', name='m1')\n >>> n = Conv1d(n, 128, 3, 1, act=tf.nn.relu, name='c2')\n >>> n = MaxPool1d(n, 2, 2, padding='valid', name='m2')\n >>> n = Conv1d(n, 128, 3, 1, act=tf.nn.relu, name='c3')\n >>> n = MaxPool1d(n, 2, 2, padding='valid', name='m3')\n >>> n = FlattenLayer(n, name='f')\n >>> n = DenseLayer(n, 500, tf.nn.relu, name='d1')\n >>> n = DenseLayer(n, 100, tf.nn.relu, name='d2')\n >>> n = DenseLayer(n, 2, tf.identity, name='o')\n\n \"\"\"\n\n if W_init_args is None:\n W_init_args = {}\n if b_init_args is None:\n b_init_args = {}\n\n return Conv1dLayer(\n prev_layer=layer,\n act=act,\n shape=(filter_size, int(layer.outputs.get_shape()[-1]), n_filter),\n stride=stride,\n dilation_rate=dilation_rate,\n padding=padding,\n data_format=data_format,\n W_init=W_init,\n b_init=b_init,\n W_init_args=W_init_args,\n b_init_args=b_init_args,\n name=name,\n )\n\n\n# TODO: DeConv1d\n\n\ndef conv2d(\n layer,\n n_filter=32,\n filter_size=(3, 3),\n strides=(1, 1),\n act=tf.identity,\n padding='SAME',\n W_init=tf.truncated_normal_initializer(stddev=0.02),\n b_init=tf.constant_initializer(value=0.0),\n W_init_args=None,\n b_init_args=None,\n use_cudnn_on_gpu=None,\n data_format=None,\n name='conv2d',\n):\n \"\"\"Simplified version of :class:`Conv2dLayer`.\n\n Parameters\n ----------\n layer : :class:`Layer`\n Previous layer.\n n_filter : int\n The number of filters.\n filter_size : tuple of int\n The filter size (height, width).\n strides : tuple of int\n The sliding window strides of corresponding input dimensions.\n It must be in the same order as the ``shape`` parameter.\n act : activation function\n The activation function of this layer.\n padding : str\n The padding algorithm type: \"SAME\" or \"VALID\".\n W_init : initializer\n The initializer for the the weight matrix.\n b_init : initializer or None\n The initializer for the the bias vector. If None, skip biases.\n W_init_args : dictionary\n The arguments for the weight matrix initializer.\n b_init_args : dictionary\n The arguments for the bias vector initializer.\n use_cudnn_on_gpu : bool\n Default is False.\n data_format : str\n \"NHWC\" or \"NCHW\", default is \"NHWC\".\n name : str\n A unique layer name.\n\n Returns\n -------\n :class:`Layer`\n A :class:`Conv2dLayer` object.\n\n Examples\n --------\n >>> net = InputLayer(x, name='inputs')\n >>> net = Conv2d(net, 64, (3, 3), act=tf.nn.relu, name='conv1_1')\n >>> net = Conv2d(net, 64, (3, 3), act=tf.nn.relu, name='conv1_2')\n >>> net = MaxPool2d(net, (2, 2), name='pool1')\n >>> net = Conv2d(net, 128, (3, 3), act=tf.nn.relu, name='conv2_1')\n >>> net = Conv2d(net, 128, (3, 3), act=tf.nn.relu, name='conv2_2')\n >>> net = MaxPool2d(net, (2, 2), name='pool2')\n\n \"\"\"\n\n if W_init_args is None:\n W_init_args = {}\n if b_init_args is None:\n b_init_args = {}\n\n if len(strides) != 2:\n raise ValueError(\"len(strides) should be 2, Conv2d and Conv2dLayer are different.\")\n\n try:\n pre_channel = int(layer.outputs.get_shape()[-1])\n except Exception: # if pre_channel is ?, it happens when using Spatial Transformer Net\n pre_channel = 1\n logging.info(\"[warnings] unknow input channels, set to 1\")\n return Conv2dLayer(\n layer,\n act=act,\n shape=(filter_size[0], filter_size[1], pre_channel, n_filter), # 32 features for each 5x5 patch\n strides=(1, strides[0], strides[1], 1),\n padding=padding,\n W_init=W_init,\n W_init_args=W_init_args,\n b_init=b_init,\n b_init_args=b_init_args,\n use_cudnn_on_gpu=use_cudnn_on_gpu,\n data_format=data_format,\n name=name)\n\n\ndef deconv2d(layer,\n n_filter=32,\n filter_size=(3, 3),\n out_size=(30, 30),\n strides=(2, 2),\n padding='SAME',\n batch_size=None,\n act=tf.identity,\n W_init=tf.truncated_normal_initializer(stddev=0.02),\n b_init=tf.constant_initializer(value=0.0),\n W_init_args=None,\n b_init_args=None,\n name='decnn2d'):\n \"\"\"Simplified version of :class:`DeConv2dLayer`.\n\n Parameters\n ----------\n layer : :class:`Layer`\n Previous layer.\n n_filter : int\n The number of filters.\n filter_size : tuple of int\n The filter size (height, width).\n out_size : tuple of int\n Require if TF version < 1.3, (height, width) of output.\n strides : tuple of int\n The stride step (height, width).\n padding : str\n The padding algorithm type: \"SAME\" or \"VALID\".\n batch_size : int\n Require if TF version < 1.3, int or None.\n If None, try to find the `batch_size` from the first dim of net.outputs (you should define the `batch_size` in the input placeholder).\n act : activation function\n The activation function of this layer.\n W_init : initializer\n The initializer for the weight matrix.\n b_init : initializer or None\n The initializer for the bias vector. If None, skip biases.\n W_init_args : dictionary\n The arguments for the weight matrix initializer.\n b_init_args : dictionary\n The arguments for the bias vector initializer.\n name : str\n A unique layer name.\n\n Returns\n -------\n :class:`Layer`\n A :class:`DeConv2dLayer` object.\n\n \"\"\"\n if W_init_args is None:\n W_init_args = {}\n if b_init_args is None:\n b_init_args = {}\n if act is None:\n act = tf.identity\n if len(strides) != 2:\n raise ValueError(\"len(strides) should be 2, DeConv2d and DeConv2dLayer are different.\")\n if tf.__version__ > '1.3':\n logging.info(\"DeConv2d %s: n_filters:%s strides:%s pad:%s act:%s\" % (name, str(n_filter), str(strides), padding, act.__name__))\n inputs = layer.outputs\n scope_name = tf.get_variable_scope().name\n # if scope_name:\n # whole_name = scope_name + '/' + name\n # else:\n # whole_name = name\n net_new = Layer(name=name) #whole_name)\n # with tf.name_scope(name):\n with tf.variable_scope(name) as vs:\n net_new.outputs = tf.contrib.layers.conv2d_transpose(\n inputs=inputs,\n num_outputs=n_filter,\n kernel_size=filter_size,\n stride=strides,\n padding=padding,\n activation_fn=act,\n weights_initializer=W_init,\n biases_initializer=b_init,\n scope=name)\n new_variables = tf.get_collection(TF_GRAPHKEYS_VARIABLES, scope=vs.name)\n net_new.all_layers = list(layer.all_layers)\n net_new.all_params = list(layer.all_params)\n net_new.all_drop = dict(layer.all_drop)\n net_new.all_layers.extend([net_new.outputs])\n net_new.all_params.extend(new_variables)\n return net_new\n else:\n if batch_size is None:\n # batch_size = tf.shape(net.outputs)[0]\n fixed_batch_size = layer.outputs.get_shape().with_rank_at_least(1)[0]\n if fixed_batch_size.value:\n batch_size = fixed_batch_size.value\n else:\n from tensorflow.python.ops import array_ops\n batch_size = array_ops.shape(layer.outputs)[0]\n return DeConv2dLayer(\n prev_layer=layer,\n act=act,\n shape=(filter_size[0], filter_size[1], n_filter, int(layer.outputs.get_shape()[-1])),\n output_shape=(batch_size, int(out_size[0]), int(out_size[1]), n_filter),\n strides=(1, strides[0], strides[1], 1),\n padding=padding,\n W_init=W_init,\n b_init=b_init,\n W_init_args=W_init_args,\n b_init_args=b_init_args,\n name=name)\n\n\nclass DeConv3d(Layer):\n \"\"\"Simplified version of The :class:`DeConv3dLayer`, see `tf.contrib.layers.conv3d_transpose <https://www.tensorflow.org/api_docs/python/tf/contrib/layers/conv3d_transpose>`__.\n\n Parameters\n ----------\n layer : :class:`Layer`\n Previous layer.\n n_filter : int\n The number of filters.\n filter_size : tuple of int\n The filter size (depth, height, width).\n stride : tuple of int\n The stride step (depth, height, width).\n padding : str\n The padding algorithm type: \"SAME\" or \"VALID\".\n act : activation function\n The activation function of this layer.\n W_init : initializer\n The initializer for the weight matrix.\n b_init : initializer or None\n The initializer for the bias vector. If None, skip bias.\n name : str\n A unique layer name.\n\n \"\"\"\n\n def __init__(self,\n prev_layer,\n n_filter=32,\n filter_size=(3, 3, 3),\n strides=(2, 2, 2),\n padding='SAME',\n act=tf.identity,\n W_init=tf.truncated_normal_initializer(stddev=0.02),\n b_init=tf.constant_initializer(value=0.0),\n name='decnn3d'):\n Layer.__init__(self, prev_layer=prev_layer, name=name)\n self.inputs = prev_layer.outputs\n logging.info(\"DeConv3d %s: n_filters:%s strides:%s pad:%s act:%s\" % (name, str(n_filter), str(strides), padding, act.__name__))\n\n with tf.variable_scope(name) as vs:\n self.outputs = tf.contrib.layers.conv3d_transpose(\n num_outputs=n_filter,\n kernel_size=filter_size,\n stride=strides,\n padding=padding,\n activation_fn=act,\n weights_initializer=W_init,\n biases_initializer=b_init,\n scope=name,\n )\n new_variables = tf.get_collection(TF_GRAPHKEYS_VARIABLES, scope=vs.name)\n\n # self.all_layers = list(layer.all_layers)\n # self.all_params = list(layer.all_params)\n # self.all_drop = dict(layer.all_drop)\n self.all_layers.append(self.outputs)\n self.all_params.extend(new_variables)\n\n\nclass DepthwiseConv2d(Layer):\n \"\"\"Separable/Depthwise Convolutional 2D layer, see `tf.nn.depthwise_conv2d <https://www.tensorflow.org/versions/master/api_docs/python/tf/nn/depthwise_conv2d>`__.\n\n Input:\n 4-D Tensor (batch, height, width, in_channels).\n Output:\n 4-D Tensor (batch, new height, new width, in_channels * depth_multiplier).\n\n Parameters\n ------------\n layer : :class:`Layer`\n Previous layer.\n filter_size : tuple of int\n The filter size (height, width).\n stride : tuple of int\n The stride step (height, width).\n act : activation function\n The activation function of this layer.\n padding : str\n The padding algorithm type: \"SAME\" or \"VALID\".\n dilation_rate: tuple of 2 int\n The dilation rate in which we sample input values across the height and width dimensions in atrous convolution. If it is greater than 1, then all values of strides must be 1.\n depth_multiplier : int\n The number of channels to expand to.\n W_init : initializer\n The initializer for the weight matrix.\n b_init : initializer or None\n The initializer for the bias vector. If None, skip bias.\n W_init_args : dictionary\n The arguments for the weight matrix initializer.\n b_init_args : dictionary\n The arguments for the bias vector initializer.\n name : str\n A unique layer name.\n\n Examples\n ---------\n >>> x = tf.placeholder(tf.float32, shape=[None, 28, 28, 1], name='x')\n >>> net = InputLayer(x, name='in')\n >>> net = Conv2d(net, 32, (3, 3), (1, 1), name='conv1')\n >>> net = MaxPool2d(net, (2, 2), name='pool1')\n >>> net = DepthwiseConv2d(net, (3, 3), (1, 1), act=tf.nn.relu, name='dethwise1')\n >>> net = Conv2d(net, 64, (1, 1), (1, 1), act=tf.nn.relu, name='conv2')\n\n References\n -----------\n - tflearn's `grouped_conv_2d <https://github.com/tflearn/tflearn/blob/3e0c3298ff508394f3ef191bcd7d732eb8860b2e/tflearn/layers/conv.py>`__\n - keras's `separableconv2d <https://keras.io/layers/convolutional/#separableconv2d>`__\n\n \"\"\" # # https://zhuanlan.zhihu.com/p/31551004 https://github.com/xiaohu2015/DeepLearning_tutorials/blob/master/CNNs/MobileNet.py\n\n def __init__(\n self,\n prev_layer,\n shape=(3, 3),\n strides=(1, 1),\n act=tf.identity,\n padding='SAME',\n dilation_rate=(1, 1),\n depth_multiplier=1,\n W_init=tf.truncated_normal_initializer(stddev=0.02),\n b_init=tf.constant_initializer(value=0.0),\n W_init_args=None,\n b_init_args=None,\n name='depthwise_conv2d',\n ):\n if W_init_args is None:\n W_init_args = {}\n if b_init_args is None:\n b_init_args = {}\n\n Layer.__init__(self, prev_layer=prev_layer, name=name)\n self.inputs = prev_layer.outputs\n\n if act is None:\n act = tf.identity\n\n logging.info(\"DepthwiseConv2d %s: shape:%s strides:%s pad:%s act:%s\" % (self.name, str(shape), str(strides), padding, act.__name__))\n try:\n pre_channel = int(prev_layer.outputs.get_shape()[-1])\n except Exception: # if pre_channel is ?, it happens when using Spatial Transformer Net\n pre_channel = 1\n logging.info(\"[warnings] unknow input channels, set to 1\")\n\n shape = [shape[0], shape[1], pre_channel, depth_multiplier]\n\n if len(strides) == 2:\n strides = [1, strides[0], strides[1], 1]\n\n assert len(strides) == 4, \"len(strides) should be 4.\"\n\n with tf.variable_scope(name):\n W = tf.get_variable(\n name='W_depthwise2d', shape=shape, initializer=W_init, dtype=LayersConfig.tf_dtype,\n **W_init_args) # [filter_height, filter_width, in_channels, depth_multiplier]\n if b_init:\n b = tf.get_variable(\n name='b_depthwise2d', shape=(pre_channel * depth_multiplier), initializer=b_init, dtype=LayersConfig.tf_dtype, **b_init_args)\n self.outputs = act(tf.nn.depthwise_conv2d(self.inputs, W, strides=strides, padding=padding, rate=dilation_rate) + b)\n else:\n self.outputs = act(tf.nn.depthwise_conv2d(self.inputs, W, strides=strides, padding=padding, rate=dilation_rate))\n\n # self.all_layers = list(layer.all_layers)\n # self.all_params = list(layer.all_params)\n # self.all_drop = dict(layer.all_drop)\n self.all_layers.append(self.outputs)\n if b_init:\n self.all_params.extend([W, b])\n else:\n self.all_params.append(W)\n\n\nclass SeparableConv2d(Layer):\n \"\"\"The :class:`SeparableConv2d` class is a 2D depthwise separable convolutional layer, see `tf.layers.separable_conv2d <https://www.tensorflow.org/api_docs/python/tf/layers/separable_conv2d>`__.\n\n This layer performs a depthwise convolution that acts separately on channels, followed by a pointwise convolution that mixes channels.\n While :class:`DepthwiseConv2d` performs depthwise convolution only, which allow us to add batch normalization between depthwise and pointwise convolution.\n\n Parameters\n ------------\n layer : :class:`Layer`\n Previous layer.\n n_filter : int\n The dimensionality of the output space (i.e. the number of filters in the convolution).\n filter_size : tuple/list of 2 int\n Specifying the spatial dimensions of the filters. Can be a single integer to specify the same value for all spatial dimensions.\n strides : tuple/list of 2 int\n Specifying the strides of the convolution. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1.\n padding : str\n One of \"valid\" or \"same\" (case-insensitive).\n data_format : str\n One of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, height, width, channels) while channels_first corresponds to inputs with shape (batch, channels, height, width).\n dilation_rate : integer or tuple/list of 2 int\n Specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1.\n depth_multiplier : int\n The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to num_filters_in * depth_multiplier.\n depthwise_init : initializer\n for the depthwise convolution kernel.\n pointwise_init : initializer\n For the pointwise convolution kernel.\n b_init : initializer\n For the bias vector. If None, ignore bias in the pointwise part only.\n name : a str\n A unique layer name.\n\n \"\"\"\n\n def __init__(\n self,\n prev_layer,\n n_filter=100,\n filter_size=(3, 3),\n strides=(1, 1),\n act=tf.identity,\n padding='valid',\n data_format='channels_last',\n dilation_rate=(1, 1),\n depth_multiplier=1,\n # activation=None,\n # use_bias=True,\n depthwise_init=None,\n pointwise_init=None,\n b_init=tf.zeros_initializer(),\n # depthwise_regularizer=None,\n # pointwise_regularizer=None,\n # bias_regularizer=None,\n # activity_regularizer=None,\n # depthwise_constraint=None,\n # pointwise_constraint=None,\n # W_init=tf.truncated_normal_initializer(stddev=0.1),\n # b_init=tf.constant_initializer(value=0.0),\n # W_init_args=None,\n # b_init_args=None,\n name='seperable',\n ):\n # if W_init_args is None:\n # W_init_args = {}\n # if b_init_args is None:\n # b_init_args = {}\n\n Layer.__init__(self, prev_layer=prev_layer, name=name)\n self.inputs = prev_layer.outputs\n # print(self.name, n_filter, str(filter_size), str(strides), depth_multiplier, act.__name__)\n logging.info(\"SeparableConv2d %s: n_filter:%d filter_size:%s filter_size:%s depth_multiplier:%d act:%s\" \\\n % (self.name, n_filter, str(filter_size), str(strides), depth_multiplier, act.__name__))\n\n with tf.variable_scope(name) as vs:\n self.outputs = tf.layers.separable_conv2d(\n inputs=self.inputs,\n filters=n_filter,\n kernel_size=filter_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n depth_multiplier=depth_multiplier,\n activation=act,\n use_bias=(True if b_init is not None else False),\n depthwise_initializer=depthwise_init,\n pointwise_initializer=pointwise_init,\n bias_initializer=b_init,\n # depthwise_regularizer=None,\n # pointwise_regularizer=None,\n # bias_regularizer=None,\n # activity_regularizer=None,\n # depthwise_constraint=None,\n # pointwise_constraint=None,\n # bias_constraint=None,\n trainable=True,\n name=None)\n new_variables = tf.get_collection(TF_GRAPHKEYS_VARIABLES, scope=vs.name)\n\n self.all_layers.append(self.outputs)\n self.all_params.extend(new_variables)\n\n\nclass GroupConv2d(Layer):\n \"\"\"The :class:`GroupConv2d` class is 2D grouped convolution, see `here <https://blog.yani.io/filter-group-tutorial/>`__.\n\n Parameters\n --------------\n layer : :class:`Layer`\n Previous layer.\n n_filter : int\n The number of filters.\n filter_size : int\n The filter size.\n stride : int\n The stride step.\n n_group : int\n The number of groups.\n act : activation function\n The activation function of this layer.\n padding : str\n The padding algorithm type: \"SAME\" or \"VALID\".\n W_init : initializer\n The initializer for the weight matrix.\n b_init : initializer or None\n The initializer for the bias vector. If None, skip biases.\n W_init_args : dictionary\n The arguments for the weight matrix initializer.\n b_init_args : dictionary\n The arguments for the bias vector initializer.\n name : str\n A unique layer name.\n \"\"\"\n\n def __init__(\n self,\n prev_layer=None,\n n_filter=32,\n filter_size=(3, 3),\n strides=(2, 2),\n n_group=2,\n act=tf.identity,\n padding='SAME',\n W_init=tf.truncated_normal_initializer(stddev=0.02),\n b_init=tf.constant_initializer(value=0.0),\n W_init_args=None,\n b_init_args=None,\n name='groupconv',\n ): # Windaway\n if W_init_args is None:\n W_init_args = {}\n if b_init_args is None:\n b_init_args = {}\n\n Layer.__init__(self, prev_layer=prev_layer, name=name)\n self.inputs = prev_layer.outputs\n groupConv = lambda i, k: tf.nn.conv2d(i, k, strides=[1, strides[0], strides[1], 1], padding=padding)\n channels = int(self.inputs.get_shape()[-1])\n\n logging.info(\"GroupConv2d %s: n_filter:%d size:%s strides:%s n_group:%d pad:%s act:%s\" % (self.name, n_filter, str(filter_size), str(strides), n_group,\n padding, act.__name__))\n with tf.variable_scope(name):\n We = tf.get_variable(\n name='W',\n shape=[filter_size[0], filter_size[1], channels / n_group, n_filter],\n initializer=W_init,\n dtype=LayersConfig.tf_dtype,\n trainable=True,\n **W_init_args)\n if b_init:\n bi = tf.get_variable(name='b', shape=n_filter, initializer=b_init, dtype=LayersConfig.tf_dtype, trainable=True, **b_init_args)\n if n_group == 1:\n conv = groupConv(self.inputs, We)\n else:\n inputGroups = tf.split(axis=3, num_or_size_splits=n_group, value=self.inputs)\n weightsGroups = tf.split(axis=3, num_or_size_splits=n_group, value=We)\n convGroups = [groupConv(i, k) for i, k in zip(inputGroups, weightsGroups)]\n conv = tf.concat(axis=3, values=convGroups)\n if b_init:\n conv = tf.add(conv, bi, name='add')\n\n self.outputs = act(conv)\n # self.all_layers = list(layer.all_layers)\n # self.all_params = list(layer.all_params)\n # self.all_drop = dict(layer.all_drop)\n self.all_layers.append(self.outputs)\n if b_init:\n self.all_params.extend([We, bi])\n else:\n self.all_params.append(We)\n\n\n# Alias\nAtrousConv1dLayer = atrous_conv1d\nConv1d = conv1d\nConv2d = conv2d\nDeConv2d = deconv2d\n" ]
[ [ "tensorflow.placeholder" ], [ "tensorflow.get_variable", "tensorflow.concat", "tensorflow.python.ops.array_ops.shape", "tensorflow.stack", "tensorflow.cast", "tensorflow.nn.conv2d_transpose", "tensorflow.nn.atrous_conv2d", "tensorflow.nn.depthwise_conv2d", "tensorflow.nn.conv2d", "tensorflow.contrib.layers.conv2d_transpose", "tensorflow.get_collection", "tensorflow.floor", "tensorflow.truncated_normal_initializer", "tensorflow.contrib.layers.conv3d_transpose", "tensorflow.add", "tensorflow.ceil", "tensorflow.nn.conv3d_transpose", "tensorflow.tile", "tensorflow.nn.convolution", "tensorflow.gather_nd", "tensorflow.shape", "tensorflow.image.resize_images", "tensorflow.zeros_initializer", "tensorflow.nn.conv3d", "tensorflow.split", "tensorflow.transpose", "tensorflow.range", "tensorflow.reshape", "tensorflow.expand_dims", "tensorflow.constant_initializer", "tensorflow.layers.separable_conv2d", "tensorflow.variable_scope", "tensorflow.get_variable_scope" ] ]
steffanschlein/cythonwrapper
[ "ef30a3bc1a24024b9845dad4aa8a42e05219bd91" ]
[ "test/test_type_conversions.py" ]
[ "import numpy as np\nfrom pywrap.testing import cython_extension_from\nfrom nose.tools import assert_equal, assert_raises\n\n\ndef test_bool_in_bool_out():\n with cython_extension_from(\"boolinboolout.hpp\"):\n from boolinboolout import A\n a = A()\n b = False\n assert_equal(not b, a.neg(b))\n\n\ndef test_double_in_double_out():\n with cython_extension_from(\"doubleindoubleout.hpp\"):\n from doubleindoubleout import A\n a = A()\n d = 3.213\n assert_equal(d + 2.0, a.plus2(d))\n\n\ndef test_complex_arg():\n with cython_extension_from(\"complexarg.hpp\"):\n from complexarg import A, B\n a = A()\n b = B(a)\n assert_equal(b.get_string(), \"test\")\n\n\ndef test_map():\n with cython_extension_from(\"map.hpp\"):\n from map import lookup\n m = {\"test\": 0}\n assert_equal(lookup(m), 0)\n\n\ndef test_vector():\n with cython_extension_from(\"vector.hpp\"):\n from vector import A\n a = A()\n v = np.array([2.0, 1.0, 3.0])\n n = a.norm(v)\n assert_equal(n, 14.0)\n\n\ndef test_string_in_string_out():\n with cython_extension_from(\"stringinstringout.hpp\"):\n from stringinstringout import A\n a = A()\n s = \"This is a sentence\"\n assert_equal(s + \".\", a.end(s))\n\n\ndef test_string_vector():\n with cython_extension_from(\"stringvector.hpp\"):\n from stringvector import A\n a = A()\n substrings = [\"AB\", \"CD\", \"EF\"]\n res = a.concat(substrings)\n assert_equal(res, \"ABCDEF\")\n\n\ndef test_complex_ptr_arg():\n with cython_extension_from(\"complexptrarg.hpp\"):\n from complexptrarg import A, B\n a = A()\n b = B(a)\n assert_equal(b.get_string(), \"test\")\n\n\ndef test_factory():\n with cython_extension_from(\"factory.hpp\"):\n from factory import AFactory\n factory = AFactory()\n a = factory.make()\n assert_equal(5, a.get())\n\n\ndef test_primitive_pointers():\n with cython_extension_from(\"primitivepointers.hpp\"):\n from primitivepointers import fun1\n assert_equal(fun1(5), 6)\n\n\ndef test_cstring():\n with cython_extension_from(\"cstring.hpp\"):\n from cstring import length, helloworld\n assert_equal(length(\"test\"), 4)\n assert_equal(helloworld(), \"hello world\")\n\n\ndef test_fixed_length_array():\n with cython_extension_from(\"fixedarray.hpp\"):\n from fixedarray import to_string\n assert_equal(to_string([1, 2, 3, 4, 5]), \"[1, 2, 3, 4, 5]\")\n assert_raises(ValueError, to_string, [1, 2, 3, 4])\n assert_raises(TypeError, to_string, [1, 2, 3, 4, \"a\"])\n\n\ndef test_missing_default_ctor():\n with cython_extension_from(\"missingdefaultctor.hpp\", hide_errors=True):\n assert_raises(ImportError, __import__, \"missingdefaultctor\")\n\n\ndef test_missing_assignment():\n with cython_extension_from(\"missingassignmentop.hpp\", hide_errors=True):\n assert_raises(ImportError, __import__, \"missingassignmentop\")\n\n\ndef test_exceptions():\n # A list of convertible exceptions can be found in the Cython docs:\n # http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html#exceptions\n with cython_extension_from(\"throwexception.hpp\"):\n from throwexception import (throw_bad_alloc, throw_bad_cast,\n throw_domain_error, throw_invalid_argument,\n throw_ios_base_failure,\n throw_out_of_range, throw_overflow_error,\n throw_range_error, throw_underflow_error,\n throw_other)\n assert_raises(MemoryError, throw_bad_alloc)\n assert_raises(TypeError, throw_bad_cast)\n assert_raises(ValueError, throw_domain_error)\n assert_raises(ValueError, throw_invalid_argument)\n assert_raises(IOError, throw_ios_base_failure)\n assert_raises(IndexError, throw_out_of_range)\n assert_raises(OverflowError, throw_overflow_error)\n assert_raises(ArithmeticError, throw_range_error)\n assert_raises(ArithmeticError, throw_underflow_error)\n assert_raises(RuntimeError, throw_other)\n" ]
[ [ "numpy.array" ] ]
DiNOV-Tokyo/uied-d
[ "c15d7e003dda13c24cfd0c17b4efb058dcc3b292" ]
[ "train_ResNet152.py" ]
[ "# https://qiita.com/daichimizuno/items/d1a255fa56960302bcc5\nfrom PIL import Image\nimport numpy as np\nimport glob\nimport os\nfrom keras.utils import np_utils\nfrom keras.models import Sequential, Model\nfrom keras.layers import Flatten, Dense, Input, Dropout\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom keras.applications.resnet import ResNet152\nfrom keras import optimizers\nfrom tensorflow.keras.optimizers import SGD\n\nroot = \"dataset\"\nfolder = os.listdir(root)\nimage_size = 224\ndense_size = len(folder)\nepochs = 3\nbatch_size = 16\n\nX = []\nY = []\nfor index, name in enumerate(folder):\n dir = \"./\" + root + \"/\" + name\n print(\"dir : \", dir)\n files = glob.glob(dir + \"/*\")\n print(\"number : \" + str(files.__len__()))\n for i, file in enumerate(files):\n try:\n image = Image.open(file)\n image = image.convert(\"RGB\")\n image = image.resize((image_size, image_size))\n data = np.asarray(image)\n X.append(data)\n Y.append(index)\n except :\n print(\"read image error\")\n\nX = np.array(X)\nY = np.array(Y)\nX = X.astype('float32')\nX = X / 255.0\n\nY = np_utils.to_categorical(Y, dense_size)\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.15)\n\ninput_tensor = Input(shape=(image_size, image_size, 3))\n#ResNet50 = ResNet50(include_top=False, weights='imagenet',input_tensor=input_tensor)\n#resnet101 = ResNet101(include_top=False, weights='imagenet',input_tensor=input_tensor)\nresnet152 = ResNet152(include_top=False, weights='imagenet',input_tensor=input_tensor)\n\ntop_model = Sequential()\ntop_model.add(Flatten(input_shape=resnet152.output_shape[1:]))\ntop_model.add(Dense(256, activation='relu'))\ntop_model.add(Dropout(0.5))\ntop_model.add(Dense(dense_size, activation='softmax'))\n\n#print(\"\\n\\n\")\n#print(ResNet50)\n#print(\"\\n\\n\")\n# ResNet50とFC層を結合してモデルを作成\ntop_model = Model(inputs=resnet152.input, outputs=top_model(resnet152.output))\n#resnet50_model = Model(inputs=resnet50.input, outputs=top_model(resnet50.output))\n\n\n\n#top_model = Model(input=ResNet50.input, output=top_model(ResNet50.output))\n#top_model.compile(loss='categorical_crossentropy',optimizer=optimizers.SGD(lr=1e-3, momentum=0.9),metrics=['accuracy'])\nopt= SGD(learning_rate= 0.01, momentum=0.9)\ntop_model.compile(loss='categorical_crossentropy',optimizer=opt,metrics=['accuracy'])\n\n\ntop_model.summary()\nresult = top_model.fit(X_train, y_train, validation_split=0.15, epochs=epochs, batch_size=batch_size)\n#top_model.save(\"saved_model.pb\")\ntop_model.save(\"saved_model\")\n\nx = range(epochs)\nplt.title('Model accuracy')\nplt.plot(x, result.history['accuracy'], label='accuracy')\nplt.plot(x, result.history['val_accuracy'], label='val_accuracy')\nplt.xlabel('Epoch')\nplt.legend(loc='center left', bbox_to_anchor=(1, 0.5), borderaxespad=0, ncol=2)\n\nname = 'resnet_tobacco_dataset_reslut.jpg'\nplt.savefig(name, bbox_inches='tight')\nplt.close()\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.title", "numpy.asarray", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "matplotlib.pyplot.close", "matplotlib.pyplot.xlabel", "numpy.array", "tensorflow.keras.optimizers.SGD" ] ]
iliya-s/pyscf
[ "81774efc036b721f7ab9963e21b1bd01e7472de0" ]
[ "pyscf/solvent/ddcosmo.py" ]
[ "#!/usr/bin/env python\n# Copyright 2014-2019 The PySCF Developers. 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# Author: Qiming Sun <[email protected]>\n#\n\n'''\ndomain decomposition COSMO\n\nSee also the code on github\n\nhttps://github.com/filippolipparini/ddPCM\n\nand the papers\n\n[1] Domain decomposition for implicit solvation models.\nE. Cances, Y. Maday, B. Stamm\nJ. Chem. Phys., 139, 054111 (2013)\nhttp://dx.doi.org/10.1063/1.4816767\n\n[2] Fast Domain Decomposition Algorithm for Continuum Solvation Models: Energy and First Derivatives.\nF. Lipparini, B. Stamm, E. Cances, Y. Maday, B. Mennucci\nJ. Chem. Theory Comput., 9, 3637-3648 (2013)\nhttp://dx.doi.org/10.1021/ct400280b\n\n[3] Quantum, classical, and hybrid QM/MM calculations in solution: General implementation of the ddCOSMO linear scaling strategy.\nF. Lipparini, G. Scalmani, L. Lagardere, B. Stamm, E. Cances, Y. Maday, J.-P.Piquemal, M. J. Frisch, B. Mennucci\nJ. Chem. Phys., 141, 184108 (2014)\nhttp://dx.doi.org/10.1063/1.4901304\n\n-- Dielectric constants (from https://gaussian.com/scrf/) --\nMore dataset can be found in Minnesota Solvent Descriptor Database\n(https://comp.chem.umn.edu/solvation)\nWater 78.3553\nAcetonitrile 35.688\nMethanol 32.613\nEthanol 24.852\nIsoQuinoline 11.00\nQuinoline 9.16\nChloroform 4.7113\nDiethylEther 4.2400\nDichloromethane 8.93\nDiChloroEthane 10.125\nCarbonTetraChloride 2.2280\nBenzene 2.2706\nToluene 2.3741\nChloroBenzene 5.6968\nNitroMethane 36.562\nHeptane 1.9113\nCycloHexane 2.0165\nAniline 6.8882\nAcetone 20.493\nTetraHydroFuran 7.4257\nDiMethylSulfoxide 46.826\nArgon 1.430\nKrypton 1.519\nXenon 1.706\nn-Octanol 9.8629\n1,1,1-TriChloroEthane 7.0826\n1,1,2-TriChloroEthane 7.1937\n1,2,4-TriMethylBenzene 2.3653\n1,2-DiBromoEthane 4.9313\n1,2-EthaneDiol 40.245\n1,4-Dioxane 2.2099\n1-Bromo-2-MethylPropane 7.7792\n1-BromoOctane 5.0244\n1-BromoPentane 6.269\n1-BromoPropane 8.0496\n1-Butanol 17.332\n1-ChloroHexane 5.9491\n1-ChloroPentane 6.5022\n1-ChloroPropane 8.3548\n1-Decanol 7.5305\n1-FluoroOctane 3.89\n1-Heptanol 11.321\n1-Hexanol 12.51\n1-Hexene 2.0717\n1-Hexyne 2.615\n1-IodoButane 6.173\n1-IodoHexaDecane 3.5338\n1-IodoPentane 5.6973\n1-IodoPropane 6.9626\n1-NitroPropane 23.73\n1-Nonanol 8.5991\n1-Pentanol 15.13\n1-Pentene 1.9905\n1-Propanol 20.524\n2,2,2-TriFluoroEthanol 26.726\n2,2,4-TriMethylPentane 1.9358\n2,4-DiMethylPentane 1.8939\n2,4-DiMethylPyridine 9.4176\n2,6-DiMethylPyridine 7.1735\n2-BromoPropane 9.3610\n2-Butanol 15.944\n2-ChloroButane 8.3930\n2-Heptanone 11.658\n2-Hexanone 14.136\n2-MethoxyEthanol 17.2\n2-Methyl-1-Propanol 16.777\n2-Methyl-2-Propanol 12.47\n2-MethylPentane 1.89\n2-MethylPyridine 9.9533\n2-NitroPropane 25.654\n2-Octanone 9.4678\n2-Pentanone 15.200\n2-Propanol 19.264\n2-Propen-1-ol 19.011\n3-MethylPyridine 11.645\n3-Pentanone 16.78\n4-Heptanone 12.257\n4-Methyl-2-Pentanone 12.887\n4-MethylPyridine 11.957\n5-Nonanone 10.6\nAceticAcid 6.2528\nAcetoPhenone 17.44\na-ChloroToluene 6.7175\nAnisole 4.2247\nBenzaldehyde 18.220\nBenzoNitrile 25.592\nBenzylAlcohol 12.457\nBromoBenzene 5.3954\nBromoEthane 9.01\nBromoform 4.2488\nButanal 13.45\nButanoicAcid 2.9931\nButanone 18.246\nButanoNitrile 24.291\nButylAmine 4.6178\nButylEthanoate 4.9941\nCarbonDiSulfide 2.6105\nCis-1,2-DiMethylCycloHexane 2.06\nCis-Decalin 2.2139\nCycloHexanone 15.619\nCycloPentane 1.9608\nCycloPentanol 16.989\nCycloPentanone 13.58\nDecalin-mixture 2.196\nDiBromomEthane 7.2273\nDiButylEther 3.0473\nDiEthylAmine 3.5766\nDiEthylSulfide 5.723\nDiIodoMethane 5.32\nDiIsoPropylEther 3.38\nDiMethylDiSulfide 9.6\nDiPhenylEther 3.73\nDiPropylAmine 2.9112\ne-1,2-DiChloroEthene 2.14\ne-2-Pentene 2.051\nEthaneThiol 6.667\nEthylBenzene 2.4339\nEthylEthanoate 5.9867\nEthylMethanoate 8.3310\nEthylPhenylEther 4.1797\nFluoroBenzene 5.42\nFormamide 108.94\nFormicAcid 51.1\nHexanoicAcid 2.6\nIodoBenzene 4.5470\nIodoEthane 7.6177\nIodoMethane 6.8650\nIsoPropylBenzene 2.3712\nm-Cresol 12.44\nMesitylene 2.2650\nMethylBenzoate 6.7367\nMethylButanoate 5.5607\nMethylCycloHexane 2.024\nMethylEthanoate 6.8615\nMethylMethanoate 8.8377\nMethylPropanoate 6.0777\nm-Xylene 2.3478\nn-ButylBenzene 2.36\nn-Decane 1.9846\nn-Dodecane 2.0060\nn-Hexadecane 2.0402\nn-Hexane 1.8819\nNitroBenzene 34.809\nNitroEthane 28.29\nn-MethylAniline 5.9600\nn-MethylFormamide-mixture 181.56\nn,n-DiMethylAcetamide 37.781\nn,n-DiMethylFormamide 37.219\nn-Nonane 1.9605\nn-Octane 1.9406\nn-Pentadecane 2.0333\nn-Pentane 1.8371\nn-Undecane 1.9910\no-ChloroToluene 4.6331\no-Cresol 6.76\no-DiChloroBenzene 9.9949\no-NitroToluene 25.669\no-Xylene 2.5454\nPentanal 10.0\nPentanoicAcid 2.6924\nPentylAmine 4.2010\nPentylEthanoate 4.7297\nPerFluoroBenzene 2.029\np-IsoPropylToluene 2.2322\nPropanal 18.5\nPropanoicAcid 3.44\nPropanoNitrile 29.324\nPropylAmine 4.9912\nPropylEthanoate 5.5205\np-Xylene 2.2705\nPyridine 12.978\nsec-ButylBenzene 2.3446\ntert-ButylBenzene 2.3447\nTetraChloroEthene 2.268\nTetraHydroThiophene-s,s-dioxide 43.962\nTetralin 2.771\nThiophene 2.7270\nThiophenol 4.2728\ntrans-Decalin 2.1781\nTriButylPhosphate 8.1781\nTriChloroEthene 3.422\nTriEthylAmine 2.3832\nXylene-mixture 2.3879\nz-1,2-DiChloroEthene 9.2\n'''\n\nimport ctypes\nimport copy\nimport numpy\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf import gto\nfrom pyscf import df\nfrom pyscf.dft import gen_grid, numint\nfrom pyscf.data import radii\nfrom pyscf.symm import sph\n\ndef ddcosmo_for_scf(mf, solvent_obj=None, dm=None):\n '''Patch ddCOSMO to SCF (HF and DFT) method.\n \n Kwargs:\n dm : if given, solvent does not response to the change of density\n matrix. A frozen ddCOSMO potential is added to the results.\n '''\n if getattr(mf, 'with_solvent', None):\n if solvent_obj is not None:\n mf.with_solvent = solvent_obj\n return mf\n\n oldMF = mf.__class__\n if solvent_obj is None:\n solvent_obj = DDCOSMO(mf.mol)\n\n if dm is not None:\n solvent_obj.epcm, solvent_obj.vpcm = solvent_obj.kernel(dm)\n solvent_obj.frozen = True\n\n class SCFWithSolvent(oldMF):\n def __init__(self, mf, solvent):\n self.__dict__.update(mf.__dict__)\n self.with_solvent = solvent\n self._keys.update(['with_solvent'])\n\n def dump_flags(self, verbose=None):\n oldMF.dump_flags(self)\n self.with_solvent.check_sanity()\n self.with_solvent.dump_flags()\n return self\n\n # Note vpcm should not be added to get_hcore for scf methods.\n # get_hcore is overloaded by many post-HF methods. Modifying\n # SCF.get_hcore may lead error.\n\n def get_veff(self, mol=None, dm=None, *args, **kwargs):\n vhf = oldMF.get_veff(self, mol, dm, *args, **kwargs)\n with_solvent = self.with_solvent\n if not with_solvent.frozen:\n with_solvent.epcm, with_solvent.vpcm = with_solvent.kernel(dm)\n epcm, vpcm = with_solvent.epcm, with_solvent.vpcm\n\n # NOTE: vpcm should not be added to vhf in this place. This is\n # because vhf is used as the reference for direct_scf in the next\n # iteration. If vpcm is added here, it may break direct SCF.\n return lib.tag_array(vhf, epcm=epcm, vpcm=vpcm)\n\n def get_fock(self, h1e=None, s1e=None, vhf=None, dm=None, cycle=-1,\n diis=None, diis_start_cycle=None,\n level_shift_factor=None, damp_factor=None):\n # DIIS was called inside oldMF.get_fock. vpcm, as a function of\n # dm, should be extrapolated as well. To enable it, vpcm has to be\n # added to the fock matrix before DIIS was called.\n if getattr(vhf, 'vpcm', None) is None:\n vhf = self.get_veff(self.mol, dm)\n return oldMF.get_fock(self, h1e, s1e, vhf+vhf.vpcm, dm, cycle, diis,\n diis_start_cycle, level_shift_factor, damp_factor)\n\n def energy_elec(self, dm=None, h1e=None, vhf=None):\n if dm is None:\n dm = self.make_rdm1()\n if getattr(vhf, 'epcm', None) is None:\n vhf = self.get_veff(self.mol, dm)\n e_tot, e_coul = oldMF.energy_elec(self, dm, h1e, vhf)\n e_tot += vhf.epcm\n logger.debug(self, ' E_diel = %.15g', vhf.epcm)\n return e_tot, e_coul\n\n def nuc_grad_method(self):\n from pyscf.solvent import ddcosmo_grad\n grad_method = oldMF.nuc_grad_method(self)\n return ddcosmo_grad.ddcosmo_grad(grad_method, self.with_solvent)\n\n mf1 = SCFWithSolvent(mf, solvent_obj)\n return mf1\n\ndef ddcosmo_for_casscf(mc, solvent_obj=None, dm=None):\n '''Patch ddCOSMO to CASSCF method.\n \n Kwargs:\n dm : if given, solvent does not response to the change of density\n matrix. A frozen ddCOSMO potential is added to the results.\n '''\n if getattr(mc, 'with_solvent', None):\n if solvent_obj is not None:\n mc.with_solvent = solvent_obj\n return mc\n\n oldCAS = mc.__class__\n if solvent_obj is None:\n if getattr(mc._scf, 'with_solvent', None):\n solvent_obj = mc._scf.with_solvent\n else:\n solvent_obj = DDCOSMO(mc.mol)\n\n if dm is not None:\n solvent_obj.epcm, solvent_obj.vpcm = solvent_obj.kernel(dm)\n solvent_obj.frozen = True\n\n class CASSCFWithSolvent(oldCAS):\n def __init__(self, mc, solvent):\n self.__dict__.update(mc.__dict__)\n self.with_solvent = solvent\n self._e_tot_without_solvent = 0\n self._keys.update(['with_solvent'])\n\n def dump_flags(self, verbose=None):\n oldCAS.dump_flags(self)\n self.with_solvent.check_sanity()\n self.with_solvent.dump_flags()\n if self.conv_tol < 1e-7:\n logger.warn(self, 'CASSCF+ddCOSMO may not be able to '\n 'converge to conv_tol=%g', self.conv_tol)\n return self\n\n def update_casdm(self, mo, u, fcivec, e_ci, eris, envs={}):\n casdm1, casdm2, gci, fcivec = \\\n oldCAS.update_casdm(self, mo, u, fcivec, e_ci, eris, envs)\n\n# The potential is generated based on the density of current micro iteration.\n# It will be added to hcore in casci function. Strictly speaking, this density\n# is not the same to the CASSCF density (which was used to measure\n# convergence) in the macro iterations. When CASSCF is converged, it\n# should be almost the same to the CASSCF density of the macro iterations.\n with_solvent = self.with_solvent\n if not with_solvent.frozen:\n # Code to mimic dm = self.make_rdm1(ci=fcivec)\n mocore = mo[:,:self.ncore]\n mocas = mo[:,self.ncore:self.ncore+self.ncas]\n dm = reduce(numpy.dot, (mocas, casdm1, mocas.T))\n dm += numpy.dot(mocore, mocore.T) * 2\n with_solvent.epcm, with_solvent.vpcm = with_solvent.kernel(dm)\n\n return casdm1, casdm2, gci, fcivec\n\n# ddCOSMO Potential should be added to the effective potential. However, there\n# is no hook to modify the effective potential in CASSCF. The workaround\n# here is to modify hcore. It can affect the 1-electron operator in many CASSCF\n# functions: gen_h_op, update_casdm, casci. Note hcore is used to compute the\n# energy for core density (Ecore). The resultant total energy from casci\n# function will include the contribution from ddCOSMO potential. The\n# duplicated energy contribution from solvent needs to be removed.\n def get_hcore(self, mol=None):\n hcore = self._scf.get_hcore(mol)\n if self.with_solvent.vpcm is not None:\n hcore += self.with_solvent.vpcm\n return hcore\n\n def casci(self, mo_coeff, ci0=None, eris=None, verbose=None, envs=None):\n log = logger.new_logger(self, verbose)\n log.debug('Running CASCI with solvent. Note the total energy '\n 'has duplicated contributions from solvent.')\n\n # In oldCAS.casci function, dE was computed based on the total\n # energy without removing the duplicated solvent contributions.\n # However, envs['elast'] is the last total energy with correct\n # solvent effects. Hack envs['elast'] to make oldCAS.casci print\n # the correct energy difference.\n envs['elast'] = self._e_tot_without_solvent\n e_tot, e_cas, fcivec = oldCAS.casci(self, mo_coeff, ci0, eris,\n verbose, envs)\n self._e_tot_without_solvent = e_tot\n\n log.debug('Computing corrections to the total energy.')\n dm = self.make_rdm1(ci=fcivec, ao_repr=True)\n\n with_solvent = self.with_solvent\n if with_solvent.epcm is not None:\n edup = numpy.einsum('ij,ji->', with_solvent.vpcm, dm)\n ediel = with_solvent.epcm\n e_tot = e_tot - edup + ediel\n log.info('Removing duplication %.15g, '\n 'adding E_diel = %.15g to total energy:\\n'\n ' E(CASSCF+solvent) = %.15g', edup, ediel, e_tot)\n\n # Update solvent effects for next iteration if needed\n if not with_solvent.frozen:\n with_solvent.epcm, with_solvent.vpcm = with_solvent.kernel(dm)\n\n return e_tot, e_cas, fcivec\n\n def nuc_grad_method(self):\n from pyscf.solvent import ddcosmo_grad\n grad_method = oldCAS.nuc_grad_method(self)\n return ddcosmo_grad.ddcosmo_grad(grad_method, self.with_solvent)\n\n return CASSCFWithSolvent(mc, solvent_obj)\n\n\ndef ddcosmo_for_casci(mc, solvent_obj=None, dm=None):\n '''Patch ddCOSMO to CASCI method.\n \n Kwargs:\n dm : if given, solvent does not response to the change of density\n matrix. A frozen ddCOSMO potential is added to the results.\n '''\n if getattr(mc, 'with_solvent', None):\n if solvent_obj is not None:\n mc.with_solvent = solvent_obj\n return mc\n\n oldCAS = mc.__class__\n if solvent_obj is None:\n if getattr(mc._scf, 'with_solvent', None):\n solvent_obj = mc._scf.with_solvent\n else:\n solvent_obj = DDCOSMO(mc.mol)\n\n if dm is not None:\n solvent_obj.epcm, solvent_obj.vpcm = solvent_obj.kernel(dm)\n solvent_obj.frozen = True\n\n class CASCIWithSolvent(oldCAS):\n def __init__(self, mc, solvent):\n self.__dict__.update(mc.__dict__)\n self.with_solvent = solvent\n self._keys.update(['with_solvent'])\n\n def dump_flags(self, verbose=None):\n oldCAS.dump_flags(self, verbose)\n self.with_solvent.check_sanity()\n self.with_solvent.dump_flags()\n return self\n\n def get_hcore(self, mol=None):\n hcore = self._scf.get_hcore(mol)\n if self.with_solvent.vpcm is not None:\n # NOTE: get_hcore was called by CASCI to generate core\n # potential. vpcm is added in this place to take accounts the\n # effects of solvent. Its contribution is duplicated and it\n # should be removed from the total energy.\n hcore += self.with_solvent.vpcm\n return hcore\n\n def kernel(self, mo_coeff=None, ci0=None, verbose=None):\n with_solvent = self.with_solvent\n\n log = logger.new_logger(self)\n log.info('\\n** Self-consistently update the solvent effects for %s **',\n oldCAS)\n log1 = copy.copy(log)\n log1.verbose -= 1 # Suppress a few output messages\n\n def casci_iter_(ci0, log):\n # self.e_tot, self.e_cas, and self.ci are updated in the call\n # to oldCAS.kernel\n e_tot, e_cas, ci0 = oldCAS.kernel(self, mo_coeff, ci0, log)[:3]\n\n if isinstance(self.e_cas, (float, numpy.number)):\n dm = self.make_rdm1(ci=ci0)\n else:\n log.debug('Computing solvent responses to DM of state %d',\n with_solvent.state_id)\n dm = self.make_rdm1(ci=ci0[with_solvent.state_id])\n\n if with_solvent.epcm is not None:\n edup = numpy.einsum('ij,ji->', with_solvent.vpcm, dm)\n self.e_tot += with_solvent.epcm - edup\n\n if not with_solvent.frozen:\n with_solvent.epcm, with_solvent.vpcm = with_solvent.kernel(dm)\n log.debug(' E_diel = %.15g', with_solvent.epcm)\n return self.e_tot, e_cas, ci0\n\n if with_solvent.frozen:\n with lib.temporary_env(self, _finalize=lambda:None):\n casci_iter_(ci0, log)\n log.note('Total energy with solvent effects')\n self._finalize()\n return self.e_tot, self.e_cas, self.ci, self.mo_coeff, self.mo_energy\n\n self.converged = False\n with lib.temporary_env(self, canonicalization=False):\n e_tot = e_last = 0\n for cycle in range(self.with_solvent.max_cycle):\n log.info('\\n** Solvent self-consistent cycle %d:', cycle)\n e_tot, e_cas, ci0 = casci_iter_(ci0, log1)\n\n de = e_tot - e_last\n if isinstance(e_cas, (float, numpy.number)):\n log.info('Sovlent cycle %d E(CASCI+solvent) = %.15g '\n 'dE = %g', cycle, e_tot, de)\n else:\n for i, e in enumerate(e_tot):\n log.info('Solvent cycle %d CASCI root %d '\n 'E(CASCI+solvent) = %.15g dE = %g',\n cycle, i, e, de[i])\n\n if abs(e_tot-e_last).max() < with_solvent.conv_tol:\n self.converged = True\n break\n e_last = e_tot\n\n # An extra cycle to canonicalize CASCI orbitals\n with lib.temporary_env(self, _finalize=lambda:None):\n casci_iter_(ci0, log)\n if self.converged:\n log.info('self-consistent CASCI+solvent converged')\n else:\n log.info('self-consistent CASCI+solvent not converged')\n log.note('Total energy with solvent effects')\n self._finalize()\n return self.e_tot, self.e_cas, self.ci, self.mo_coeff, self.mo_energy\n\n def nuc_grad_method(self):\n from pyscf.solvent import ddcosmo_grad\n grad_method = oldCAS.nuc_grad_method(self)\n return ddcosmo_grad.ddcosmo_grad(grad_method, self.with_solvent)\n\n return CASCIWithSolvent(mc, solvent_obj)\n\n\ndef ddcosmo_for_post_scf(method, solvent_obj=None, dm=None):\n '''Default wrapper to patch ddCOSMO to post-SCF methods (CC, CI, MP,\n TDDFT etc.)\n\n NOTE: this implementation often causes (macro iteration) convergence issue\n \n Kwargs:\n dm : if given, solvent does not response to the change of density\n matrix. A frozen ddCOSMO potential is added to the results.\n '''\n if getattr(method, 'with_solvent', None):\n if solvent_obj is not None:\n method.with_solvent = solvent_obj\n method._scf.with_solvent = solvent_obj\n return method\n\n old_method = method.__class__\n\n if getattr(method._scf, 'with_solvent', None):\n scf_with_solvent = method._scf\n if solvent_obj is not None:\n scf_with_solvent.with_solvent = solvent_obj\n else:\n scf_with_solvent = ddcosmo_for_scf(method._scf, solvent_obj, dm)\n if dm is None:\n solvent_obj = scf_with_solvent.with_solvent\n solvent_obj.epcm, solvent_obj.vpcm = \\\n solvent_obj.kernel(scf_with_solvent.make_rdm1())\n\n # Post-HF objects access the solvent effects indirectly through the\n # underlying ._scf object.\n basic_scanner = method.as_scanner()\n basic_scanner._scf = scf_with_solvent.as_scanner()\n\n if dm is not None:\n solvent_obj = scf_with_solvent.with_solvent\n solvent_obj.epcm, solvent_obj.vpcm = solvent_obj.kernel(dm)\n solvent_obj.frozen = True\n\n class PostSCFWithSolvent(old_method):\n def __init__(self, method):\n self.__dict__.update(method.__dict__)\n self._scf = scf_with_solvent\n\n @property\n def with_solvent(self):\n return self._scf.with_solvent\n\n def dump_flags(self, verbose=None):\n old_method.dump_flags(self)\n self.with_solvent.check_sanity()\n self.with_solvent.dump_flags()\n return self\n\n def kernel(self, *args, **kwargs):\n with_solvent = self.with_solvent\n # The underlying ._scf object is decorated with solvent effects.\n # The resultant Fock matrix and orbital energies both include the\n # effects from solvent. It means that solvent effects for post-HF\n # methods are automatically counted if solvent is enabled at scf\n # level.\n if with_solvent.frozen:\n return old_method.kernel(self, *args, **kwargs)\n\n log = logger.new_logger(self)\n log.info('\\n** Self-consistently update the solvent effects for %s **',\n old_method)\n ##TODO: Suppress a few output messages\n #log1 = copy.copy(log)\n #log1.note, log1.info = log1.info, log1.debug\n\n e_last = 0\n #diis = lib.diis.DIIS()\n for cycle in range(self.with_solvent.max_cycle):\n log.info('\\n** Solvent self-consistent cycle %d:', cycle)\n # Solvent effects are applied when accessing the\n # underlying ._scf objects. The flag frozen=True ensures that\n # the generated potential with_solvent.vpcm is passed to the\n # the post-HF object, without being updated in the implicit\n # call to the _scf iterations.\n with lib.temporary_env(with_solvent, frozen=True):\n e_tot = basic_scanner(self.mol)\n dm = basic_scanner.make_rdm1(ao_repr=True)\n #dm = diis.update(dm)\n\n # To generate the solvent potential for ._scf object. Since\n # frozen is set when calling basic_scanner, the solvent\n # effects are frozen during the scf iterations.\n with_solvent.epcm, with_solvent.vpcm = with_solvent.kernel(dm)\n\n de = e_tot - e_last\n log.info('Sovlent cycle %d E_tot = %.15g dE = %g',\n cycle, e_tot, de)\n\n if abs(e_tot-e_last).max() < with_solvent.conv_tol:\n break\n e_last = e_tot\n\n # An extra cycle to compute the total energy\n log.info('\\n** Extra cycle for solvent effects')\n with lib.temporary_env(with_solvent, frozen=True):\n #Update everything except the _scf object and _keys\n basic_scanner(self.mol)\n self.__dict__.update(basic_scanner.__dict__)\n self._scf.__dict__.update(basic_scanner._scf.__dict__)\n self._finalize()\n return self.e_corr, None\n\n def nuc_grad_method(self):\n from pyscf.solvent import ddcosmo_grad\n grad_method = old_method.nuc_grad_method(self)\n return ddcosmo_grad.ddcosmo_grad(grad_method, self.with_solvent)\n\n return PostSCFWithSolvent(method)\n\n\n# Inject DDCOSMO to other methods\nfrom pyscf import scf\nfrom pyscf import mcscf\nfrom pyscf import mp, ci, cc\nscf.hf.SCF.DDCOSMO = ddcosmo_for_scf\nmcscf.casci.DDCOSMO = ddcosmo_for_casci\nmcscf.mc1step.DDCOSMO = ddcosmo_for_casscf\nmp.mp2.MP2.DDCOSMO = ddcosmo_for_post_scf\nci.cisd.CISD.DDCOSMO = ddcosmo_for_post_scf\ncc.ccsd.CCSD.DDCOSMO = ddcosmo_for_post_scf\n\n\n# TODO: Testing the value of psi (make_psi_vmat). All intermediates except\n# psi are tested against ddPCM implementation on github. Psi needs to be\n# computed by the host program. It requires the numerical integration code. \ndef gen_ddcosmo_solver(pcmobj, verbose=None):\n '''Generate ddcosmo function to compute energy and potential matrix\n '''\n mol = pcmobj.mol\n if pcmobj.grids.coords is None:\n pcmobj.grids.build(with_non0tab=True)\n\n natm = mol.natm\n lmax = pcmobj.lmax\n\n r_vdw = pcmobj.get_atomic_radii()\n coords_1sph, weights_1sph = make_grids_one_sphere(pcmobj.lebedev_order)\n ylm_1sph = numpy.vstack(sph.real_sph_vec(coords_1sph, lmax, True))\n\n fi = make_fi(pcmobj, r_vdw)\n ui = 1 - fi\n ui[ui<0] = 0\n nexposed = numpy.count_nonzero(ui==1)\n nbury = numpy.count_nonzero(ui==0)\n on_shell = numpy.count_nonzero(ui>0) - nexposed\n logger.debug(pcmobj, 'Num points exposed %d', nexposed)\n logger.debug(pcmobj, 'Num points buried %d', nbury)\n logger.debug(pcmobj, 'Num points on shell %d', on_shell)\n\n nlm = (lmax+1)**2\n Lmat = make_L(pcmobj, r_vdw, ylm_1sph, fi)\n Lmat = Lmat.reshape(natm*nlm,-1)\n\n cached_pol = cache_fake_multipoles(pcmobj.grids, r_vdw, lmax)\n\n def gen_vind(dm):\n pcmobj._dm = dm\n if not (isinstance(dm, numpy.ndarray) and dm.ndim == 2):\n # spin-traced DM for UHF or ROHF\n dm = dm[0] + dm[1]\n\n phi = make_phi(pcmobj, dm, r_vdw, ui)\n L_X = numpy.linalg.solve(Lmat, phi.ravel()).reshape(natm,-1)\n psi, vmat = make_psi_vmat(pcmobj, dm, r_vdw, ui, pcmobj.grids, ylm_1sph,\n cached_pol, L_X, Lmat)[:2]\n dielectric = pcmobj.eps\n if dielectric > 0:\n f_epsilon = (dielectric-1.)/dielectric\n else:\n f_epsilon = 1\n pcmobj.epcm = .5 * f_epsilon * numpy.einsum('jx,jx', psi, L_X)\n pcmobj.vpcm = .5 * f_epsilon * vmat\n return pcmobj.epcm, pcmobj.vpcm\n return gen_vind\n\ndef energy(pcmobj, dm):\n '''\n ddCOSMO energy\n Es = 1/2 f(eps) \\int rho(r) W(r) dr\n '''\n epcm = gen_ddcosmo_solver(pcmobj, pcmobj.verbose)(dm)[0]\n return epcm\n\ndef get_atomic_radii(pcmobj):\n mol = pcmobj.mol\n vdw_radii = pcmobj.radii_table\n atom_radii = pcmobj.atom_radii\n\n atom_symb = [mol.atom_symbol(i) for i in range(mol.natm)]\n r_vdw = [vdw_radii[gto.charge(x)] for x in atom_symb]\n if atom_radii is not None:\n for i in range(mol.natm):\n if atom_symb[i] in atom_radii:\n r_vdw[i] = atom_radii[atom_symb[i]]\n return numpy.asarray(r_vdw)\n\n\ndef regularize_xt(t, eta):\n xt = numpy.zeros_like(t)\n inner = t <= 1-eta\n on_shell = (1-eta < t) & (t < 1)\n xt[inner] = 1\n ti = t[on_shell]\n# JCTC, 9, 3637\n xt[on_shell] = 1./eta**5 * (1-ti)**3 * (6*ti**2 + (15*eta-12)*ti\n + 10*eta**2 - 15*eta + 6)\n# JCP, 139, 054111\n# xt[on_shell] = 1./eta**4 * (1-ti)**2 * (ti-1+2*eta)**2\n return xt\n\ndef make_grids_one_sphere(lebedev_order):\n ngrid_1sph = gen_grid.LEBEDEV_ORDER[lebedev_order]\n leb_grid = numpy.empty((ngrid_1sph,4))\n gen_grid.libdft.MakeAngularGrid(leb_grid.ctypes.data_as(ctypes.c_void_p),\n ctypes.c_int(ngrid_1sph))\n coords_1sph = leb_grid[:,:3]\n # Note the Lebedev angular grids are normalized to 1 in pyscf\n weights_1sph = 4*numpy.pi * leb_grid[:,3]\n return coords_1sph, weights_1sph\n\ndef make_L(pcmobj, r_vdw, ylm_1sph, fi):\n # See JCTC, 9, 3637, Eq (18)\n mol = pcmobj.mol\n natm = mol.natm\n lmax = pcmobj.lmax\n eta = pcmobj.eta\n nlm = (lmax+1)**2\n\n coords_1sph, weights_1sph = make_grids_one_sphere(pcmobj.lebedev_order)\n ngrid_1sph = weights_1sph.size\n atom_coords = mol.atom_coords()\n ylm_1sph = ylm_1sph.reshape(nlm,ngrid_1sph)\n\n# JCP, 141, 184108 Eq (9), (12) is incorrect\n# L_diag = <lm|(1/|s-s'|)|l'm'>\n# Using Laplace expansion for electrostatic potential 1/r\n# L_diag = 4pi/(2l+1)/|s| <lm|l'm'>\n L_diag = numpy.zeros((natm,nlm))\n p1 = 0\n for l in range(lmax+1):\n p0, p1 = p1, p1 + (l*2+1)\n L_diag[:,p0:p1] = 4*numpy.pi/(l*2+1)\n L_diag *= 1./r_vdw.reshape(-1,1)\n Lmat = numpy.diag(L_diag.ravel()).reshape(natm,nlm,natm,nlm)\n\n for ja in range(natm):\n # scale the weight, precontract d_nj and w_n\n # see JCTC 9, 3637, Eq (16) - (18)\n # Note all values are scaled by 1/r_vdw to make the formulas\n # consistent to Psi in JCP, 141, 184108\n part_weights = weights_1sph.copy()\n part_weights[fi[ja]>1] /= fi[ja,fi[ja]>1]\n for ka in atoms_with_vdw_overlap(ja, atom_coords, r_vdw):\n vjk = r_vdw[ja] * coords_1sph + atom_coords[ja] - atom_coords[ka]\n tjk = lib.norm(vjk, axis=1) / r_vdw[ka]\n wjk = pcmobj.regularize_xt(tjk, eta, r_vdw[ka])\n wjk *= part_weights\n pol = sph.multipoles(vjk, lmax)\n p1 = 0\n for l in range(lmax+1):\n fac = 4*numpy.pi/(l*2+1) / r_vdw[ka]**(l+1)\n p0, p1 = p1, p1 + (l*2+1)\n a = numpy.einsum('xn,n,mn->xm', ylm_1sph, wjk, pol[l])\n Lmat[ja,:,ka,p0:p1] += -fac * a\n return Lmat\n\ndef make_fi(pcmobj, r_vdw):\n coords_1sph, weights_1sph = make_grids_one_sphere(pcmobj.lebedev_order)\n mol = pcmobj.mol\n eta = pcmobj.eta\n natm = mol.natm\n atom_coords = mol.atom_coords()\n ngrid_1sph = coords_1sph.shape[0]\n fi = numpy.zeros((natm,ngrid_1sph))\n for ia in range(natm):\n for ja in atoms_with_vdw_overlap(ia, atom_coords, r_vdw):\n v = r_vdw[ia]*coords_1sph + atom_coords[ia] - atom_coords[ja]\n rv = lib.norm(v, axis=1)\n t = rv / r_vdw[ja]\n xt = pcmobj.regularize_xt(t, eta, r_vdw[ja])\n fi[ia] += xt\n fi[fi < 1e-20] = 0\n return fi\n\ndef make_phi(pcmobj, dm, r_vdw, ui):\n mol = pcmobj.mol\n natm = mol.natm\n coords_1sph, weights_1sph = make_grids_one_sphere(pcmobj.lebedev_order)\n ngrid_1sph = coords_1sph.shape[0]\n\n if not (isinstance(dm, numpy.ndarray) and dm.ndim == 2):\n dm = dm[0] + dm[1]\n tril_dm = lib.pack_tril(dm+dm.T)\n nao = dm.shape[0]\n diagidx = numpy.arange(nao)\n diagidx = diagidx*(diagidx+1)//2 + diagidx\n tril_dm[diagidx] *= .5\n\n atom_coords = mol.atom_coords()\n atom_charges = mol.atom_charges()\n\n extern_point_idx = ui > 0\n cav_coords = (atom_coords.reshape(natm,1,3)\n + numpy.einsum('r,gx->rgx', r_vdw, coords_1sph))\n\n v_phi = numpy.empty((natm,ngrid_1sph))\n for ia in range(natm):\n# Note (-) sign is not applied to atom_charges, because (-) is explicitly\n# included in rhs and L matrix\n d_rs = atom_coords.reshape(-1,1,3) - cav_coords[ia]\n v_phi[ia] = numpy.einsum('z,zp->p', atom_charges, 1./lib.norm(d_rs,axis=2))\n\n max_memory = pcmobj.max_memory - lib.current_memory()[0]\n blksize = int(max(max_memory*1e6/8/nao**2, 400))\n\n cav_coords = cav_coords[extern_point_idx]\n v_phi_e = numpy.empty(cav_coords.shape[0])\n int3c2e = mol._add_suffix('int3c2e')\n cintopt = gto.moleintor.make_cintopt(mol._atm, mol._bas,\n mol._env, int3c2e)\n for i0, i1 in lib.prange(0, cav_coords.shape[0], blksize):\n fakemol = gto.fakemol_for_charges(cav_coords[i0:i1])\n v_nj = df.incore.aux_e2(mol, fakemol, intor=int3c2e, aosym='s2ij',\n cintopt=cintopt)\n v_phi_e[i0:i1] = numpy.einsum('x,xk->k', tril_dm, v_nj)\n v_phi[extern_point_idx] -= v_phi_e\n\n ylm_1sph = numpy.vstack(sph.real_sph_vec(coords_1sph, pcmobj.lmax, True))\n phi = -numpy.einsum('n,xn,jn,jn->jx', weights_1sph, ylm_1sph, ui, v_phi)\n return phi\n\ndef make_psi_vmat(pcmobj, dm, r_vdw, ui, grids, ylm_1sph, cached_pol, L_X, L):\n mol = pcmobj.mol\n natm = mol.natm\n lmax = pcmobj.lmax\n nlm = (lmax+1)**2\n\n i1 = 0\n scaled_weights = numpy.empty(grids.weights.size)\n for ia in range(natm):\n fak_pol, leak_idx = cached_pol[mol.atom_symbol(ia)]\n i0, i1 = i1, i1 + fak_pol[0].shape[1]\n eta_nj = 0\n p1 = 0\n for l in range(lmax+1):\n fac = 4*numpy.pi/(l*2+1)\n p0, p1 = p1, p1 + (l*2+1)\n eta_nj += fac * numpy.einsum('mn,m->n', fak_pol[l], L_X[ia,p0:p1])\n scaled_weights[i0:i1] = eta_nj * grids.weights[i0:i1]\n\n if not (isinstance(dm, numpy.ndarray) and dm.ndim == 2):\n dm = dm[0] + dm[1]\n ni = numint.NumInt()\n max_memory = pcmobj.max_memory - lib.current_memory()[0]\n make_rho, nset, nao = ni._gen_rho_evaluator(mol, dm)\n shls_slice = (0, mol.nbas)\n ao_loc = mol.ao_loc_nr()\n den = numpy.empty(grids.weights.size)\n vmat = numpy.zeros((nao,nao))\n p1 = 0\n aow = None\n for ao, mask, weight, coords \\\n in ni.block_loop(mol, grids, nao, 0, max_memory):\n p0, p1 = p1, p1 + weight.size\n den[p0:p1] = weight * make_rho(0, ao, mask, 'LDA')\n aow = numpy.ndarray(ao.shape, order='F', buffer=aow)\n aow = numpy.einsum('pi,p->pi', ao, scaled_weights[p0:p1], out=aow)\n vmat -= numint._dot_ao_ao(mol, ao, aow, mask, shls_slice, ao_loc)\n ao = aow = scaled_weights = None\n\n nelec_leak = 0\n psi = numpy.empty((natm,nlm))\n i1 = 0\n for ia in range(natm):\n fak_pol, leak_idx = cached_pol[mol.atom_symbol(ia)]\n i0, i1 = i1, i1 + fak_pol[0].shape[1]\n nelec_leak += den[i0:i1][leak_idx].sum()\n p1 = 0\n for l in range(lmax+1):\n fac = 4*numpy.pi/(l*2+1)\n p0, p1 = p1, p1 + (l*2+1)\n psi[ia,p0:p1] = -fac * numpy.einsum('n,mn->m', den[i0:i1], fak_pol[l])\n# Contribution of nuclear charge to the total density\n# The factor numpy.sqrt(4*numpy.pi) is due to the product of 4*pi * Y_0^0\n psi[ia,0] += numpy.sqrt(4*numpy.pi)/r_vdw[ia] * mol.atom_charge(ia)\n logger.debug(pcmobj, 'electron leak %f', nelec_leak)\n\n # <Psi, L^{-1}g> -> Psi = SL the adjoint equation to LX = g\n L_S = numpy.linalg.solve(L.T.reshape(natm*nlm,-1), psi.ravel()).reshape(natm,-1)\n coords_1sph, weights_1sph = make_grids_one_sphere(pcmobj.lebedev_order)\n # JCP, 141, 184108, Eq (39)\n xi_jn = numpy.einsum('n,jn,xn,jx->jn', weights_1sph, ui, ylm_1sph, L_S)\n extern_point_idx = ui > 0\n cav_coords = (mol.atom_coords().reshape(natm,1,3)\n + numpy.einsum('r,gx->rgx', r_vdw, coords_1sph))\n cav_coords = cav_coords[extern_point_idx]\n xi_jn = xi_jn[extern_point_idx]\n\n max_memory = pcmobj.max_memory - lib.current_memory()[0]\n blksize = int(max(max_memory*1e6/8/nao**2, 400))\n\n cintopt = gto.moleintor.make_cintopt(mol._atm, mol._bas,\n mol._env, 'int3c2e')\n vmat_tril = 0\n for i0, i1 in lib.prange(0, xi_jn.size, blksize):\n fakemol = gto.fakemol_for_charges(cav_coords[i0:i1])\n v_nj = df.incore.aux_e2(mol, fakemol, intor='int3c2e', aosym='s2ij',\n cintopt=cintopt)\n vmat_tril += numpy.einsum('xn,n->x', v_nj, xi_jn[i0:i1])\n vmat += lib.unpack_tril(vmat_tril)\n return psi, vmat, L_S\n\ndef cache_fake_multipoles(grids, r_vdw, lmax):\n# For each type of atoms, cache the product of last two terms in\n# JCP, 141, 184108, Eq (31):\n# x_{<}^{l} / x_{>}^{l+1} Y_l^m\n mol = grids.mol\n atom_grids_tab = grids.gen_atomic_grids(mol)\n r_vdw_type = {}\n for ia in range(mol.natm):\n symb = mol.atom_symbol(ia)\n if symb not in r_vdw_type:\n r_vdw_type[symb] = r_vdw[ia]\n\n cached_pol = {}\n for symb in atom_grids_tab:\n x_nj, w = atom_grids_tab[symb]\n r = lib.norm(x_nj, axis=1)\n # Different equations are used in JCTC, 9, 3637. r*Ys (the fake_pole)\n # is computed as r^l/r_vdw. \"leak_idx\" is not needed.\n # Here, the implementation is based on JCP, 141, 184108\n leak_idx = r > r_vdw_type[symb]\n\n pol = sph.multipoles(x_nj, lmax)\n fak_pol = []\n for l in range(lmax+1):\n # x_{<}^{l} / x_{>}^{l+1} Y_l^m in JCP, 141, 184108, Eq (31)\n #:Ys = sph.real_sph_vec(x_nj/r.reshape(-1,1), lmax, True)\n #:rr = numpy.zeros_like(r)\n #:rr[r<=r_vdw[ia]] = r[r<=r_vdw[ia]]**l / r_vdw[ia]**(l+1)\n #:rr[r> r_vdw[ia]] = r_vdw[ia]**l / r[r>r_vdw[ia]]**(l+1)\n #:xx_ylm = numpy.einsum('n,mn->mn', rr, Ys[l])\n xx_ylm = pol[l] * (1./r_vdw_type[symb]**(l+1))\n # The line below is not needed for JCTC, 9, 3637\n xx_ylm[:,leak_idx] *= (r_vdw_type[symb]/r[leak_idx])**(2*l+1)\n fak_pol.append(xx_ylm)\n cached_pol[symb] = (fak_pol, leak_idx)\n return cached_pol\n\ndef atoms_with_vdw_overlap(atm_id, atom_coords, r_vdw):\n atm_dist = atom_coords - atom_coords[atm_id]\n atm_dist = numpy.einsum('pi,pi->p', atm_dist, atm_dist)\n atm_dist[atm_id] = 1e200\n vdw_sum = r_vdw + r_vdw[atm_id]\n atoms_nearby = numpy.where(atm_dist < vdw_sum**2)[0]\n return atoms_nearby\n\nclass DDCOSMO(lib.StreamObject):\n def __init__(self, mol):\n self.mol = mol\n self.stdout = mol.stdout\n self.verbose = mol.verbose\n self.max_memory = mol.max_memory\n\n #self.radii_table = radii.VDW\n self.radii_table = radii.UFF*1.1\n #self.radii_table = radii.MM3\n self.atom_radii = None\n self.lebedev_order = 17\n self.lmax = 6 # max angular momentum of spherical harmonics basis\n self.eta = .1 # regularization parameter\n self.eps = 78.3553\n self.grids = gen_grid.Grids(mol)\n\n # The maximum iterations and convergence tolerance to update solvent\n # effects in CASCI, CC, MP, CI, ... methods \n self.max_cycle = 20\n self.conv_tol = 1e-7\n self.state_id = 0\n\n # Set frozen to enable/disable the frozen ddCOSMO solvent potential.\n # If frozen is set, _dm (density matrix) needs to be specified to\n # generate the potential.\n self.frozen = False\n\n##################################################\n# don't modify the following attributes, they are not input options\n # epcm (the dielectric correction) and vpcm (the additional\n # potential) are updated during the SCF iterations\n self.epcm = None\n self.vpcm = None\n self._dm = None\n\n # _solver_ is a cached function returned by self.as_solver() to reduce\n # the overhead of initialization. It should be cleared whenever the\n # solvent parameters or the integration grids were changed.\n self._solver_ = None\n\n self._keys = set(self.__dict__.keys())\n\n @property\n def dm(self):\n '''Density matrix to generate the frozen ddCOSMO solvent potential.'''\n return self._dm\n @dm.setter\n def dm(self, dm):\n '''Set dm to enable/disable the frozen ddCOSMO solvent potential.\n Setting dm to None will disable the frozen potental, i.e. the\n potential will be response to the change of the density during SCF\n iterations.\n '''\n if isinstance(dm, numpy.ndarray):\n self._dm = dm\n self.epcm, self.vpcm = self.kernel(dm)\n else:\n self.epcm = self.vpcm = self._dm = None\n\n def __setattr__(self, key, val):\n if key in ('radii_table', 'atom_radii', 'lebedev_order', 'lmax',\n 'eta', 'eps', 'grids'):\n self._solver_ = None\n super(DDCOSMO, self).__setattr__(key, val)\n\n def dump_flags(self):\n logger.info(self, '******** %s ********', self.__class__)\n logger.info(self, 'lebedev_order = %s (%d grids per sphere)',\n self.lebedev_order, gen_grid.LEBEDEV_ORDER[self.lebedev_order])\n logger.info(self, 'lmax = %s' , self.lmax)\n logger.info(self, 'eta = %s' , self.eta)\n logger.info(self, 'eps = %s' , self.eps)\n logger.debug2(self, 'radii_table %s', self.radii_table)\n if self.atom_radii:\n logger.info(self, 'User specified atomic radii %s', str(self.atom_radii))\n self.grids.dump_flags()\n return self\n\n def kernel(self, dm):\n '''A single shot solvent effects for given density matrix.\n '''\n if (self._solver_ is None or\n# If self.grids.coords is None, it is very likely caused by the updates of the\n# \"grids\" parameters. The COSMO solver should be updated to adapt the new\n# integral grids.\n self.grids.coords is None):\n self._solver_ = self.as_solver()\n\n epcm, vpcm = self._solver_(dm)\n return epcm, vpcm\n\n energy = energy\n gen_solver = as_solver = gen_ddcosmo_solver\n get_atomic_radii = get_atomic_radii\n\n def regularize_xt(self, t, eta, scale=1):\n # scale = eta*scale, is it correct?\n return regularize_xt(t, eta*scale)\n\n\nif __name__ == '__main__':\n from pyscf import scf\n from pyscf import mcscf\n from pyscf import cc\n mol = gto.M(atom='H 0 0 0; H 0 1 1.2; H 1. .1 0; H .5 .5 1')\n natm = mol.natm\n r_vdw = [radii.VDW[gto.charge(mol.atom_symbol(i))]\n for i in range(natm)]\n r_vdw = numpy.asarray(r_vdw)\n pcmobj = DDCOSMO(mol)\n pcmobj.regularize_xt = lambda t, eta, scale: regularize_xt(t, eta)\n pcmobj.lebedev_order = 7\n pcmobj.lmax = 6\n pcmobj.eta = 0.1\n nlm = (pcmobj.lmax+1)**2\n coords_1sph, weights_1sph = make_grids_one_sphere(pcmobj.lebedev_order)\n fi = make_fi(pcmobj, r_vdw)\n ylm_1sph = numpy.vstack(sph.real_sph_vec(coords_1sph, pcmobj.lmax, True))\n L = make_L(pcmobj, r_vdw, ylm_1sph, fi)\n print(lib.finger(L) - 6.2823493771037473)\n\n mol = gto.Mole()\n mol.atom = ''' O 0.00000000 0.00000000 -0.11081188\n H -0.00000000 -0.84695236 0.59109389\n H -0.00000000 0.89830571 0.52404783 '''\n mol.basis = '3-21g' #cc-pvdz'\n mol.build()\n cm = DDCOSMO(mol)\n cm.verbose = 4\n mf = ddcosmo_for_scf(scf.RHF(mol), cm)#.newton()\n mf.verbose = 4\n print(mf.kernel() - -75.570364368059)\n cm.verbose = 3\n e = ddcosmo_for_casci(mcscf.CASCI(mf, 4, 4)).kernel()[0]\n print(e - -75.5743583693215)\n cc_cosmo = ddcosmo_for_post_scf(cc.CCSD(mf)).run()\n print(cc_cosmo.e_tot - -75.70961637250134)\n\n mol = gto.Mole()\n mol.atom = ''' Fe 0.00000000 0.00000000 -0.11081188\n H -0.00000000 -0.84695236 0.59109389\n H -0.00000000 0.89830571 0.52404783 '''\n mol.basis = '3-21g' #cc-pvdz'\n mol.build()\n cm = DDCOSMO(mol)\n cm.eps = -1\n cm.verbose = 4\n mf = ddcosmo_for_scf(scf.ROHF(mol), cm).newton()\n mf.verbose=4\n mf.kernel()\n" ]
[ [ "numpy.dot", "numpy.sqrt", "numpy.einsum", "numpy.asarray", "numpy.arange", "numpy.ndarray", "numpy.zeros_like", "numpy.count_nonzero", "numpy.zeros", "numpy.where", "numpy.empty" ] ]
MyWhiteCastle/datasets
[ "e75a54948bb8aaf9cf45933a538502d2f66c41a6" ]
[ "tensorflow_datasets/image/open_images.py" ]
[ "# coding=utf-8\n# Copyright 2019 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Open images datasets.\n\nhttps://storage.googleapis.com/openimages/web/index.html\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport csv\nimport functools\nimport io\nimport os\n\nfrom absl import logging\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\n\n_DESCRIPTION = '''\\\nOpen Images is a dataset of ~9M images that have been annotated with image-level\n labels and object bounding boxes.\n\nThe training set of V4 contains 14.6M bounding boxes for 600 object classes on\n1.74M images, making it the largest existing dataset with object location\nannotations. The boxes have been largely manually drawn by professional\nannotators to ensure accuracy and consistency. The images are very diverse and\noften contain complex scenes with several objects (8.4 per image on average).\nMoreover, the dataset is annotated with image-level labels spanning thousands of\nclasses.\n'''\n\n_CITATION = '''\\\n@article{OpenImages,\n author = {Alina Kuznetsova and\n Hassan Rom and\n Neil Alldrin and\n Jasper Uijlings and\n Ivan Krasin and\n Jordi Pont-Tuset and\n Shahab Kamali and\n Stefan Popov and\n Matteo Malloci and\n Tom Duerig and\n Vittorio Ferrari},\n title = {The Open Images Dataset V4: Unified image classification,\n object detection, and visual relationship detection at scale},\n year = {2018},\n journal = {arXiv:1811.00982}\n}\n@article{OpenImages2,\n author = {Krasin, Ivan and\n Duerig, Tom and\n Alldrin, Neil and\n Ferrari, Vittorio\n and Abu-El-Haija, Sami and\n Kuznetsova, Alina and\n Rom, Hassan and\n Uijlings, Jasper and\n Popov, Stefan and\n Kamali, Shahab and\n Malloci, Matteo and\n Pont-Tuset, Jordi and\n Veit, Andreas and\n Belongie, Serge and\n Gomes, Victor and\n Gupta, Abhinav and\n Sun, Chen and\n Chechik, Gal and\n Cai, David and\n Feng, Zheyun and\n Narayanan, Dhyanesh and\n Murphy, Kevin},\n title = {OpenImages: A public dataset for large-scale multi-label and\n multi-class image classification.},\n journal = {Dataset available from\n https://storage.googleapis.com/openimages/web/index.html},\n year={2017}\n}\n'''\n\n# Reading from .tar.gz is slower than extracting the gz and then reading from\n# tar. We still read from the tar because it's faster to read fewer files on\n# many network based FS.\n# pylint: disable=line-too-long\n_URLS = {\n 'train_images': [tfds.download.Resource( # pylint:disable=g-complex-comprehension\n url='http://open-images-dataset.s3.amazonaws.com/tar/train_%s.tar.gz' % i_,\n extract_method=tfds.download.ExtractMethod.GZIP)\n for i_ in '0123456789abcdef'],\n 'test_images': tfds.download.Resource(\n url='http://open-images-dataset.s3.amazonaws.com/tar/test.tar.gz',\n extract_method=tfds.download.ExtractMethod.GZIP),\n 'validation_images': tfds.download.Resource(\n url='http://open-images-dataset.s3.amazonaws.com/tar/validation.tar.gz',\n extract_method=tfds.download.ExtractMethod.GZIP),\n 'train_human_labels': 'https://storage.googleapis.com/openimages/2018_04/train/train-annotations-human-imagelabels.csv',\n 'train_machine_labels': 'https://storage.googleapis.com/openimages/2018_04/train/train-annotations-machine-imagelabels.csv',\n 'test_human_labels': 'https://storage.googleapis.com/openimages/2018_04/test/test-annotations-human-imagelabels.csv',\n 'test_machine_labels': 'https://storage.googleapis.com/openimages/2018_04/test/test-annotations-machine-imagelabels.csv',\n 'validation_human_labels': 'https://storage.googleapis.com/openimages/2018_04/validation/validation-annotations-human-imagelabels.csv',\n 'validation_machine_labels': 'https://storage.googleapis.com/openimages/2018_04/validation/validation-annotations-machine-imagelabels.csv',\n 'train-annotations-bbox': 'https://storage.googleapis.com/openimages/2018_04/train/train-annotations-bbox.csv',\n 'test-annotations-bbox': 'https://storage.googleapis.com/openimages/2018_04/test/test-annotations-bbox.csv',\n 'validation-annotations-bbox': 'https://storage.googleapis.com/openimages/2018_04/validation/validation-annotations-bbox.csv',\n}\n# pylint: enable=line-too-long\n\n_Object = collections.namedtuple('Object', ['label', 'confidence', 'source'])\n_Bbox = collections.namedtuple('Bbox', [\n 'label', 'source', 'bbox', 'is_occluded',\n 'is_truncated', 'is_group_of', 'is_depiction', 'is_inside'])\n\nIMAGE_LEVEL_SOURCES = [\n 'verification', 'crowdsource-verification', # human labels\n 'machine',\n]\n\nBBOX_SOURCES = [\n 'freeform', 'xclick', # Manually drawn boxes.\n 'activemil', # Machine generated, human controlled.\n]\n\n\nclass OpenImagesV4Config(tfds.core.BuilderConfig):\n \"\"\"BuilderConfig for OpenImagesV4.\"\"\"\n\n def __init__(self, target_pixels=None, **kwargs):\n \"\"\"BuilderConfig for OpenImagesV4.\n\n Args:\n target_pixels: If given, rescale the images so that the number of pixels\n is roughly this value.\n **kwargs: keyword arguments forward to super.\n \"\"\"\n kwargs['supported_versions'] = [\n tfds.core.Version(\n '2.0.0', 'New split API (https://tensorflow.org/datasets/splits)'),\n ]\n super(OpenImagesV4Config, self).__init__(**kwargs)\n self._target_pixels = target_pixels\n\n @property\n def target_pixels(self):\n return self._target_pixels\n\n\nclass OpenImagesV4(tfds.core.GeneratorBasedBuilder):\n \"\"\"Open Images v4.\"\"\"\n\n BUILDER_CONFIGS = [\n OpenImagesV4Config(\n name='original',\n version=tfds.core.Version(\n '0.2.0', experiments={tfds.core.Experiment.S3: False}),\n description='Images at their original resolution and quality.'),\n OpenImagesV4Config(\n name='300k',\n version=tfds.core.Version(\n '0.2.1', experiments={tfds.core.Experiment.S3: False}),\n description='Images have roughly 300,000 pixels, at 72 JPEG quality.',\n target_pixels=300000),\n OpenImagesV4Config(\n name='200k',\n version=tfds.core.Version(\n '0.2.1', experiments={tfds.core.Experiment.S3: False}),\n description='Images have roughly 200,000 pixels, at 72 JPEG quality.',\n target_pixels=200000)\n ]\n\n def _info(self):\n source_class_label = tfds.features.ClassLabel(\n names=IMAGE_LEVEL_SOURCES + BBOX_SOURCES)\n all_class_label = tfds.features.ClassLabel(\n names_file=tfds.core.get_tfds_path(\n os.path.join('image', 'open_images_classes_all.txt')))\n trainable_class_label = tfds.features.ClassLabel(\n names_file=tfds.core.get_tfds_path(\n os.path.join('image', 'open_images_classes_trainable.txt')))\n boxable_class_label = tfds.features.ClassLabel(\n names_file=tfds.core.get_tfds_path(\n os.path.join('image', 'open_images_classes_boxable.txt')))\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict({\n 'image': tfds.features.Image(),\n 'image/filename': tfds.features.Text(), # eg '226f0a1873b9bf8e.jpg'\n 'objects': tfds.features.Sequence({\n 'label': all_class_label,\n # Original data is 0, .1, ..., 1. We use 0, 1, 2, ..., 10.\n 'confidence': tf.int32,\n 'source': source_class_label,\n }),\n 'objects_trainable': tfds.features.Sequence({\n 'label': trainable_class_label,\n # Original data is 0, .1, ..., 1. We use 0, 1, 2, ..., 10.\n 'confidence': tf.int32,\n 'source': source_class_label,\n }),\n 'bobjects': tfds.features.Sequence({\n 'label': boxable_class_label,\n 'source': source_class_label,\n 'bbox': tfds.features.BBoxFeature(),\n # Following values can be: 1 (true), 0 (false) and -1 (unknown).\n 'is_occluded': tf.int8,\n 'is_truncated': tf.int8,\n 'is_group_of': tf.int8,\n 'is_depiction': tf.int8,\n 'is_inside': tf.int8,\n }),\n }),\n urls=['https://storage.googleapis.com/openimages/web/index.html'],\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n \"\"\"Returns SplitGenerators.\"\"\"\n paths = dl_manager.download_and_extract(_URLS)\n # Load labels from CSVs:\n def load(names):\n csv_positions = [0] * len(names)\n return functools.partial(_load_objects, [paths[name] for name in names],\n csv_positions)\n train_objects = load(['train_human_labels', 'train_machine_labels'])\n test_objects = load(['test_human_labels', 'test_machine_labels'])\n validation_objects = load(['validation_human_labels',\n 'validation_machine_labels'])\n def load_boxes(name):\n csv_positions = [0]\n return functools.partial(_load_bboxes, paths[name], csv_positions)\n train_bbox = load_boxes('train-annotations-bbox')\n test_bbox = load_boxes('test-annotations-bbox')\n validation_bbox = load_boxes('validation-annotations-bbox')\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n num_shards=512,\n gen_kwargs=dict(archive_paths=paths['train_images'],\n objects_getter=train_objects,\n bboxes_getter=train_bbox,\n prefixes='0123456789abcdef'),\n ),\n tfds.core.SplitGenerator(\n name=tfds.Split.TEST,\n num_shards=36,\n gen_kwargs=dict(archive_paths=[paths['test_images']],\n objects_getter=test_objects,\n bboxes_getter=test_bbox),\n ),\n tfds.core.SplitGenerator(\n name=tfds.Split.VALIDATION,\n num_shards=12,\n gen_kwargs=dict(archive_paths=[paths['validation_images']],\n objects_getter=validation_objects,\n bboxes_getter=validation_bbox),\n ),\n ]\n\n def _generate_examples(self, archive_paths, objects_getter, bboxes_getter,\n prefixes=None):\n \"\"\"Yields examples.\"\"\"\n trainable_classes = set(\n self.info.features['objects_trainable']['label'].names)\n for i, archive_path in enumerate(archive_paths):\n prefix = prefixes[i] if prefixes else None\n objects = objects_getter(prefix)\n bboxes = bboxes_getter(prefix)\n logging.info('Opening archive %s ...', archive_path)\n archive = tfds.download.iter_archive(\n archive_path, tfds.download.ExtractMethod.TAR_STREAM)\n for fpath, fobj in archive:\n fname = os.path.basename(fpath)\n image_id = int(os.path.splitext(fname)[0], 16)\n image_objects = [obj._asdict() for obj in objects.get(image_id, [])]\n image_bboxes = [bbox._asdict() for bbox in bboxes.get(image_id, [])]\n image_objects_trainable = [\n obj for obj in image_objects if obj['label'] in trainable_classes\n ]\n record = {\n 'image': _resize_image_if_necessary(\n fobj, target_pixels=self.builder_config.target_pixels),\n 'image/filename': fname,\n 'objects': image_objects,\n 'objects_trainable': image_objects_trainable,\n 'bobjects': image_bboxes,\n }\n yield fname, record\n\n\ndef _resize_image_if_necessary(image_fobj, target_pixels=None):\n \"\"\"Resize an image to have (roughly) the given number of target pixels.\n\n Args:\n image_fobj: File object containing the original image.\n target_pixels: If given, number of pixels that the image must have.\n\n Returns:\n A file object.\n \"\"\"\n if target_pixels is None:\n return image_fobj\n\n cv2 = tfds.core.lazy_imports.cv2\n # Decode image using OpenCV2.\n image = cv2.imdecode(\n np.fromstring(image_fobj.read(), dtype=np.uint8), flags=3)\n # Get image height and width.\n height, width, _ = image.shape\n actual_pixels = height * width\n if actual_pixels > target_pixels:\n factor = np.sqrt(target_pixels / actual_pixels)\n image = cv2.resize(image, dsize=None, fx=factor, fy=factor)\n # Encode the image with quality=72 and store it in a BytesIO object.\n _, buff = cv2.imencode('.jpg', image, [int(cv2.IMWRITE_JPEG_QUALITY), 72])\n return io.BytesIO(buff.tostring())\n\n\ndef _load_objects(csv_paths, csv_positions, prefix):\n \"\"\"Returns objects listed within given CSV files.\"\"\"\n logging.info('Loading CSVs %s from positions %s with prefix %s',\n csv_paths, csv_positions, prefix)\n objects = collections.defaultdict(list)\n for i, labels_path in enumerate(csv_paths):\n with tf.io.gfile.GFile(labels_path) as csv_f:\n if csv_positions[i] > 0:\n csv_f.seek(csv_positions[i])\n else:\n csv_f.readline() # Drop headers\n reader = csv.reader(csv_f)\n for image_id, source, label, confidence in reader:\n if prefix and image_id[0] != prefix:\n break\n csv_positions[i] = csv_f.tell()\n image_id = int(image_id, 16)\n current_obj = _Object(label, int(float(confidence) * 10), source)\n objects[image_id].append(current_obj)\n return dict(objects)\n\n\ndef _load_bboxes(csv_path, csv_positions, prefix):\n \"\"\"Returns bounded boxes listed within given CSV file.\"\"\"\n logging.info('Loading CSVs %s from positions %s with prefix %s',\n csv_path, csv_positions, prefix)\n boxes = collections.defaultdict(list)\n with tf.io.gfile.GFile(csv_path) as csv_f:\n if csv_positions[0] > 0:\n csv_f.seek(csv_positions[0])\n else:\n csv_f.readline() # Drop headers\n reader = csv.reader(csv_f)\n for (image_id, source, label, confidence, xmin, xmax, ymin, ymax,\n is_occluded, is_truncated, is_group_of, is_depiction, is_inside,\n ) in reader:\n if prefix and image_id[0] != prefix:\n break\n csv_positions[0] = csv_f.tell()\n image_id = int(image_id, 16)\n del confidence # always 1 in bounding boxes.\n current_row = _Bbox(\n label, source, tfds.features.BBox(\n float(ymin), float(xmin), float(ymax), float(xmax)),\n int(is_occluded), int(is_truncated),\n int(is_group_of), int(is_depiction), int(is_inside))\n boxes[image_id].append(current_row)\n return dict(boxes)\n" ]
[ [ "tensorflow.io.gfile.GFile", "numpy.sqrt" ] ]
nevinadalal/intro-to-ds
[ "5ae7bd0f0f998961cc49552fc2fc79577603f514" ]
[ "Introduction-to-Data-Science/code.py" ]
[ "# --------------\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n# Read the data\ndata = pd.read_csv(path)\n# print the first 5 rows of the dataset\nprint(data.head())\n\n# Split the data into independent and target variable\nX = data.drop(['G3'],1)\ny = data.G3\n# Split the data into train and test data sets\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3)\n\n\n\n# --------------\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\n\n# Assign the Randomforrest classifier to a variable rf\nrf = RandomForestClassifier()\n\n# Train the model\nrf.fit(X_train,y_train)\n\n# Predict the class on the test data\ny_pred = rf.predict(X_test)\n\n\n\n# --------------\nfrom sklearn.metrics import accuracy_score,mean_absolute_error\n\n# Accuracy score\naccuracy_score(y_test,y_pred)\n\n\n\n" ]
[ [ "pandas.read_csv", "sklearn.model_selection.train_test_split", "sklearn.ensemble.RandomForestClassifier", "sklearn.metrics.accuracy_score" ] ]
SriMethan/python-tictactoe
[ "40dcd64c7a42c1e4a94eb40d54e985f7165f46c2" ]
[ "tictactoe/__init__.py" ]
[ "import itertools\r\nimport numpy\r\n\r\nX = 1\r\nO = 2\r\n\r\n\r\nclass Board:\r\n def __init__(self, dimensions=(3, 3), x_in_a_row=3):\r\n self.dimensions = dimensions\r\n self.x_in_a_row = x_in_a_row\r\n self.board = self.create_board()\r\n self._directions = self.find_directions()\r\n self.move_count = 0\r\n self.moves = []\r\n self.x = []\r\n self.o = []\r\n self.turn = X\r\n\r\n def create_board(self):\r\n return numpy.zeros(self.dimensions)\r\n\r\n def copy(self):\r\n board = Board(self.dimensions, self.x_in_a_row)\r\n board.turn = self.turn\r\n board.board = self.board.copy()\r\n return board\r\n\r\n def get_mark_at_position(self, position):\r\n position = tuple(position)\r\n return self.board[position]\r\n\r\n def set_mark(self, coordinates, player):\r\n self.board[coordinates] = player\r\n if player == X:\r\n self.x.append(Move(coordinates))\r\n else:\r\n self.o.append(Move(coordinates))\r\n\r\n def is_empty(self, position):\r\n return self.get_mark_at_position(position) == 0\r\n\r\n def push(self, coordinates):\r\n coordinates = tuple(coordinates)\r\n if not self.is_empty(coordinates):\r\n raise Exception(\"Position is not empty.\")\r\n move = Move(coordinates)\r\n self.set_mark(coordinates, self.turn)\r\n self.turn = X if self.turn == O else O\r\n self.moves.append(move)\r\n self.move_count += 1\r\n\r\n def find_directions(self):\r\n directions = list(itertools.product([1, 0, -1], repeat=len(self.dimensions)))\r\n correct_directions = []\r\n for direction in directions:\r\n for item in direction:\r\n if item > 0:\r\n correct_directions.append(direction)\r\n break\r\n elif item < 0:\r\n break\r\n return correct_directions\r\n\r\n def possible_moves(self):\r\n return numpy.argwhere(self.board == 0)\r\n\r\n def out_of_bounds(self, pos):\r\n return (pos < 0).any() or (pos >= self.dimensions).any()\r\n\r\n def in_bounds(self, pos):\r\n return not self.out_of_bounds(pos)\r\n\r\n def has_won(self, player):\r\n positions = numpy.argwhere(self.board == player)\r\n for position in positions:\r\n for direction in self._directions:\r\n for in_a_row in range(1, self.x_in_a_row):\r\n pos = position + numpy.multiply(direction, in_a_row)\r\n if self.out_of_bounds(pos) or self.board[tuple(pos)] != player:\r\n break\r\n else:\r\n return True\r\n return False\r\n\r\n def result(self):\r\n if self.has_won(X):\r\n return X\r\n elif self.has_won(O):\r\n return O\r\n elif self.board.all():\r\n return 0\r\n\r\n\r\nclass Move:\r\n def __init__(self, coordinate_move=None, str_move=None):\r\n assert coordinate_move or str_move\r\n self.coordinate_move = coordinate_move\r\n self.str_move = str_move\r\n if self.coordinate_move:\r\n self.str_move = \"-\".join(map(str, tuple(self.coordinate_move)))\r\n else:\r\n self.coordinate_move = tuple(map(int, self.str_move.split(\"-\")))\r\n" ]
[ [ "numpy.zeros", "numpy.multiply", "numpy.argwhere" ] ]
txsing/RobustNet
[ "e5bc6f3234f2140a265279999d7ba91e6cd7011f" ]
[ "datasets/kitti.py" ]
[ "\"\"\"\r\nKITTI Dataset Loader\r\n\"\"\"\r\n\r\nimport os\r\nimport sys\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom torch.utils import data\r\nimport logging\r\nimport datasets.uniform as uniform\r\nimport datasets.cityscapes_labels as cityscapes_labels\r\nimport json\r\nfrom config import cfg\r\n\r\n\r\ntrainid_to_name = cityscapes_labels.trainId2name\r\nid_to_trainid = cityscapes_labels.label2trainid\r\nnum_classes = 19\r\nignore_label = 255\r\nroot = cfg.DATASET.KITTI_DIR\r\naug_root = cfg.DATASET.KITTI_AUG_DIR\r\n\r\npalette = [128, 64, 128, 244, 35, 232, 70, 70, 70, 102, 102, 156, 190, 153, 153,\r\n 153, 153, 153, 250, 170, 30,\r\n 220, 220, 0, 107, 142, 35, 152, 251, 152, 70, 130, 180, 220, 20, 60,\r\n 255, 0, 0, 0, 0, 142, 0, 0, 70,\r\n 0, 60, 100, 0, 80, 100, 0, 0, 230, 119, 11, 32]\r\nzero_pad = 256 * 3 - len(palette)\r\nfor i in range(zero_pad):\r\n palette.append(0)\r\n\r\ndef colorize_mask(mask):\r\n # mask: numpy array of the mask\r\n new_mask = Image.fromarray(mask.astype(np.uint8)).convert('P')\r\n new_mask.putpalette(palette)\r\n return new_mask\r\n\r\ndef get_train_val(cv_split, all_items):\r\n\r\n # 90/10 train/val split, three random splits\r\n val_0 = [1,5,11,29,35,49,57,68,72,82,93,115,119,130,145,154,156,167,169,189,198]\r\n val_1 = [0,12,24,31,42,50,63,71,84,96,101,112,121,133,141,155,164,171,187,191,197]\r\n val_2 = [3,6,13,21,41,54,61,73,88,91,110,121,126,131,142,149,150,163,173,183,199]\r\n\r\n train_set = []\r\n val_set = []\r\n\r\n if cv_split == 0:\r\n for i in range(200):\r\n if i in val_0:\r\n val_set.append(all_items[i])\r\n else:\r\n train_set.append(all_items[i])\r\n elif cv_split == 1:\r\n for i in range(200):\r\n if i in val_1:\r\n val_set.append(all_items[i])\r\n else:\r\n train_set.append(all_items[i])\r\n elif cv_split == 2:\r\n for i in range(200):\r\n if i in val_2:\r\n val_set.append(all_items[i])\r\n else:\r\n train_set.append(all_items[i])\r\n else:\r\n logging.info('Unknown cv_split {}'.format(cv_split))\r\n sys.exit()\r\n\r\n return train_set, val_set\r\n\r\ndef make_dataset(quality, mode, maxSkip=0, cv_split=0, hardnm=0):\r\n \r\n items = []\r\n all_items = []\r\n aug_items = []\r\n\r\n assert quality == 'semantic' \r\n assert mode in ['train', 'val', 'trainval']\r\n # note that train and val are randomly determined, no official split\r\n\r\n img_dir_name = \"training\"\r\n img_path = os.path.join(root, img_dir_name, 'image_2')\r\n mask_path = os.path.join(root, img_dir_name, 'semantic')\r\n\r\n c_items = os.listdir(img_path)\r\n c_items.sort()\r\n\r\n for it in c_items:\r\n item = (os.path.join(img_path, it), os.path.join(mask_path, it))\r\n all_items.append(item)\r\n logging.info('KITTI has a total of {} images'.format(len(all_items)))\r\n\r\n # split into train/val \r\n train_set, val_set = get_train_val(cv_split, all_items)\r\n\r\n if mode == 'train':\r\n items = train_set\r\n elif mode == 'val':\r\n items = val_set\r\n elif mode == 'trainval':\r\n items = train_set + val_set\r\n else:\r\n logging.info('Unknown mode {}'.format(mode))\r\n sys.exit()\r\n\r\n logging.info('KITTI-{}: {} images'.format(mode, len(items)))\r\n\r\n return items, aug_items\r\n\r\nclass KITTI(data.Dataset):\r\n\r\n def __init__(self, quality, mode, maxSkip=0, joint_transform_list=None,\r\n transform=None, target_transform=None, dump_images=False,\r\n class_uniform_pct=0, class_uniform_tile=0, test=False, \r\n cv_split=None, scf=None, hardnm=0):\r\n\r\n self.quality = quality\r\n self.mode = mode\r\n self.maxSkip = maxSkip\r\n self.joint_transform_list = joint_transform_list\r\n self.transform = transform\r\n self.target_transform = target_transform\r\n self.dump_images = dump_images\r\n self.class_uniform_pct = class_uniform_pct\r\n self.class_uniform_tile = class_uniform_tile\r\n self.scf = scf\r\n self.hardnm = hardnm\r\n\r\n if cv_split:\r\n self.cv_split = cv_split\r\n assert cv_split < cfg.DATASET.CV_SPLITS, \\\r\n 'expected cv_split {} to be < CV_SPLITS {}'.format(\r\n cv_split, cfg.DATASET.CV_SPLITS)\r\n else:\r\n self.cv_split = 0\r\n\r\n self.imgs, _ = make_dataset(quality, mode, self.maxSkip, cv_split=self.cv_split, hardnm=self.hardnm)\r\n assert len(self.imgs), 'Found 0 images, please check the data set'\r\n # self.cal_shape(self.imgs)\r\n\r\n # Centroids for GT data\r\n if self.class_uniform_pct > 0:\r\n if self.scf:\r\n json_fn = 'kitti_tile{}_cv{}_scf.json'.format(self.class_uniform_tile, self.cv_split)\r\n else:\r\n json_fn = 'kitti_tile{}_cv{}_{}_hardnm{}.json'.format(self.class_uniform_tile, self.cv_split, self.mode, self.hardnm)\r\n if os.path.isfile(json_fn):\r\n with open(json_fn, 'r') as json_data:\r\n centroids = json.load(json_data)\r\n self.centroids = {int(idx): centroids[idx] for idx in centroids}\r\n else:\r\n if self.scf:\r\n self.centroids = kitti_uniform.class_centroids_all(\r\n self.imgs,\r\n num_classes,\r\n id2trainid=id_to_trainid,\r\n tile_size=class_uniform_tile)\r\n else:\r\n self.centroids = uniform.class_centroids_all(\r\n self.imgs,\r\n num_classes,\r\n id2trainid=id_to_trainid,\r\n tile_size=class_uniform_tile)\r\n with open(json_fn, 'w') as outfile:\r\n json.dump(self.centroids, outfile, indent=4)\r\n\r\n self.build_epoch()\r\n\r\n\r\n def cal_shape(self, imgs):\r\n\r\n for i in imgs:\r\n img_path, mask_path = i\r\n img = Image.open(img_path).convert('RGB')\r\n print(img.size)\r\n\r\n def build_epoch(self, cut=False):\r\n if self.class_uniform_pct > 0:\r\n self.imgs_uniform = uniform.build_epoch(self.imgs,\r\n self.centroids,\r\n num_classes,\r\n cfg.CLASS_UNIFORM_PCT)\r\n else:\r\n self.imgs_uniform = self.imgs\r\n\r\n def __getitem__(self, index):\r\n elem = self.imgs_uniform[index]\r\n centroid = None\r\n if len(elem) == 4:\r\n img_path, mask_path, centroid, class_id = elem\r\n else:\r\n img_path, mask_path = elem\r\n\r\n img, mask = Image.open(img_path).convert('RGB'), Image.open(mask_path)\r\n img_name = os.path.splitext(os.path.basename(img_path))[0]\r\n\r\n # kitti scale correction factor\r\n if self.mode == 'train' or self.mode == 'trainval':\r\n if self.scf:\r\n width, height = img.size\r\n img = img.resize((width*2, height*2), Image.BICUBIC)\r\n mask = mask.resize((width*2, height*2), Image.NEAREST)\r\n elif self.mode == 'val':\r\n width, height = 1242, 376\r\n img = img.resize((width, height), Image.BICUBIC)\r\n mask = mask.resize((width, height), Image.NEAREST)\r\n else:\r\n logging.info('Unknown mode {}'.format(mode))\r\n sys.exit()\r\n\r\n mask = np.array(mask)\r\n mask_copy = mask.copy()\r\n\r\n for k, v in id_to_trainid.items():\r\n mask_copy[mask == k] = v\r\n mask = Image.fromarray(mask_copy.astype(np.uint8))\r\n\r\n # Image Transformations\r\n if self.joint_transform_list is not None:\r\n for idx, xform in enumerate(self.joint_transform_list):\r\n if idx == 0 and centroid is not None:\r\n # HACK\r\n # We assume that the first transform is capable of taking\r\n # in a centroid\r\n img, mask = xform(img, mask, centroid)\r\n else:\r\n img, mask = xform(img, mask)\r\n\r\n # Debug\r\n if self.dump_images and centroid is not None:\r\n outdir = './dump_imgs_{}'.format(self.mode)\r\n os.makedirs(outdir, exist_ok=True)\r\n dump_img_name = trainid_to_name[class_id] + '_' + img_name\r\n out_img_fn = os.path.join(outdir, dump_img_name + '.png')\r\n out_msk_fn = os.path.join(outdir, dump_img_name + '_mask.png')\r\n mask_img = colorize_mask(np.array(mask))\r\n img.save(out_img_fn)\r\n mask_img.save(out_msk_fn)\r\n\r\n if self.transform is not None:\r\n img = self.transform(img)\r\n if self.target_transform is not None:\r\n mask = self.target_transform(mask)\r\n\r\n return img, mask, img_name\r\n\r\n def __len__(self):\r\n return len(self.imgs_uniform)\r\n\r\n" ]
[ [ "numpy.array" ] ]
TomasTrnkaPLC/TrainYourOwnYOLO
[ "9c831d0c14046fe436378a7407a62dd247a3ef82" ]
[ "2_Training/Train_YOLO.py" ]
[ "\n\nimport os\nimport sys\nimport argparse\nimport time\nimport datetime\ndef get_parent_dir(n=1):\n \"\"\" returns the n-th parent dicrectory of the current\n working directory \"\"\"\n current_path = os.path.dirname(os.path.abspath(__file__))\n for k in range(n):\n current_path = os.path.dirname(current_path)\n return current_path\n\nsrc_path = os.path.join(get_parent_dir(0),'src')\nsys.path.append(src_path)\n\nutils_path = os.path.join(get_parent_dir(1),'Utils')\nsys.path.append(utils_path)\nimport tensorflow as tf\nTF_VERSION2=tf.__version__.startswith(\"2\")\nif TF_VERSION2: from tensorflow import keras\nimport numpy as np\nimport keras.backend as K\nfrom tensorflow.keras.layers import Input, Lambda\nfrom tensorflow.keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping\nfrom keras_yolo3.yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss\nfrom keras_yolo3.yolo3.utils import get_random_data\nfrom PIL import Image\nfrom time import time\nimport pickle\nimport timeit\n\nconfig = tf.compat.v1.ConfigProto()\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.7\nconfig.log_device_placement = False # to log device placement (on which device the operation ran)\nsess = tf.compat.v1.Session(config=config)\nK.set_session(sess)\nfrom Train_Utils import get_classes, get_anchors, create_model, create_tiny_model, data_generator, data_generator_wrapper, ChangeToOtherMachine\n\n\nkeras_path = os.path.join(src_path,'keras_yolo3')\nData_Folder = os.path.join(get_parent_dir(1),'Data')\nImage_Folder = os.path.join(Data_Folder,'Source_Images','Training_Images')\nVoTT_Folder = os.path.join(Image_Folder,'vott-csv-export')\nYOLO_filename = os.path.join(VoTT_Folder,'data_train.txt')\nprint (YOLO_filename)\nModel_Folder = os.path.join(Data_Folder,'Model_Weights')\nYOLO_classname = os.path.join(Model_Folder,'data_classes.txt')\nYOLO_yaml = os.path.join(Model_Folder,'data.yaml')\nYOLO_xml = os.path.join(Model_Folder,'data.json')\nlog_dir = Model_Folder\nanchors_path = os.path.join(keras_path,'model_data','yolo_anchors.txt') \nweights_path = os.path.join(keras_path,'yolo.h5') \n\nFLAGS = None\n\nif __name__ == '__main__':\n # Delete all default flags\n parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)\n '''\n Command line options\n '''\n\n parser.add_argument(\n \"--annotation_file\", type=str, default=YOLO_filename,\n help = \"Path to annotation file for Yolo. Default is \"+ YOLO_filename\n )\n parser.add_argument(\n \"--classes_file\", type=str, default=YOLO_classname,\n help = \"Path to YOLO classnames. Default is \"+ YOLO_classname\n )\n\n parser.add_argument(\n \"--log_dir\", type=str, default=log_dir,\n help = \"Folder to save training logs and trained weights to. Default is \"+ log_dir \n )\n\n parser.add_argument(\n \"--anchors_path\", type=str, default=anchors_path,\n help = \"Path to YOLO anchors. Default is \"+ anchors_path\n )\n\n parser.add_argument(\n \"--weights_path\", type=str, default=weights_path,\n help = \"Path to pre-trained YOLO weights. Default is \"+ weights_path\n )\n parser.add_argument(\n \"--val_split\", type=float, default=0.1,\n help = \"Percentage of training set to be used for validation. Default is 10%.\"\n )\n parser.add_argument(\n \"--is_tiny\", default=False, action=\"store_true\",\n help = \"Use the tiny Yolo version for better performance and less accuracy. Default is False.\"\n )\n parser.add_argument(\n \"--random_seed\", type=float, default=None,\n help = \"Random seed value to make script deterministic. Default is 'None', i.e. non-deterministic.\"\n )\n parser.add_argument(\n \"--epochs\", type=float, default=30,\n help = \"Number of epochs for training last layers and number of epochs for fine-tuning layers. Default is 51.\"\n )\n\n \n FLAGS = parser.parse_args()\n\n np.random.seed(FLAGS.random_seed)\n\n log_dir = FLAGS.log_dir\n\n class_names = get_classes(FLAGS.classes_file)\n num_classes = len(class_names)\n anchors = get_anchors(FLAGS.anchors_path)\n weights_path = FLAGS.weights_path\n\n input_shape = (416, 416) # multiple of 32, height, width\n epoch1, epoch2 = FLAGS.epochs, FLAGS.epochs\n\n is_tiny_version = (len(anchors)==6) # default setting\n if FLAGS.is_tiny:\n model = create_tiny_model(input_shape, anchors, num_classes,\n freeze_body=2, weights_path = weights_path)\n else:\n model = create_model(input_shape, anchors, num_classes,\n freeze_body=2, weights_path = weights_path) # make sure you know what you freeze\n\n log_dir_time = os.path.join(log_dir,'{}'.format(int(time())))\n logging = TensorBoard(log_dir=log_dir_time)\n checkpoint = ModelCheckpoint(os.path.join(log_dir,'checkpoint.h5'),\n monitor='val_loss', save_weights_only=True, save_best_only=True, period=5)\n reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1)\n early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1)\n\n val_split = FLAGS.val_split\n with open(FLAGS.annotation_file) as f:\n lines = f.readlines()\n\n # This step makes sure that the path names correspond to the local machine\n # This is important if annotation and training are done on different machines (e.g. training on AWS)\n #lines = ChangeToOtherMachine(lines,remote_machine = '')\n np.random.shuffle(lines)\n num_val = int(len(lines)*val_split)\n num_train = len(lines) - num_val\n\n # Train with frozen layers first, to get a stable loss.\n # Adjust num epochs to your dataset. This step is enough to obtain a decent model.\n if True:\n start = time()\n model.compile(optimizer=Adam(lr=1e-3), loss={\n # use custom yolo_loss Lambda layer.\n 'yolo_loss': lambda y_true, y_pred: y_pred})\n\n batch_size = 12\n print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))\n history = model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),\n steps_per_epoch=max(1, num_train//batch_size),\n validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes),\n validation_steps=max(1, num_val//batch_size),\n epochs=epoch1,\n initial_epoch=0,\n callbacks=[logging, checkpoint])\n model.save_weights(os.path.join(log_dir,'trained_weights_stage_1.h5'))\n\n step1_train_loss = history.history['loss']\n \n file = open(os.path.join(log_dir_time,'step1_loss.npy'), \"w\")\n with open(os.path.join(log_dir_time,'step1_loss.npy'), 'w') as f:\n for item in step1_train_loss:\n f.write(\"%s\\n\" % item) \n file.close()\n \n step1_val_loss = np.array(history.history['val_loss'])\n \n file = open(os.path.join(log_dir_time,'step1_val_loss.npy'), \"w\")\n with open(os.path.join(log_dir_time,'step1_val_loss.npy'), 'w') as f:\n for item in step1_val_loss:\n f.write(\"%s\\n\" % item) \n file.close()\n \n # Unfreeze and continue training, to fine-tune.\n # Train longer if the result is unsatisfactory.\n if True:\n for i in range(len(model.layers)):\n model.layers[i].trainable = True\n model.compile(optimizer=Adam(lr=1e-4), loss={'yolo_loss': lambda y_true, y_pred: y_pred}) # recompile to apply the change\n print('Unfreeze all layers.')\n\n batch_size = 4 # note that more GPU memory is required after unfreezing the body\n print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))\n history=model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),\n steps_per_epoch=max(1, num_train//batch_size),\n validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes),\n validation_steps=max(1, num_val//batch_size),\n epochs=epoch1+epoch2,\n initial_epoch=epoch1,\n callbacks=[logging, checkpoint, reduce_lr, early_stopping])\n model.save_weights(os.path.join(log_dir,'trained_weights_final_t1.h5'))\n model.save_weights(os.path.join(log_dir,'trained_weights_final_t1.h5'))\n model.save_weights(os.path.join(log_dir,'trained_weights_final_t2.hdf5'))\n model.save(os.path.join(log_dir,'model.h5'))\n model.save(os.path.join(log_dir,'model2.hdf5'))\n step2_train_loss = history.history['loss']\n \n file = open(os.path.join(log_dir_time,'step2_loss.npy'), \"w\")\n with open(os.path.join(log_dir_time,'step2_loss.npy'), 'w') as f:\n for item in step2_train_loss:\n f.write(\"%s\\n\" % item) \n file.close()\n \n step2_val_loss = np.array(history.history['val_loss'])\n \n file = open(os.path.join(log_dir_time,'step2_val_loss.npy'), \"w\")\n with open(os.path.join(log_dir_time,'step2_val_loss.npy'), 'w') as f:\n for item in step2_val_loss:\n f.write(\"%s\\n\" % item) \n file.close()\n end = time()\n # Time elapsed\n seconds = end - start\n seconds = round(seconds , 3)\n print (\"Process taken : {0} seconds\".format(seconds)) \n" ]
[ [ "tensorflow.compat.v1.ConfigProto", "numpy.random.seed", "numpy.random.shuffle", "tensorflow.compat.v1.Session", "numpy.array", "tensorflow.__version__.startswith" ] ]
kuc2477/pytorch-wgan-gp
[ "0a1e8bd719577ffd7061059fcf26bc61fe2bd076" ]
[ "train.py" ]
[ "from torch import optim\nfrom torch.autograd import Variable\nfrom tqdm import tqdm\nimport utils\nimport visual\n\n\ndef train(model, dataset, collate_fn=None,\n lr=1e-04, weight_decay=1e-04, beta1=0.5, beta2=.999, lamda=10.,\n batch_size=32, sample_size=32, epochs=10,\n d_trains_per_g_train=2,\n checkpoint_dir='checkpoints',\n checkpoint_interval=1000,\n image_log_interval=100,\n loss_log_interval=30,\n resume=False, cuda=False):\n # define the optimizers.\n generator_optimizer = optim.Adam(\n model.generator.parameters(), lr=lr, betas=(beta1, beta2),\n weight_decay=weight_decay\n )\n critic_optimizer = optim.Adam(\n model.critic.parameters(), lr=lr, betas=(beta1, beta2),\n weight_decay=weight_decay\n )\n\n # prepare the model and statistics.\n model.train()\n epoch_start = 1\n\n # load checkpoint if needed.\n if resume:\n iteration = utils.load_checkpoint(model, checkpoint_dir)\n epoch_start = iteration // (len(dataset) // batch_size) + 1\n\n for epoch in range(epoch_start, epochs+1):\n data_loader = utils.get_data_loader(\n dataset, batch_size,\n cuda=cuda, collate_fn=collate_fn,\n )\n data_stream = tqdm(enumerate(data_loader, 1))\n for batch_index, data in data_stream:\n # unpack the data if needed.\n try:\n x, _ = data\n except ValueError:\n x = data\n\n # where are we?\n dataset_size = len(data_loader.dataset)\n dataset_batches = len(data_loader)\n iteration = (\n (epoch-1)*(dataset_size // batch_size) +\n batch_index + 1\n )\n\n # prepare the data.\n x = Variable(x).cuda() if cuda else Variable(x)\n d_trains = (\n 30 if (batch_index < 25 or batch_index % 500 == 0) else\n d_trains_per_g_train\n )\n\n # run the critic and backpropagate the errors.\n for _ in range(d_trains):\n critic_optimizer.zero_grad()\n z = model.sample_noise(batch_size)\n c_loss, g = model.c_loss(x, z, return_g=True)\n c_loss_gp = c_loss + model.gradient_penalty(x, g, lamda=lamda)\n c_loss_gp.backward()\n critic_optimizer.step()\n\n # run the generator and backpropagate the errors.\n generator_optimizer.zero_grad()\n z = model.sample_noise(batch_size)\n g_loss = model.g_loss(z)\n g_loss.backward()\n generator_optimizer.step()\n\n # update the progress.\n data_stream.set_description((\n 'epoch: {epoch}/{epochs} | '\n 'iteration: {iteration} | '\n 'progress: [{trained}/{total}] ({progress:.0f}%) | '\n 'loss => '\n 'g: {g_loss:.4} / '\n 'w: {w_dist:.4}'\n ).format(\n epoch=epoch,\n epochs=epochs,\n iteration=iteration,\n trained=batch_index*batch_size,\n total=dataset_size,\n progress=(100.*batch_index/dataset_batches),\n g_loss=g_loss.data[0],\n w_dist=-c_loss.data[0],\n ))\n\n # send losses to the visdom server.\n if iteration % loss_log_interval == 0:\n visual.visualize_scalar(\n -c_loss.data[0],\n 'estimated wasserstein distance between x and g',\n iteration=iteration,\n env=model.name\n )\n visual.visualize_scalar(\n g_loss.data[0],\n 'generator loss',\n iteration=iteration,\n env=model.name\n )\n\n # send sample images to the visdom server.\n if iteration % image_log_interval == 0:\n visual.visualize_images(\n model.sample_image(sample_size).data,\n 'generated samples',\n env=model.name\n )\n\n # save the model at checkpoints.\n if iteration % checkpoint_interval == 0:\n # notify that we've reached to a new checkpoint.\n print()\n print()\n print('#############')\n print('# checkpoint!')\n print('#############')\n print()\n\n utils.save_checkpoint(model, checkpoint_dir, iteration)\n\n print()\n" ]
[ [ "torch.autograd.Variable" ] ]
Amdis23/Tapestry_Intial
[ "7924380692df59fed3c3b982a2de0558cac3a419" ]
[ "algos/clustered_sbl.py" ]
[ "# vim: tabstop=2 expandtab shiftwidth=2 softtabstop=8\n\n# Imports the precise variant of SBL using clustering method instead of\n# thresholding\n\nfrom inbuilt_algos import sbl\n\nimport numpy as np\n\n# Use thresholding method 'cluster' for SBL to get very precise results\ndef clustered_sbl(params):\n A = params[\"A\"]\n y = params[\"y\"]\n t = A.shape[0]\n n = A.shape[1]\n #print(t, n)\n #print(len(y))\n assert t == len(y)\n x_est = sbl.sbl(A, y, thresholding_method='cluster') \n res = {'x_est' : x_est}\n #print(\"config.noise_model = \", config.noise_model)\n return res\n\n# clustered SBL has some variability in results. \n#\n# Repeat above precise SBL many times to reduce variability\ndef sbl_multi(params, selection_method, n_tries, frac):\n A = params[\"A\"]\n y = params[\"y\"]\n t = A.shape[0]\n n = A.shape[1]\n #print(t, n)\n #print(len(y))\n assert t == len(y)\n sum_x_est = np.zeros(n, dtype=np.int32)\n and_x_est = np.ones(n, dtype=np.int32)\n for i in range(n_tries):\n tmp_x_est = sbl.sbl(A, y, thresholding_method='cluster') \n tmp_x_est = (tmp_x_est > 0).astype(np.int32)\n sum_x_est += tmp_x_est\n and_x_est = and_x_est * tmp_x_est\n \n union_x_est = (sum_x_est > 0).astype(np.int32)\n # Only choose an x if chosen by 80% of tests\n maj_x_est = np.zeros(n)\n maj_x_est[sum_x_est >= n_tries * frac] = 1\n #res = {'x_est' : sum_x_est}\n if selection_method == 'majority':\n res = {'x_est' : maj_x_est}\n elif selection_method == 'union':\n res = {'x_est' : union_x_est}\n elif selection_method == 'intersection':\n res = {'x_est' : and_x_est}\n else:\n raise ValueError('wrong selection method: %s' % selection_method)\n\n #print(\"config.noise_model = \", config.noise_model)\n return res\n" ]
[ [ "numpy.zeros", "numpy.ones" ] ]
damirmardanov/figure-generator
[ "1ed7ee6d423f2d7392e95529336b8f2d35ea65fd" ]
[ "Plotter.py" ]
[ "import matplotlib.pyplot as plt\nimport numpy.random as rnd\n\n\nclass Plotter:\n @staticmethod\n def plot(figure=None, figures=None, filename='output.png', height=27, width=27):\n fig = plt.figure(0, figsize=(height / 102, width / 102), dpi=102)\n ax = fig.add_subplot(111, aspect='equal')\n if (figure is not None) and (figures is None):\n ax.add_artist(figure)\n else:\n for figure in figures:\n ax.add_artist(figure)\n figure.set_clip_box(ax.bbox)\n figure.set_alpha(rnd.rand())\n ax.set_xlim(0, 10)\n ax.set_ylim(0, 10)\n\n plt.axis('off')\n plt.savefig(filename)\n plt.clf()\n\n" ]
[ [ "matplotlib.pyplot.savefig", "matplotlib.pyplot.clf", "numpy.random.rand", "matplotlib.pyplot.axis", "matplotlib.pyplot.figure" ] ]
pdooner/azure-cosmos-db-mongo-migration
[ "35e0e2f606c27fdd681c57095aac1038f12ce88e" ]
[ "m2c/mongoexport_pk_analyze.py" ]
[ "\n\"\"\"\nUsage:\n python mongoexport_analyze.py hello_matplotlib\n ---\n source env.sh\n export infile=$M2C_APP_DATA_DIR/mongoexports/openflights/openflights__routes.json\n python mongoexport_pk_analyze.py pk_analysis $infile\n\"\"\"\n\n\n\n__author__ = 'Chris Joakim'\n__email__ = \"[email protected]\"\n__license__ = \"MIT\"\n__version__ = \"October 2021\"\n\n# Links:\n# https://pandas.pydata.org/\n# https://matplotlib.org/\n# https://pandas.pydata.org/docs/getting_started/intro_tutorials/04_plotting.html\n\nimport os\nimport sys\nimport time\nimport traceback\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom docopt import docopt\n\nplt.style.use('classic')\n\ndef hello_matplotlib():\n # simple test of your python configuration. if you run \n # 'python mongoexport_analyze.py hello_matplotlib' on the command-line\n # and see a popup window with a graph, then it's working properly.\n x = np.linspace(0, 10, 100)\n plt.plot(x, np.sin(x))\n plt.plot(x, np.cos(x))\n plt.show()\n\ndef pk_analysis(infile):\n print('mongoexport_pk_analyze: {}'.format(infile))\n df = pd.read_json(infile, lines=True)\n describe_df(df, 'mongoexport file: {}'.format(infile))\n print(df.head())\n candidate_attrs = 'airline_id,from_airport,to_airport,equipment'.split(',')\n show_popup_visualization = False\n\n for attr_name in candidate_attrs:\n unique_values = df[attr_name].unique()\n print(\"attribute '{}' has {} unique values\".format(attr_name, len(unique_values)))\n counts = df[attr_name].value_counts()\n counts.plot()\n if show_popup_visualization:\n plt.show()\n else:\n outfile = 'plots/{}.png'.format(attr_name)\n plt.savefig(outfile)\n print('plot saved to file {}'.format(outfile))\n\ndef describe_df(df, msg):\n print('=== describe df: {}'.format(msg))\n print(str(type(df))) # <class 'pandas.core.frame.DataFrame'>\n print('--- df.dtypes')\n print(df.dtypes)\n print('--- df.shape')\n print(df.shape)\n\ndef print_options(msg):\n print(msg)\n arguments = docopt(__doc__, version=__version__)\n print(arguments)\n\n\nif __name__ == \"__main__\":\n\n if len(sys.argv) > 1:\n func = sys.argv[1].lower()\n\n if func == 'hello_matplotlib':\n hello_matplotlib()\n elif func == 'pk_analysis':\n infile = sys.argv[2]\n pk_analysis(infile)\n else:\n print_options('Error: invalid command-line function: {}'.format(func))\n else:\n print_options('Error: no command-line function given')\n\n\n# Sample Output:\n#\n# $ python mongoexport_analyze.py pk_analysis raw_data/mongoexport/openflights__routes.json\n# mongoexport_pk_analyze: raw_data/mongoexport/openflights__routes.json\n# === describe df: mongoexport file: raw_data/mongoexport/openflights__routes.json\n# <class 'pandas.core.frame.DataFrame'>\n# --- df.dtypes\n# _id object\n# airline_id object\n# openflights_airline_id object\n# from_airport object\n# openflights_from_airport object\n# to_airport object\n# openflights_to_airport object\n# x object\n# codeshare int64\n# equipment object\n# dtype: object\n# --- df.shape\n# (67663, 10)\n# _id airline_id openflights_airline_id ... x codeshare equipment\n# 0 {'$oid': '6166d5927a8e7d4fa3497300'} 2B 410 ... 0 CR2\n# 1 {'$oid': '6166d5927a8e7d4fa3497301'} 2B 410 ... 0 CR2\n# 2 {'$oid': '6166d5927a8e7d4fa3497302'} 2B 410 ... 0 CR2\n# 3 {'$oid': '6166d5927a8e7d4fa3497303'} 2B 410 ... 0 CR2\n# 4 {'$oid': '6166d5927a8e7d4fa3497304'} 2B 410 ... 0 CR2\n\n# [5 rows x 10 columns]\n# attribute 'airline_id' has 568 unique values\n# plot saved to file plots/airline_id.png\n# attribute 'from_airport' has 3409 unique values\n# plot saved to file plots/from_airport.png\n# attribute 'to_airport' has 3418 unique values\n# plot saved to file plots/to_airport.png\n# attribute 'equipment' has 3946 unique values\n# plot saved to file plots/equipment.png\n" ]
[ [ "numpy.linspace", "numpy.cos", "matplotlib.pyplot.savefig", "numpy.sin", "pandas.read_json", "matplotlib.pyplot.show", "matplotlib.pyplot.style.use" ] ]
gbalke/bldc-controller
[ "99e4e71d5bdc0c7c7901d886aa7709c66db8b718" ]
[ "tools/dev/characterize.py" ]
[ "#!/usr/bin/env python\nfrom __future__ import division\nfrom comms import *\nimport serial\nimport sys\nimport time\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\nfrom scipy.integrate import odeint\n\nPWM_DUTY_CYCLE = 0.3\n\nif len(sys.argv) >= 3:\n # Data collection mode\n\n # if len(sys.argv) < 3:\n # print(\"give me a serial port and address\")\n # exit()\n\n port = sys.argv[1]\n s = serial.Serial(port=port, baudrate=COMM_DEFAULT_BAUD_RATE, timeout=0.1)\n\n address = int(sys.argv[2])\n\n client = BLDCControllerClient(s, protocol_v2=True)\n\n # angle_mapping = {1: 726, 2: 243, 3: 2827, 4: 1125, 5: 7568, 10: 800, 11: 823, 12: 501, 13: 10054, 14: 1008, 15: 775, 16: 22, 17: 1087, 18: 247, 19: 601, 20: 721, 21: 621, 22: 269, 23: 678, 24: 518} # mapping of id to joints\n\n # needs_flip_phase = [3, 4, 11, 17, 18, 22, 23, 24]\n\n # has_21_erevs_per_mrev = [2, 13, 18, 19, 20, 21]\n\n client.leaveBootloader(address)\n time.sleep(0.2)\n s.reset_input_buffer()\n\n # client.writeRegisters(address, 0x1000, 1, struct.pack('<H', angle_mapping[address]) )\n # client.writeRegisters(address, 0x1002, 1, struct.pack('<B', int(address in needs_flip_phase)) )\n # try:\n # client.writeRegisters(address, 0x1001, 1, struct.pack('<B', 21 if (address in has_21_erevs_per_mrev) else 14))\n # except:\n # print \"WARNING: Motor driver board does not support erevs_per_mrev, try updating the firmware.\"\n\n # Align motor to phase A\n client.writeRegisters(address, 0x2003, 1, struct.pack('<f', PWM_DUTY_CYCLE))\n client.writeRegisters(address, 0x2004, 1, struct.pack('<f', 0))\n client.writeRegisters(address, 0x2005, 1, struct.pack('<f', 0))\n client.writeRegisters(address, 0x2000, 1, struct.pack('<B', 1) ) # Raw PWM control\n\n time.sleep(0.5)\n\n client.writeRegisters(address, 0x2003, 1, struct.pack('<f', 0))\n\n time.sleep(0.5)\n\n reset = struct.unpack('<B', client.readRegisters(address, 0x300b, 1))[0]\n print(\"reset: %u\" % reset)\n success = struct.unpack('<B', client.readRegisters(address, 0x3009, 1))[0]\n print(\"success: %u\" % success)\n\n if success:\n client.writeRegisters(address, 0x2003, 1, struct.pack('<f', PWM_DUTY_CYCLE))\n\n time.sleep(0.2)\n\n client.writeRegisters(address, 0x2003, 1, struct.pack('<f', 0))\n \n l = struct.unpack('<H', client.readRegisters(address, 0x300a, 1))[0]\n while l == 0:\n l = struct.unpack('<H', client.readRegisters(address, 0x300a, 1))[0]\n time.sleep(0.1)\n data = []\n chunk_len = 16\n for i in range(0, int(l/4), chunk_len):\n a = (struct.unpack(\"<{}f\".format(chunk_len), client.readRegisters(address, 0x8000 + i, chunk_len)))\n data += a\n\n supply_voltage = struct.unpack('<f', client.readRegisters(address, 0x3004, 1))[0]\n\n with open('characterize.pkl', 'wb') as file:\n pickle.dump({'data': data, 'supply_voltage': supply_voltage}, file)\n print(\"dumped data to file\")\nelse:\n # Use cached data\n\n with open('characterize.pkl', 'rb') as file:\n obj = pickle.load(file)\n\n if 'data' in obj:\n data = obj['data']\n supply_voltage = obj['supply_voltage']\n else:\n data = obj\n supply_voltage = 23.9\n\nnum_channels = 9\nlength = len(data) // num_channels\n\nia = np.array([data[i * num_channels] for i in range(length)])\nib = np.array([data[i * num_channels + 1] for i in range(length)])\nic = np.array([data[i * num_channels + 2] for i in range(length)])\nva = np.array([data[i * num_channels + 3] for i in range(length)])\nvb = np.array([data[i * num_channels + 4] for i in range(length)])\nvc = np.array([data[i * num_channels + 5] for i in range(length)])\nvin = np.array([data[i * num_channels + 6] for i in range(length)])\nangle = np.array([data[i * num_channels + 7] for i in range(length)])\nvel = np.array([data[i * num_channels + 8] for i in range(length)])\n\ntime = np.arange(length) / 20000\n\n# Combine current measurements from all three channels\ncurrent = (ia - ib - ic) / 2.0\n\n# Find start of step\nstart_index = np.argmax(current >= 0.1 * np.max(current))\n\n# Find approximate end of step\nend_index = np.argmax(current >= 0.95 * np.max(current)) + 100\nif end_index > length:\n end_index = length\n\ndef model_func(x, a, k, b):\n return a * np.exp(-k*x) + b\n\np0 = (-1e10, 1e4, 0.25)\nopt, pcov = curve_fit(model_func, time[start_index:end_index], current[start_index:end_index], p0)\na, k, b = opt\n\nmotor_resistance = supply_voltage * PWM_DUTY_CYCLE / b\nmotor_inductance = motor_resistance / k\n\ndef current_func(y, t0):\n return supply_voltage * PWM_DUTY_CYCLE / motor_inductance - motor_resistance / motor_inductance * y\n\ncurrent_sim = odeint(current_func, current[start_index], time[start_index:end_index])\n\nplt.figure()\nplt.plot(time[start_index:end_index], current[start_index:end_index], label='Measured current')\nplt.plot(time[start_index:end_index], model_func(time[start_index:end_index], a, k, b), label='Fitted current')\nplt.plot(time[start_index:end_index], current_sim, label='Simulated current')\nplt.xlabel('Time (s)')\nplt.ylabel('Current (A)')\nplt.title('Voltage step response')\nplt.legend()\nplt.show()\n\n# Find effective number of bits for the encoder\nencoder_bits = 14\nraw_angle = angle / (2 * np.pi) * 2 ** encoder_bits\nencoder_enob = encoder_bits - np.log2(np.std(raw_angle))\nprint(np.std(raw_angle))\n\n# Find RMS current noise\n# current_noise = np.sqrt(np.mean(np.square(ic[:start_index])))\ncurrent_noise = np.std(ic[:start_index])\n\nprint('Resistance (ohms): {}'.format(motor_resistance))\nprint('Inductance (henries): {}'.format(motor_inductance))\nprint('Encoder ENOB: {}'.format(encoder_enob))\nprint('Current stddev (A): {}'.format(current_noise))\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.title", "numpy.arange", "scipy.integrate.odeint", "matplotlib.pyplot.plot", "numpy.max", "matplotlib.pyplot.ylabel", "numpy.std", "numpy.exp", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "scipy.optimize.curve_fit", "matplotlib.pyplot.figure" ] ]
brandontan99/MVSNet
[ "18bfe23cfa54f8bfe1ac160aadef8a811b9dd94b" ]
[ "mvsnet/test.py" ]
[ "#!/usr/bin/env python\n\"\"\"\nCopyright 2019, Yao Yao, HKUST.\nTest script.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport os\nimport time\nimport sys\nimport math\nimport argparse\nimport numpy as np\n\nimport cv2\nimport tensorflow as tf\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n\nsys.path.append(\"../\")\nfrom tools.common import Notify\nfrom preprocess import *\nfrom model import *\nfrom loss import *\n\n# input path\ntf.app.flags.DEFINE_string('dense_folder', None, \n \"\"\"Root path to dense folder.\"\"\")\ntf.app.flags.DEFINE_string('pretrained_model_ckpt_path', \n '/data/tf_model/3DCNNs/BlendedMVS/blended_augmented/model.ckpt',\n \"\"\"Path to restore the model.\"\"\")\ntf.app.flags.DEFINE_integer('ckpt_step', 150000,\n \"\"\"ckpt step.\"\"\")\n\n# input parameters\ntf.app.flags.DEFINE_integer('view_num', 5,\n \"\"\"Number of images (1 ref image and view_num - 1 view images).\"\"\")\ntf.app.flags.DEFINE_integer('max_d', 256, \n \"\"\"Maximum depth step when testing.\"\"\")\ntf.app.flags.DEFINE_integer('max_w', 1600, \n \"\"\"Maximum image width when testing.\"\"\")\ntf.app.flags.DEFINE_integer('max_h', 1200, \n \"\"\"Maximum image height when testing.\"\"\")\ntf.app.flags.DEFINE_float('sample_scale', 0.25, \n \"\"\"Downsample scale for building cost volume (W and H).\"\"\")\ntf.app.flags.DEFINE_float('interval_scale', 0.8, \n \"\"\"Downsample scale for building cost volume (D).\"\"\")\ntf.app.flags.DEFINE_float('base_image_size', 8, \n \"\"\"Base image size\"\"\")\ntf.app.flags.DEFINE_integer('batch_size', 1, \n \"\"\"Testing batch size.\"\"\")\ntf.app.flags.DEFINE_bool('adaptive_scaling', True, \n \"\"\"Let image size to fit the network, including 'scaling', 'cropping'\"\"\")\n\n# network architecture\ntf.app.flags.DEFINE_string('regularization', 'GRU',\n \"\"\"Regularization method, including '3DCNNs' and 'GRU'\"\"\")\ntf.app.flags.DEFINE_boolean('refinement', False,\n \"\"\"Whether to apply depth map refinement for MVSNet\"\"\")\ntf.app.flags.DEFINE_bool('inverse_depth', True,\n \"\"\"Whether to apply inverse depth for R-MVSNet\"\"\")\n\nFLAGS = tf.app.flags.FLAGS\n\nclass MVSGenerator:\n \"\"\" data generator class, tf only accept generator without param \"\"\"\n def __init__(self, sample_list, view_num):\n self.sample_list = sample_list\n self.view_num = view_num\n self.sample_num = len(sample_list)\n self.counter = 0\n \n def __iter__(self):\n while True:\n for data in self.sample_list: \n \n # read input data\n images = []\n cams = []\n image_index = int(os.path.splitext(os.path.basename(data[0]))[0])\n selected_view_num = int(len(data) / 2)\n\n for view in range(min(self.view_num, selected_view_num)):\n image_file = file_io.FileIO(data[2 * view], mode='r')\n image = scipy.misc.imread(image_file, mode='RGB')\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n cam_file = file_io.FileIO(data[2 * view + 1], mode='r')\n cam = load_cam(cam_file, FLAGS.interval_scale)\n if cam[1][3][2] == 0:\n cam[1][3][2] = FLAGS.max_d\n images.append(image)\n cams.append(cam)\n\n if selected_view_num < self.view_num:\n for view in range(selected_view_num, self.view_num):\n image_file = file_io.FileIO(data[0], mode='r')\n image = scipy.misc.imread(image_file, mode='RGB')\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n cam_file = file_io.FileIO(data[1], mode='r')\n cam = load_cam(cam_file, FLAGS.interval_scale)\n images.append(image)\n cams.append(cam)\n print ('range: ', cams[0][1, 3, 0], cams[0][1, 3, 1], cams[0][1, 3, 2], cams[0][1, 3, 3])\n\n # determine a proper scale to resize input \n resize_scale = 1\n if FLAGS.adaptive_scaling:\n h_scale = 0\n w_scale = 0\n for view in range(self.view_num):\n height_scale = float(FLAGS.max_h) / images[view].shape[0]\n width_scale = float(FLAGS.max_w) / images[view].shape[1]\n if height_scale > h_scale:\n h_scale = height_scale\n if width_scale > w_scale:\n w_scale = width_scale\n if h_scale > 1 or w_scale > 1:\n print (\"max_h, max_w should < W and H!\")\n exit(-1)\n resize_scale = h_scale\n if w_scale > h_scale:\n resize_scale = w_scale\n scaled_input_images, scaled_input_cams = scale_mvs_input(images, cams, scale=resize_scale)\n\n # crop to fit network\n croped_images, croped_cams = crop_mvs_input(scaled_input_images, scaled_input_cams)\n\n # center images\n centered_images = []\n for view in range(self.view_num):\n centered_images.append(center_image(croped_images[view]))\n\n # sample cameras for building cost volume\n real_cams = np.copy(croped_cams) \n scaled_cams = scale_mvs_camera(croped_cams, scale=FLAGS.sample_scale)\n\n print(\"resize_scale:\",resize_scale)\n print(\"croped_images:\",croped_images)\n # return mvs input\n scaled_images = []\n for view in range(self.view_num):\n print(\"croped_images[view]:\",croped_images[view])\n print(\"croped_images[view].shape:\",croped_images[view].shape)\n scaled_images.append(scale_image(croped_images[view], scale=FLAGS.sample_scale))\n scaled_images = np.stack(scaled_images, axis=0)\n croped_images = np.stack(croped_images, axis=0)\n scaled_cams = np.stack(scaled_cams, axis=0)\n self.counter += 1\n yield (scaled_images, centered_images, scaled_cams, image_index) \n\ndef mvsnet_pipeline(mvs_list):\n\n \"\"\" mvsnet in altizure pipeline \"\"\"\n print ('Testing sample number: ', len(mvs_list))\n\n # create output folder\n output_folder = os.path.join(FLAGS.dense_folder, 'depths_mvsnet')\n if not os.path.isdir(output_folder):\n os.mkdir(output_folder)\n\n # testing set\n mvs_generator = iter(MVSGenerator(mvs_list, FLAGS.view_num))\n generator_data_type = (tf.float32, tf.float32, tf.float32, tf.int32) \n mvs_set = tf.data.Dataset.from_generator(lambda: mvs_generator, generator_data_type)\n mvs_set = mvs_set.batch(FLAGS.batch_size)\n mvs_set = mvs_set.prefetch(buffer_size=1)\n\n # data from dataset via iterator\n mvs_iterator = mvs_set.make_initializable_iterator()\n scaled_images, centered_images, scaled_cams, image_index = mvs_iterator.get_next()\n\n # set shapes\n scaled_images.set_shape(tf.TensorShape([None, FLAGS.view_num, None, None, 3]))\n centered_images.set_shape(tf.TensorShape([None, FLAGS.view_num, None, None, 3]))\n scaled_cams.set_shape(tf.TensorShape([None, FLAGS.view_num, 2, 4, 4]))\n depth_start = tf.reshape(\n tf.slice(scaled_cams, [0, 0, 1, 3, 0], [FLAGS.batch_size, 1, 1, 1, 1]), [FLAGS.batch_size])\n depth_interval = tf.reshape(\n tf.slice(scaled_cams, [0, 0, 1, 3, 1], [FLAGS.batch_size, 1, 1, 1, 1]), [FLAGS.batch_size])\n depth_num = tf.cast(\n tf.reshape(tf.slice(scaled_cams, [0, 0, 1, 3, 2], [1, 1, 1, 1, 1]), []), 'int32')\n\n # deal with inverse depth\n if FLAGS.regularization == '3DCNNs' and FLAGS.inverse_depth:\n depth_end = tf.reshape(\n tf.slice(scaled_cams, [0, 0, 1, 3, 3], [FLAGS.batch_size, 1, 1, 1, 1]), [FLAGS.batch_size])\n else:\n depth_end = depth_start + (tf.cast(depth_num, tf.float32) - 1) * depth_interval\n\n # depth map inference using 3DCNNs\n if FLAGS.regularization == '3DCNNs':\n init_depth_map, prob_map = inference_mem(\n centered_images, scaled_cams, FLAGS.max_d, depth_start, depth_interval)\n\n if FLAGS.refinement:\n ref_image = tf.squeeze(tf.slice(centered_images, [0, 0, 0, 0, 0], [-1, 1, -1, -1, 3]), axis=1)\n refined_depth_map = depth_refine(\n init_depth_map, ref_image, FLAGS.max_d, depth_start, depth_interval, True)\n\n # depth map inference using GRU\n elif FLAGS.regularization == 'GRU':\n init_depth_map, prob_map = inference_winner_take_all(centered_images, scaled_cams, \n depth_num, depth_start, depth_end, reg_type='GRU', inverse_depth=FLAGS.inverse_depth)\n\n # init option\n init_op = tf.global_variables_initializer()\n var_init_op = tf.local_variables_initializer()\n\n # GPU grows incrementally\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n\n with tf.Session(config=config) as sess: \n\n # initialization\n sess.run(var_init_op)\n sess.run(init_op)\n total_step = 0\n\n # load model\n if FLAGS.pretrained_model_ckpt_path is not None:\n restorer = tf.train.Saver(tf.global_variables())\n restorer.restore(\n sess, '-'.join([FLAGS.pretrained_model_ckpt_path, str(FLAGS.ckpt_step)]))\n print(Notify.INFO, 'Pre-trained model restored from %s' %\n ('-'.join([FLAGS.pretrained_model_ckpt_path, str(FLAGS.ckpt_step)])), Notify.ENDC)\n total_step = FLAGS.ckpt_step\n \n # run inference for each reference view\n sess.run(mvs_iterator.initializer)\n for step in range(len(mvs_list)):\n\n start_time = time.time()\n try:\n out_init_depth_map, out_prob_map, out_images, out_cams, out_index = sess.run(\n [init_depth_map, prob_map, scaled_images, scaled_cams, image_index])\n except tf.errors.OutOfRangeError:\n print(\"all dense finished\") # ==> \"End of dataset\"\n break\n duration = time.time() - start_time\n print(Notify.INFO, 'depth inference %d finished. (%.3f sec/step)' % (step, duration), \n Notify.ENDC)\n\n # squeeze output\n out_init_depth_image = np.squeeze(out_init_depth_map)\n out_prob_map = np.squeeze(out_prob_map)\n out_ref_image = np.squeeze(out_images)\n out_ref_image = np.squeeze(out_ref_image[0, :, :, :])\n out_ref_cam = np.squeeze(out_cams)\n out_ref_cam = np.squeeze(out_ref_cam[0, :, :, :])\n out_index = np.squeeze(out_index)\n\n # paths\n init_depth_map_path = output_folder + ('/%08d_init.pfm' % out_index)\n prob_map_path = output_folder + ('/%08d_prob.pfm' % out_index)\n out_ref_image_path = output_folder + ('/%08d.jpg' % out_index)\n out_ref_cam_path = output_folder + ('/%08d.txt' % out_index)\n\n # save output\n write_pfm(init_depth_map_path, out_init_depth_image)\n write_pfm(prob_map_path, out_prob_map)\n out_ref_image = cv2.cvtColor(out_ref_image, cv2.COLOR_RGB2BGR)\n image_file = file_io.FileIO(out_ref_image_path, mode='w')\n scipy.misc.imsave(image_file, out_ref_image)\n write_cam(out_ref_cam_path, out_ref_cam)\n total_step += 1\n\n\ndef main(_): # pylint: disable=unused-argument\n \"\"\" program entrance \"\"\"\n # generate input path list\n mvs_list = gen_pipeline_mvs_list(FLAGS.dense_folder)\n # mvsnet inference\n mvsnet_pipeline(mvs_list)\n\n\nif __name__ == '__main__':\n print ('Testing MVSNet with totally %d view inputs (including reference view)' % FLAGS.view_num)\n tf.app.run()" ]
[ [ "numpy.squeeze", "tensorflow.global_variables", "tensorflow.cast", "tensorflow.app.flags.DEFINE_string", "tensorflow.data.Dataset.from_generator", "tensorflow.app.flags.DEFINE_boolean", "tensorflow.app.flags.DEFINE_integer", "numpy.stack", "tensorflow.ConfigProto", "numpy.copy", "tensorflow.Session", "tensorflow.app.run", "tensorflow.TensorShape", "tensorflow.app.flags.DEFINE_bool", "tensorflow.global_variables_initializer", "tensorflow.local_variables_initializer", "tensorflow.slice", "tensorflow.compat.v1.logging.set_verbosity", "tensorflow.app.flags.DEFINE_float" ] ]
TedrosGitHub/TSA-yatsm
[ "8e328f366c8fd94d5cc57cd2cc42080c43d1f391" ]
[ "yatsm/masking.py" ]
[ "from __future__ import division\n\nimport numpy as np\n\nfrom .accel import try_jit\nfrom .regression import robust_fit as rlm\n\nndays = 365.25\n\n\n@try_jit() # np.array prevents nopython\ndef multitemp_mask(x, Y, n_year, crit=400,\n green=1, swir1=4,\n maxiter=10):\n \"\"\" Multi-temporal masking using RLM\n\n Taken directly from CCDC (Zhu and Woodcock, 2014). This \"temporal masking\"\n procedure was ported from CCDC v9.3.\n\n Args:\n x (ndarray): array of ordinal dates\n Y (ndarray): matrix of observed spectra\n n_year (float): \"number of years to mask\"\n crit (float): critical value for masking clouds/shadows\n green (int): 0 indexed value for green band in Y\n (default: 1)\n swir1 (int): 0 indexed value for SWIR (~1.55-1.75um) band\n in Y (default: 4)\n maxiter (int): maximum iterations for RLM fit\n\n Returns:\n mask (np.ndarray): mask where False indicates values to be masked\n\n \"\"\"\n green = Y[green, :]\n swir1 = Y[swir1, :]\n\n n_year = np.ceil(n_year)\n w = 2.0 * np.pi / ndays\n\n X = np.array([np.ones_like(x),\n np.cos(w * x),\n np.sin(w * x),\n np.cos(w / n_year * x),\n np.sin(w / n_year * x)]).T\n\n green_RLM = rlm.RLM(M=rlm.bisquare, maxiter=maxiter).fit(X, green)\n swir1_RLM = rlm.RLM(M=rlm.bisquare, maxiter=maxiter).fit(X, swir1)\n\n mask = ((green - green_RLM.predict(X) < crit) *\n (swir1 - swir1_RLM.predict(X) > -crit))\n\n return mask\n\n\ndef smooth_mask(x, Y, span, crit=400, green=1, swir1=4,\n maxiter=5):\n \"\"\" Multi-temporal masking using LOWESS\n\n Taken directly from newer version of CCDC than Zhu and Woodcock, 2014.\n This \"temporal masking\" replaced the older method which used robust\n linear models. This version uses a regular LOWESS instead of robust\n LOWESS\n\n .. note::\n\n \"span\" argument is the inverse of \"frac\" from statsmodels and is\n actually 'k' in their code:\n\n `n = x.shape[0]`\n `k = int(frac * n + 1e-10)`\n\n .. todo::\n\n We need to put the data on a regular period since span changes as\n is right now. Statsmodels will only allow for dropna, so we would\n need to impute missing data somehow...\n\n Args:\n x (np.ndarray): array of ordinal dates\n Y (np.ndarray): matrix of observed spectra\n span (int): span of LOWESS\n crit (float): critical value for masking clouds/shadows\n green (int): 0 indexed value for green band in Y (default: 1)\n swir1 (int): 0 indexed value for SWIR (~1.55-1.75um) band\n in Y (default: 4)\n maxiter (int): maximum increases to span when checking for\n NaN in LOWESS results\n\n Returns:\n mask (ndarray): mask where False indicates values to be masked\n\n \"\"\"\n from statsmodels.nonparametric import smoothers_lowess\n\n # Reverse span to get frac\n frac = span / x.shape[0]\n # Estimate delta as \"good choice\": delta = 0.01 * range(exog)\n delta = (x.max() - x.min()) * 0.01\n\n # Run LOWESS checking for NaN in output\n i = 0\n green_lowess, swir1_lowess = np.nan, np.nan\n while (np.any(np.isnan(green_lowess)) or\n np.any(np.isnan(swir1_lowess))) and i < maxiter:\n green_lowess = smoothers_lowess.lowess(Y[green, :], x,\n frac=frac, delta=delta)\n swir1_lowess = smoothers_lowess.lowess(Y[swir1, :], x,\n frac=frac, delta=delta)\n span += 1\n frac = span / x.shape[0]\n i += 1\n\n mask = (((Y[green, :] - green_lowess[:, 1]) < crit) *\n ((Y[swir1, :] - swir1_lowess[:, 1]) > -crit))\n\n return mask\n" ]
[ [ "numpy.ones_like", "numpy.isnan", "numpy.cos", "numpy.sin", "numpy.ceil" ] ]
harrow/computational_QM
[ "d8a2060bee6a55c4b8bf937ad96feed10227373b" ]
[ "2_tensor_networks/a_mps.py" ]
[ "\"\"\"Toy code implementing a matrix product state.\"\"\"\n\nimport numpy as np\nfrom scipy.linalg import svd\n\n\nclass MPS:\n \"\"\"Class for a matrix product state.\n\n We index sites with `i` from 0 to L-1; bond `i` is left of site `i`.\n We *assume* that the state is in right-canonical form.\n\n Parameters\n ----------\n Bs, Ss:\n Same as attributes.\n\n Attributes\n ----------\n Bs : list of np.Array[ndim=3]\n The 'matrices' in right-canonical form, one for each physical site.\n Each `B[i]` has legs (virtual left, physical, virtual right), in short ``vL i vR``\n Ss : list of np.Array[ndim=1]\n The Schmidt values at each of the bonds, ``Ss[i]`` is left of ``Bs[i]``.\n L : int\n Number of sites.\n \"\"\"\n\n def __init__(self, Bs, Ss):\n self.Bs = Bs\n self.Ss = Ss\n self.L = len(Bs)\n\n def copy(self):\n return MPS([B.copy() for B in self.Bs], [S.copy() for S in self.Ss])\n\n def get_theta1(self, i):\n \"\"\"Calculate effective single-site wave function on sites i in mixed canonical form.\n\n The returned array has legs ``vL, i, vR`` (as one of the Bs).\"\"\"\n return np.tensordot(np.diag(self.Ss[i]), self.Bs[i], [1, 0]) # vL [vL'], [vL] i vR\n\n def get_theta2(self, i):\n \"\"\"Calculate effective two-site wave function on sites i,j=(i+1) in mixed canonical form.\n\n The returned array has legs ``vL, i, j, vR``.\"\"\"\n j = i + 1\n return np.tensordot(self.get_theta1(i), self.Bs[j], [2, 0]) # vL i [vR], [vL] j vR\n\n def get_chi(self):\n \"\"\"Return bond dimensions.\"\"\"\n return [self.Bs[i].shape[2] for i in range(self.L - 1)]\n\n def site_expectation_value(self, op):\n \"\"\"Calculate expectation values of a local operator at each site.\"\"\"\n result = []\n for i in range(self.L):\n theta = self.get_theta1(i) # vL i vR\n op_theta = np.tensordot(op, theta, axes=[1, 1]) # i [i*], vL [i] vR\n result.append(np.tensordot(theta.conj(), op_theta, [[0, 1, 2], [1, 0, 2]]))\n # [vL*] [i*] [vR*], [i] [vL] [vR]\n return np.real_if_close(result)\n\n def bond_expectation_value(self, op):\n \"\"\"Calculate expectation values of a local operator at each bond.\"\"\"\n result = []\n for i in range(self.L - 1):\n theta = self.get_theta2(i) # vL i j vR\n op_theta = np.tensordot(op[i], theta, axes=[[2, 3], [1, 2]])\n # i j [i*] [j*], vL [i] [j] vR\n result.append(np.tensordot(theta.conj(), op_theta, [[0, 1, 2, 3], [2, 0, 1, 3]]))\n # [vL*] [i*] [j*] [vR*], [i] [j] [vL] [vR]\n return np.real_if_close(result)\n\n def entanglement_entropy(self):\n \"\"\"Return the (von-Neumann) entanglement entropy for a bipartition at any of the bonds.\"\"\"\n result = []\n for i in range(1, self.L):\n S = self.Ss[i].copy()\n S[S < 1.e-20] = 0. # 0*log(0) should give 0; avoid warning or NaN.\n S2 = S * S\n assert abs(np.linalg.norm(S) - 1.) < 1.e-14\n result.append(-np.sum(S2 * np.log(S2)))\n return np.array(result)\n\n\ndef init_spinup_MPS(L):\n \"\"\"Return a product state with all spins up as an MPS\"\"\"\n B = np.zeros([1, 2, 1], np.float)\n B[0, 0, 0] = 1.\n S = np.ones([1], np.float)\n Bs = [B.copy() for i in range(L)]\n Ss = [S.copy() for i in range(L)]\n return MPS(Bs, Ss)\n\n\ndef split_truncate_theta(theta, chi_max, eps):\n \"\"\"Split and truncate a two-site wave function in mixed canonical form.\n\n Split a two-site wave function as follows::\n vL --(theta)-- vR => vL --(A)--diag(S)--(B)-- vR\n | | | |\n i j i j\n\n Afterwards, truncate in the new leg (labeled ``vC``).\n\n Parameters\n ----------\n theta : np.Array[ndim=4]\n Two-site wave function in mixed canonical form, with legs ``vL, i, j, vR``.\n chi_max : int\n Maximum number of singular values to keep\n eps : float\n Discard any singular values smaller than that.\n\n Returns\n -------\n A : np.Array[ndim=3]\n Left-canonical matrix on site i, with legs ``vL, i, vC``\n S : np.Array[ndim=1]\n Singular/Schmidt values.\n B : np.Array[ndim=3]\n Right-canonical matrix on site j, with legs ``vC, j, vR``\n \"\"\"\n chivL, dL, dR, chivR = theta.shape\n theta = np.reshape(theta, [chivL * dL, dR * chivR])\n X, Y, Z = svd(theta, full_matrices=False)\n # truncate\n chivC = min(chi_max, np.sum(Y > eps))\n assert chivC >= 1\n piv = np.argsort(Y)[::-1][:chivC] # keep the largest `chivC` singular values\n X, Y, Z = X[:, piv], Y[piv], Z[piv, :]\n # renormalize\n S = Y / np.linalg.norm(Y) # == Y/sqrt(sum(Y**2))\n # split legs of X and Z\n A = np.reshape(X, [chivL, dL, chivC])\n B = np.reshape(Z, [chivC, dR, chivR])\n return A, S, B\n" ]
[ [ "numpy.diag", "numpy.real_if_close", "numpy.log", "scipy.linalg.svd", "numpy.reshape", "numpy.linalg.norm", "numpy.ones", "numpy.tensordot", "numpy.argsort", "numpy.array", "numpy.zeros", "numpy.sum" ] ]
CMLPlatform/pysuttoio
[ "4d0c2de6c7d6d90e9caf4b5b361e5046828bf113" ]
[ "pySUTtoIO/transformation_model_b.py" ]
[ "import math\nimport numpy as np\nimport os.path\nimport pySUTtoIO.tools as tl\nimport pySUTtoIO.sut as st\nfrom pySUTtoIO.secondary_flows import make_secondary as ms\n\n\nclass TransformationModelB:\n \"\"\"A supply-use table to input-output table transformation object.\n From the supply-use table a product-by-product input-output table\n based on industry technology assumption is created. In the 'Eurostat Manual\n of Supply, Use and Input-Output Tables' this transformation model is called\n model B. The resulting input-output table does not contain negative values.\n Onlythe domestic tables are taken into consideration\"\"\"\n\n default_rel_tol = 1E-3\n debug = False\n debug_data_dir = os.path.join('data', 'transformed', '2010', 'sut')\n\n def __init__(self, sut, make_secondary):\n assert type(sut) is st.Sut\n self._sut = sut\n if make_secondary:\n sut2 = ms(sut)\n self.V = sut2.supply\n self.U = sut2.use\n self.q = np.sum(self.V, axis=1)\n self.Y = sut2.final_use\n else:\n self.V = self._sut.supply\n self.U = self._sut.use\n self.q = self._sut.total_product_supply\n self.Y = self._sut.final_use\n\n if self.debug:\n product_out = np.sum(self.V, axis=1, keepdims=True)\n product_in = np.sum(self.U, axis=1, keepdims=True) + np.sum(self.Y, axis=1, keepdims=True)\n industry_out = np.sum(self.V, axis=0, keepdims=True)\n industry_in = np.sum(self.U, axis=0, keepdims=True) + np.sum(self._sut.value_added, axis=0, keepdims=True)\n\n full_supply_fn = os.path.join(self.debug_data_dir,'supply_transformed_new.txt')\n full_use_fn = os.path.join(self.debug_data_dir, 'use_transformed_new.txt')\n full_finaldemand_fn = os.path.join(self.debug_data_dir, 'finaldemand_transformed_new.txt')\n full_value_added_fn = os.path.join(self.debug_data_dir, 'value_added_transformed_new.txt')\n full_prd_supply_fn = os.path.join(self.debug_data_dir, 'product_supply_new.txt')\n full_prd_use_fn = os.path.join(self.debug_data_dir, 'product_use_new.txt')\n full_ind_input_fn = os.path.join(self.debug_data_dir, 'industry_input_new.txt')\n full_ind_output_fn = os.path.join(self.debug_data_dir, 'industry_output_new.txt')\n\n tl.list_to_csv_file(full_supply_fn, self.V, '\\t')\n tl.list_to_csv_file(full_use_fn, self.U, '\\t')\n tl.list_to_csv_file(full_finaldemand_fn, self.Y, '\\t')\n tl.list_to_csv_file(full_value_added_fn, self._sut.value_added, '\\t') # notice value added not touched\n tl.list_to_csv_file(full_prd_supply_fn, product_out, '\\t')\n tl.list_to_csv_file(full_prd_use_fn, product_in, '\\t')\n tl.list_to_csv_file(full_ind_output_fn, np.transpose(industry_out), '\\t')\n tl.list_to_csv_file(full_ind_input_fn, np.transpose(industry_in), '\\t')\n\n def transformation_matrix(self):\n make = np.transpose(self.V)\n g = np.sum(self.V, axis=0)\n return np.dot(tl.invdiag(g), make)\n\n def io_transaction_matrix(self):\n use = self.U\n transaction_matrix = np.dot(use, self.transformation_matrix())\n\n if self.debug:\n full_transaction_output_fn = os.path.join(self.debug_data_dir, 'transaction_output_new.txt')\n tl.list_to_csv_file(full_transaction_output_fn, np.sum(transaction_matrix, axis=1, keepdims=True), '\\t')\n print('transaction matrix ready and saved')\n print('transaction matrix ready')\n return transaction_matrix\n\n def io_coefficient_matrix(self):\n q = self.q\n return np.dot(self.io_transaction_matrix(), tl.invdiag(q))\n\n def ext_transaction_matrix(self):\n return np.dot(self._sut.extensions, self.transformation_matrix())\n\n def ext_coefficients_matrix(self):\n q = self.q\n return np.dot(self.ext_transaction_matrix(), tl.invdiag(q))\n\n def factor_inputs_transaction_matrix(self):\n return np.dot(self._sut.factor_inputs, self.transformation_matrix())\n\n def factor_inputs_coefficients_matrix(self):\n q = self.q\n return np.dot(self.factor_inputs_transaction_matrix(), tl.invdiag(q))\n\n def final_demand(self, fd=None):\n if fd is None:\n fd = self.Y\n return fd\n\n def io_total_requirement_matrix(self):\n A = self.io_coefficient_matrix()\n identity = np.identity(len(A))\n A = np.nan_to_num(A)\n return np.linalg.inv(identity - A)\n\n def check_io_transaction_matrix(self, rel_tol=default_rel_tol):\n is_correct = True\n q1 = np.sum(self.io_transaction_matrix(), axis=1) + \\\n np.sum(self.Y, axis=1)\n q2 = np.sum(self.U, axis=1) + \\\n np.sum(self.Y, axis=1)\n it = np.nditer(q1, flags=['f_index'])\n while not it.finished and is_correct:\n if not math.isclose(q1[it.index], q2[it.index], rel_tol=rel_tol):\n print(q1[it.index]- q2[it.index])\n is_correct = False\n it.iternext()\n return is_correct\n\n def check_io_coefficients_matrix(self, rel_tol=default_rel_tol):\n is_correct = True\n q1 = np.sum(self.io_transaction_matrix(), axis=1) + \\\n np.sum(self.Y, axis=1)\n (row_cnt, col_cnt) = self.U.shape\n eye = np.diag(np.ones(row_cnt))\n l_inverse = np.linalg.inv(eye - self.io_coefficient_matrix())\n fd = np.sum(self.Y, axis=1)\n q2 = np.dot(l_inverse, fd)\n it = np.nditer(q1, flags=['f_index'])\n while not it.finished and is_correct:\n if not math.isclose(q1[it.index], q2[it.index], rel_tol=rel_tol):\n is_correct = False\n it.iternext()\n return is_correct\n\n def check_ext_transaction_matrix(self, rel_tol=default_rel_tol):\n is_correct = True\n e1 = np.sum(self._sut.extensions, axis=1)\n e2 = np.sum(self.ext_transaction_matrix(), axis=1)\n it = np.nditer(e1, flags=['f_index'])\n while not it.finished and is_correct:\n if not math.isclose(e1[it.index], e2[it.index], rel_tol=rel_tol):\n is_correct = False\n it.iternext()\n return is_correct\n\n def check_ext_coefficient_matrix(self, rel_tol=default_rel_tol):\n is_correct = True\n e1 = np.sum(self._sut.extensions, axis=1)\n ext = self.ext_coefficients_matrix()\n (row_cnt, col_cnt) = self.U.shape\n eye = np.diag(np.ones(row_cnt))\n l_inverse = np.linalg.inv(eye - self.io_coefficient_matrix())\n fd = np.sum(self.Y, axis=1)\n e2 = np.dot(ext, np.dot(l_inverse, fd))\n it = np.nditer(e1, flags=['f_index'])\n while not it.finished and is_correct:\n if not math.isclose(e1[it.index], e2[it.index], rel_tol=rel_tol):\n is_correct = False\n it.iternext()\n return is_correct\n" ]
[ [ "numpy.dot", "numpy.nditer", "numpy.linalg.inv", "numpy.nan_to_num", "numpy.ones", "numpy.transpose", "numpy.sum" ] ]
7starsea/shark
[ "5030f576da6f5998728d80170480e68a3debfe79" ]
[ "shark/trainer/trainer_base.py" ]
[ "# coding=utf-8\nimport os.path\nimport torch\nimport numpy as np\nfrom abc import ABC, abstractmethod\n\nfrom torch.utils.tensorboard import SummaryWriter\nfrom shark.replay import ReplayBufferBase, SimpleReplayBuffer\n\n\nclass RLConfig(object):\n def __init__(self, batch_size=256):\n self.batch_size = batch_size\n self.init_learn_size = batch_size * 4\n\n # # buffer related parameter\n self.capacity = 100000\n self.buffer = SimpleReplayBuffer\n self.buffer_kwargs = dict()\n\n self.double_q = True\n self.exploration = None\n\n self.processes = 6\n self.forward_step = 10\n\n self.gamma = 0.99 # # discount rate\n self.updates = 200\n self.updates_tau = 1\n self.learning_rate = 0.0001\n\n\nclass BaseTrainer(ABC):\n def __init__(self, config, train_env, test_env, policy, device, is_train=True, log_dir='logs', param_dir='params'):\n assert isinstance(config, RLConfig)\n # assert isinstance(policy, BasePolicy)\n self.config = config\n self.env = train_env\n self.test_env = test_env\n self.policy = policy\n self.device = device\n\n self.buffer = None\n tran_cls = self.policy.replay_transition()\n if issubclass(tran_cls, tuple):\n assert issubclass(config.buffer, ReplayBufferBase) and \"config.buffer is not a subclass of ReplayBufferBase\"\n self.buffer = config.buffer(tran_cls, config.capacity, config.batch_size, **config.buffer_kwargs)\n\n self._param_dir = param_dir\n self.logger = None\n if is_train:\n assert os.path.isdir(self._param_dir) and \"Invalid param_dir!\"\n from datetime import datetime\n assert os.path.isdir(log_dir) and \"Invalid log_dir!\"\n tod = datetime.today().strftime('%m-%dT%H:%M')\n log_file = '%s_%s_%s' % (self.env.spec.id, self.policy.name, tod)\n self.logger = SummaryWriter(os.path.join(log_dir, log_file))\n\n def __del__(self):\n try:\n if self.logger:\n self.logger.close()\n except:\n pass\n\n def load_param(self, param_file):\n self.policy.load_param(param_file)\n self.policy.sync_target()\n\n def save_param(self, frame_idx=0):\n from datetime import datetime\n tod = datetime.today().strftime('%m%dT%H%M')\n param_file = '%s_%s_%s_%d.bin' % (self.env.spec.id, self.policy.name, tod, frame_idx)\n self.policy.save_param(os.path.join(self._param_dir, param_file))\n\n def test(self, num_episode=1):\n total_rewards = 0\n env = self.test_env\n with torch.no_grad():\n for i in range(num_episode):\n\n s = env.reset()\n episode_r = 0\n while True:\n a = self.policy.actor(s)\n next_s, r, done, info = env.step(a.cpu().numpy())\n s = next_s\n\n env.render()\n\n episode_r += r[0]\n ind = torch.where(done > .5)[0]\n if len(ind) > 0:\n break\n print('Episode %d Reward %.2f' % (i + 1, episode_r))\n total_rewards += episode_r\n print('Total Reward %.2f' % total_rewards)\n\n @abstractmethod\n def train(self, num_frames=100000, checkpoints=10):\n pass\n" ]
[ [ "torch.no_grad", "torch.where" ] ]
kemfic/SimpleVO
[ "4dffad27c47ca8a20bbc4dea75128b0f45c94d61" ]
[ "utils.py" ]
[ "# Utility functions\nimport cv2\nimport numpy as np\nimport quaternion\nfrom params import param\n\ndef bgr2gray(img):\n return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\ndef getCorners(img, params=param.get(\"gftt\")):\n \"\"\"\n - Example from: https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_shi_tomasi/py_shi_tomasi.html\n \n - API Ref: https://docs.opencv.org/master/dd/d1a/group__imgproc__feature.html#ga1d6bb77486c8f92d79c8793ad995d541\n \"\"\"\n gray = bgr2gray(img)\n corners = cv2.goodFeaturesToTrack(gray, **params)\n corners = np.int0(corners)\n return corners\n\ndef get_features_orb(img, corners):\n '''\n Computes ORB descriptors and coords for an image\n '''\n\n kp = [cv2.KeyPoint(x=f[0][0], y=f[0][1], _size=15) for f in corners]\n\n orb = cv2.ORB_create()\n kps, des = orb.compute(img, kp)\n\n # Convert Keypoint to coord\n coords = np.array([kp.pt for kp in kps])\n \n return coords, des\n\ndef match_frames(des1, des2, pt1, pt2):\n '''\n Matches features using K-Nearest Neighbors, and returns the indexes of the matches\n '''\n\n kp1 = coords_to_kp(pt1)\n kp2 = coords_to_kp(pt2)\n bf = cv2.BFMatcher(cv2.NORM_HAMMING)\n matches = bf.knnMatch(des1, des2, k=2)\n\n # Lowe's Ratio Test\n good = []\n des_idxs = []\n for m, n in matches:\n if m.distance < 32 and (m.distance < 0.75*n.distance and 5 < np.linalg.norm(np.subtract(kp2[m.trainIdx].pt, kp1[m.queryIdx].pt)) < 300): #m.distance < 32\n good.append(m.trainIdx)\n des_idxs.append((m.queryIdx, m.trainIdx))\n\n des_idxs = np.array(des_idxs)\n\n return des_idxs\n\ndef coords_to_kp(coords):\n return [cv2.KeyPoint(x=f[0][0], y=f[0][1], _size=15) for f in coords]\n\ndef getTransform(cur_pose, prev_pose):\n \"\"\"\n Computes the error of the transformation between 2 poses\n \"\"\"\n Rt = np.eye(4)\n Rt[:3,:3] = cur_pose[:3,:3].T @ prev_pose[:3, :3]\n Rt[:3, -1] = cur_pose[:3, :3].T @ (cur_pose[:3,-1] - prev_pose[:3, -1])\n return Rt\n\ndef getError(cur_pose, prev_pose, cur_gt, prev_gt):\n \"\"\"\n Computes the error of the transformation between 2 poses\n \"\"\"\n error_t = np.linalg.norm((prev_pose[:3, -1] - cur_pose[:3,-1]) - (cur_gt[:3,-1] - prev_gt[:3,-1]))\n \n gt_prev_qt = quaternion.from_rotation_matrix(prev_gt[:3, :3])\n gt_qt = quaternion.from_rotation_matrix(cur_gt[:3, :3])\n gt_tform = gt_prev_qt * gt_qt.inverse()\n \n cur_qt = quaternion.from_rotation_matrix(prev_pose[:3, :3])\n prev_qt = quaternion.from_rotation_matrix(cur_pose[:3, :3])\n\n qt_tform = prev_qt * cur_qt.inverse()\n\n error_r = np.sum(np.rad2deg(quaternion.rotation_intrinsic_distance(gt_tform, qt_tform)))\n\n return error_r, error_t\n\ndef roll_rot3d(theta):\n cos = np.cos(theta)\n sin = np.sin(theta)\n R_x = np.array([[1, 0, 0],\n [0,cos, -sin],\n [0,sin,cos]])\n return R_x\ndef pitch_rot3d(theta):\n cos = np.cos(theta)\n sin = np.sin(theta)\n R_y = np.array([[cos, 0, sin],\n [0, 1, 0],\n [-sin,0,cos]])\n return R_y\n\ndef yaw_rot3d(theta):\n cos = np.cos(theta)\n sin = np.sin(theta)\n R_z = np.array([[cos, -sin, 0],\n [sin, cos, 0],\n [0, 0, 1]])\n return R_z\n\ndef euler2rot3d(angles):\n \"\"\"\n x -> pitch\n y -> yaw\n z -> roll\n \"\"\"\n return yaw_rot3d(angles[1]) @ pitch_rot3d(angles[0]) @ roll_rot3d(angles[2])\n\n# https://www.learnopencv.com/rotation-matrix-to-euler-angles/\n# Checks if a matrix is a valid rotation matrix.\ndef isRMatrix(R) :\n Rt = np.transpose(R)\n shouldBeIdentity = np.dot(Rt, R)\n I = np.identity(3, dtype = R.dtype)\n n = np.linalg.norm(I - shouldBeIdentity)\n return n < 1e-6\n \n \n# Calculates rotation matrix to euler angles\n# The result is the same as MATLAB except the order\n# of the euler angles ( x and z are swapped ).\ndef rot2euler(R) :\n \n assert(isRMatrix(R))\n \n sy = np.sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0])\n\n \n singular = sy < 1e-6\n \n if not singular :\n x = np.arctan2(R[2,1] , R[2,2])\n y = np.arctan2(-R[2,0], sy)\n z = np.arctan2(R[1,0], R[0,0])\n else :\n x = np.arctan2(-R[1,2], R[1,1])\n y = np.arctan2(-R[2,0], sy)\n z = 0\n \n return np.array([x, y, z])\n" ]
[ [ "numpy.int0", "numpy.dot", "numpy.sqrt", "numpy.eye", "numpy.subtract", "numpy.cos", "numpy.linalg.norm", "numpy.sin", "numpy.arctan2", "numpy.identity", "numpy.transpose", "numpy.array" ] ]
rmarcacini/cc-meli2019
[ "57139212b0afce5ada550c903516e5b919347b7b" ]
[ "meli/sampling.py" ]
[ "from tqdm import tqdm\nimport pandas as pd\n\n\ndef balanced_sampling(df, num_instances=500):\n\n\n L = []\n counter = 1\n categories = df['category'].unique()\n for category in tqdm(categories):\n sample = df[df.category==category]\n try:\n sample_reliable = sample[sample.label_quality=='reliable'].sample(num_instances,replace=True)\n L.append(sample_reliable)\n except:\n x=1\n\n sample_unreliable = sample[sample.label_quality=='unreliable'].sample(num_instances,replace=True)\n L.append(sample_unreliable)\n counter+=1\n\n\n return pd.concat(L)\n\n\ndef unbalanced_sampling(df, num_instances=1000000):\n\n\n num_classes = len(df['category'].unique())\n \n while True:\n sample = df.sample(num_instances)\n if len(sample['category'].unique()) == num_classes:\n return sample\n \n " ]
[ [ "pandas.concat" ] ]
cheonbok94/Pytorch-Latent-Constraints-Learning-to-Generate-Conditionally-from-Unconditional-Generative-Models
[ "0dbd182b294e0c6d3ad0deda3be1dd855fd57617" ]
[ "main.py" ]
[ "import argparse \r\nimport numpy \r\nfrom model.trainer import Trainer,AC_Trainer \r\nfrom model.loss import loss_function,celeba_loss\r\n\r\n\r\nfrom model.vae import Mnist_VAE,Celeba_VAE\r\nfrom utils.get_data import MNIST_DATA ,Celeba_DATA\r\nfrom model.model import Actor,Critic\r\nimport torch\r\n\r\ndef main():\r\n\tparser = argparse.ArgumentParser()\r\n\t\r\n\tparser.add_argument('--gpu_num', type = int, default = None)\r\n\tparser.add_argument('--data',type =str,required=True)\r\n\tparser.add_argument('--num_epoch',type=int,default =50)\r\n\tparser.add_argument('--batch_size',type=int,default =128)\r\n\tparser.add_argument('--tensorboard_dirs',type=str,default ='./run')\r\n\tparser.add_argument('--train_id',type=str , default = 'my_model')\r\n\tparser.add_argument('--gpu_accelerate',action='store_true')\r\n\tparser.add_argument('--image_dir',type = str , default = './data/CelebA_nocrop/images')\r\n\tparser.add_argument('--attr_path',type = str ,default = './data/list_attr_celeba.txt')\r\n\tparser.add_argument('--distance_penalty',type=float, default = 0.1)\r\n\tparser.add_argument('--vae_mode',action = 'store_true')\r\n\tparser.add_argument('--save_model',type=str,default = './')\r\n\tparser_config = parser.parse_args()\r\n\tprint (parser_config)\r\n\tif parser_config.gpu_num is not None :\r\n\t\ttorch.cuda.set_device(parser_config.gpu_num)\r\n\r\n\tif parser_config.gpu_accelerate:\r\n\t\ttorch.backends.cudnn.benchmark = True\r\n\tif parser_config.gpu_num == -1:\r\n\t\tdevice = 'cpu'\r\n\telse:\r\n\t\tdevice = parser_config.gpu_num\r\n\tif parser_config.vae_mode:\r\n\r\n\t\tif parser_config.data == 'MNIST':\r\n\t\t\ttrainDset,testDset,trainDataLoader,testDataLoader= MNIST_DATA(batch_size = parser_config.batch_size )\r\n\t\t\tmodel = Mnist_VAE(input_dim= 28*28 ,layer_num= 4, d_model=1024)\r\n\t\t\ttrainer = Trainer(model=model,\r\n\t\t\t\t\t\t\tloss = loss_function,\r\n\t\t\t\t\t\t\tdata = parser_config.data,\r\n\t\t\t\t\t\t\tepoch = parser_config.num_epoch,\r\n\t\t\t\t\t\t\ttrainDataLoader=trainDataLoader,\r\n\t\t\t\t\t\t\ttestDataLoader=testDataLoader)\r\n\r\n\t\telif parser_config.data == 'celeba':\r\n\t\t\ttrainDset,testDset,trainDataLoader,testDataLoader = Celeba_DATA(celeba_img_dir=parser_config.image_dir ,attr_path=parser_config.attr_path,batch_size = parser_config.batch_size,image_size=64,celeba_crop_size=128)\r\n\t\t\tmodel = Celeba_VAE(128,d_model=1024,layer_num=3)\r\n\t\t\ttrainer = Trainer(model=model,\r\n\t\t\t\t\t\t\tloss = celeba_loss,\r\n\t\t\t\t\t\t\tdata = parser_config.data,\r\n\t\t\t\t\t\t\tepoch = parser_config.num_epoch,\r\n\t\t\t\t\t\t\ttrainDataLoader=trainDataLoader,\r\n\t\t\t\t\t\t\ttestDataLoader=testDataLoader)\r\n\r\n\t\telse:\r\n\t\t\traise NotImplementedError\r\n\telse:\r\n\t\tif parser_config.data == 'MNIST':\r\n\t\t\ttrainDset,testDset,trainDataLoader,testDataLoader = MNIST_DATA(batch_size = parser_config.batch_size )\r\n\t\t\tmodel = Mnist_VAE(input_dim= 28*28 ,layer_num= 4, d_model=1024)\r\n\t\t\tactor = Actor(1024,2048)\r\n\t\t\treal_critic = Critic(1024,2048,num_labels=10,condition_mode =True)\r\n\t\t\tattr_critic = Critic(1024,2048,num_labels=10,num_output=10,condition_mode =False)\r\n\t\t\tactrainer = AC_Trainer(vae_model=model,\r\n\t\t\t\t\t\t\tactor = actor,\r\n\t\t\t\t\t\t\treal_critic = real_critic,\r\n\t\t\t\t\t\t\tattr_critic = attr_critic,\r\n\t\t\t\t\t\t\tepoch = parser_config.num_epoch,\r\n\t\t\t\t\t\t\tdata = parser_config.data,\r\n\t\t\t\t\t\t\ttrainDataLoader=trainDataLoader,\r\n\t\t\t\t\t\t\ttestDataLoader=testDataLoader)\r\n\t\t\tactrainer.load_vae('./save_model/vae_model50_MNIST.path.tar')\r\n\t\t\tactrainer._set_label_type()\r\n\t\tif parser_config.data == 'celeba':\r\n\t\t\tselected_attrs = ['Bald','Black_Hair','Blond_Hair','Brown_Hair','Eyeglasses','Male','No_Beard','Smiling','Wearing_Hat','Young']\r\n\t\t\ttrainDset,testDset,trainDataLoader,testDataLoader = Celeba_DATA(celeba_img_dir=parser_config.image_dir ,attr_path=parser_config.attr_path,selected_attrs=selected_attrs,batch_size = parser_config.batch_size,image_size=64,celeba_crop_size=128)\r\n\t\t\tmodel = Celeba_VAE(128,d_model=1024,layer_num=3)\r\n\t\t\tactor = Actor(1024,2048)\r\n\t\t\treal_critic = Critic(1024,2048,num_labels=10,condition_mode =True)\r\n\t\t\tattr_critic = Critic(1024,2048,num_labels=10,num_output=10,condition_mode =False)\r\n\t\t\tactrainer = AC_Trainer(vae_model=model,\r\n\t\t\t\t\t\t\tactor = actor,\r\n\t\t\t\t\t\t\treal_critic = real_critic,\r\n\t\t\t\t\t\t\tattr_critic = attr_critic,\r\n\t\t\t\t\t\t\tepoch = parser_config.num_epoch,\r\n\t\t\t\t\t\t\tdata = parser_config.data,\r\n\t\t\t\t\t\t\ttrainDataLoader=trainDataLoader,\r\n\t\t\t\t\t\t\ttestDataLoader=testDataLoader)\r\n\t\t\tactrainer.load_vae('./save_model/vae_model150_celeba.path.tar')\r\n\r\n\r\n\tprint (\"[+] Train model start\")\r\n\tif parser_config.vae_mode:\r\n\t\ttrainer.train()\r\n\telse:\r\n\t\tactrainer.train()\r\n\r\nif __name__ == '__main__':\r\n\tmain()" ]
[ [ "torch.cuda.set_device" ] ]
ericosmic/2019-CCF-BDCI-OCR-MCZJ-OCR-IdentificationIDElement
[ "54417d43d71af37588f3a8141aa34d151e5b7884" ]
[ "recognize_process/tools/mytest_crnn.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 19-11-19 23:45\n# @Author : Miao Wenqiang\n# @Reference : https://github.com/MaybeShewill-CV/CRNN_Tensorflow\n# https://github.com/bai-shang/crnn_ctc_ocr.Tensorflow\n# @File : test_crnn.py\n# @IDE : PyCharm Community Edition\n\"\"\"\n识别图片中的文本。需要的参数有:\n 1.图片所在路径。\n 2.保存有图片名称的txt文件\n 3.加载模型的路径\n\n输出结果为:\n 识别结果\n\"\"\"\nimport argparse\nimport os\nimport time\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nimport json\n\nimport sys\n#sys.path.append('./')\n#print(sys.path)\n\nfrom recognize_process.config import model_config\nfrom recognize_process.crnn_model import crnn_model\n\nCFG = model_config.cfg\n\n\ndef init_args():\n \"\"\"\n 初始化参数\n :return: None\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--image_path', type=str,\n help='Path to the image to be tested',\n # default='./recognize_process/test_imgs/')\n default='./test_imgs/')\n parser.add_argument('-w', '--weights_path', type=str,\n help='Path to the pre-trained weights to use',\n # default='./recognize_process/model_save/recognize_model')\n default='./recognize_model')\n parser.add_argument('-c', '--char_dict_path', type=str,\n help='Directory where character dictionaries for the dataset were stored',\n # default='./recognize_process/char_map/char_map.json')\n default='./char_map/char_map.json')\n parser.add_argument('-t', '--txt_path', type=str,\n help='Whether to display images',\n # default='./recognize_process/img_list.txt')\n default='./img_list.txt')\n\n return parser.parse_args()\n\n\ndef _resize_image(img):\n \"\"\"\n 用于将图片resize为固定高度(32)\n :param img: 输入图片\n :return: resize为固定高度的图片\n \"\"\"\n dst_height = CFG.ARCH.INPUT_SIZE[1]\n h_old, w_old, _ = img.shape\n height = dst_height\n width = int(w_old * height / h_old)\n resized_img = cv2.resize(img, (width, height), interpolation=cv2.INTER_CUBIC)\n\n return resized_img\n\n\ndef _sparse_matrix_to_list(sparse_matrix, char_map_dict_path=None):\n \"\"\"\n 将矩阵拆分为list,参考:https://github.com/bai-shang/crnn_ctc_ocr.Tensorflow\n :param sparse_matrix:\n :param char_map_dict_path:\n :return:\n \"\"\"\n indices = sparse_matrix.indices\n values = sparse_matrix.values\n dense_shape = sparse_matrix.dense_shape\n\n # the last index in sparse_matrix is ctc blanck note\n char_map_dict = json.load(open(char_map_dict_path, 'r', encoding='UTF-8'))\n if char_map_dict is None:\n print(\"error\")\n assert (isinstance(char_map_dict, dict) and 'char_map_dict is not a dict')\n\n dense_matrix = len(char_map_dict.keys()) * np.ones(dense_shape, dtype=np.int32)\n for i, indice in enumerate(indices):\n dense_matrix[indice[0], indice[1]] = values[i]\n string_list = []\n for row in dense_matrix:\n string = []\n for val in row:\n string.append(_int_to_string(val, char_map_dict))\n string_list.append(''.join(s for s in string if s != '*'))\n return string_list\n\n\ndef _int_to_string(value, char_map_dict=None):\n \"\"\"\n 将识别结果转化为string,参考:https://github.com/bai-shang/crnn_ctc_ocr.Tensorflow\n :param value:\n :param char_map_dict:\n :return:\n \"\"\"\n if char_map_dict is None:\n print(\"error\")\n #char_map_dict = json.load(open(FLAGS.char_map_json_file, 'r'))\n assert (isinstance(char_map_dict, dict) and 'char_map_dict is not a dict')\n\n for key in char_map_dict.keys():\n if char_map_dict[key] == int(value):\n return str(key)\n elif len(char_map_dict.keys()) == int(value):\n return \"\"\n raise ValueError('char map dict not has {:d} value. convert index to char failed.'.format(value))\n\n\ndef recognize(image_path, weights_path, char_dict_path, txt_path):\n \"\"\"\n 识别函数\n :param image_path: 图片所在路径\n :param weights_path: 模型保存路径\n :param char_dict_path: 字典文件存放位置\n :param txt_path: 包含图片名的txt文件\n :return: None\n \"\"\"\n with open(txt_path, 'r', encoding='UTF-8') as fd:\n # image_names = [line.split(' ')[0] for line in fd.readlines()] # 有标注的情况\n image_names = [line.strip() for line in fd.readlines()] # 无标注的情况\n #with tf.device('/gpu:0'):\n inputdata = tf.placeholder(dtype=tf.float32, shape=[1, CFG.ARCH.INPUT_SIZE[1], None, CFG.ARCH.INPUT_CHANNELS], #宽度可变\n name='input')\n \n input_sequence_length = tf.placeholder(tf.int32, shape=[1], name='input_sequence_length')\n\n net = crnn_model.ShadowNet(phase='test', hidden_nums=CFG.ARCH.HIDDEN_UNITS,\n layers_nums=CFG.ARCH.HIDDEN_LAYERS, num_classes=CFG.ARCH.NUM_CLASSES)\n\n inference_ret = net.inference(inputdata=inputdata, name='shadow_net', reuse=False)\n\n #decodes = inference_ret\n decodes, _ = tf.nn.ctc_beam_search_decoder(inputs=inference_ret, sequence_length=input_sequence_length, # 序列宽度可变\n merge_repeated=False, beam_width=10)\n #preds = _sparse_matrix_to_list(decodes[0], char_dict_path)\n # 更改到此结束,把with tf.device注释了20191120\n\n # config tf saver\n saver = tf.train.Saver()\n\n # config tf session\n sess_config = tf.ConfigProto(allow_soft_placement=True) #, log_device_placement=True)\n # allow_soft_placement=True 不能在gpu上运行的自动迁移到cpu; log_device_placement=True 打印使用的设备\n sess_config.gpu_options.per_process_gpu_memory_fraction = CFG.TRAIN.GPU_MEMORY_FRACTION\n sess_config.gpu_options.allow_growth = CFG.TRAIN.TF_ALLOW_GROWTH\n\n sess = tf.Session(config=sess_config)\n\n with sess.as_default():\n saver.restore(sess=sess, save_path=weights_path)\n\n for image_name in image_names:\n # time_start = time.time()\n image_paths = os.path.join(image_path, image_name)\n # print(image_paths)\n image = cv2.imread(image_paths, cv2.IMREAD_COLOR)\n if image is None:\n print(image_paths+' is not exist')\n continue\n image = np.array(image, np.float32) / 127.5 - 1.0\n seq_len = np.array([image.shape[1] / 4], dtype=np.int32)\n # time_end_1 = time.time()\n preds = sess.run(decodes, feed_dict={inputdata: [image], input_sequence_length:seq_len})\n # time_end_2 = time.time()\n preds = _sparse_matrix_to_list(preds[0], char_dict_path)\n # time_end_3 = time.time()\n # print('Predict image {:s} result: {:s} cost time:{:f}'.format(image_name, preds[0], time_end-time_start))\n # print('Predict image {:s} total time:{:f} pre_process time:{:f}, run time:{:f}, convert_time:{:f}'.format(preds[0], time_end_3 - time_start, time_end_1 - time_start, time_end_2 - time_end_1, time_end_3 - time_end_2))\n print('Predict image {:s} result: {:s}'.format(image_name, preds[0]))\n\n sess.close()\n\n return\n\n\nif __name__ == '__main__':\n # init images\n args = init_args()\n # detect images\n recognize(image_path=args.image_path, weights_path=args.weights_path,\n char_dict_path=args.char_dict_path, txt_path=args.txt_path)\n" ]
[ [ "tensorflow.nn.ctc_beam_search_decoder", "tensorflow.placeholder", "numpy.ones", "tensorflow.ConfigProto", "tensorflow.Session", "tensorflow.train.Saver", "numpy.array" ] ]
ZiningWang/Inferring-Spatial-Uncertainty-in-Object-Detection
[ "3fc7c8d78e538805d928ba084c1c4570f795babc" ]
[ "utils/probability_utils.py" ]
[ "import numpy as np\r\nimport os\r\nimport sys\r\nfrom tqdm import tqdm\r\nfrom utils.kitti_utils import boxes3d_to_corners3d\r\n\r\n\r\nclass cov_interp:\r\n\t#interpterlate covariance matrix of Var[X(w)] = cov[\\Phi(Y)ww^T\\Phi(Y)^T] where w is n*1 and Y is m*n (Var[X] is m*m)\r\n\t#Y is a fixed random variable matrix, w is the coordinate (input argument)\r\n\tdef __init__(self, W, Vs):\r\n\t\t#W is tuple of k input w's\r\n\t\t#Vs are the k corresponding Var[X(w)]'s\r\n\t\t#the solved preprocessed matrix is Vinterp so that new Var[X(w)] = flatten(uppertriangle(ww^T))^T * Vinterp\r\n\t\tk = len(W)\r\n\t\tVstack = np.zeros([k,Vs[0].size])\r\n\t\tself.m = Vs[0].shape[0]\r\n\t\tself.n = W[0].size\r\n\t\twwstack = np.zeros([self.ww_flatten_size(),k])\r\n\t\tfor i in range(k):\r\n\t\t\tw = W[i]\r\n\t\t\tww = np.matmul(w.reshape([self.n,1]),w.reshape([1,self.n]))\r\n\t\t\twwstack[:,i] = self.extract_upper_triangle_ww(ww)\r\n\t\t\tVstack[i,:] = Vs[i].reshape([1,-1])\r\n\t\t#print(w, ww, self.extract_upper_triangle_ww(ww))\r\n\t\t#print(np.transpose(wwstack).shape, Vstack.shape)\r\n\t\t#print(np.linalg.eig(wwstack))\r\n\t\t#print(wwstack)\r\n\t\tself.Vinterp = np.linalg.solve(np.transpose(wwstack),Vstack)\r\n\r\n\tdef interp(self,w):\r\n\t\t#a single point w: n*1\r\n\t\tww = np.matmul(w.reshape([self.n,1]),w.reshape([1,self.n]))\r\n\t\tww_flatten = self.extract_upper_triangle_ww(ww)\r\n\t\tVout = ww_flatten*self.Vinterp\r\n\t\treturn Vout.reshape([self.m,self.m])\r\n\r\n\tdef interps(self,ws):\r\n\t\t#multiple points ws: k*n\r\n\t\twws_flatten = self.extract_upper_triangle_ws(ws)\r\n\t\tVouts = np.matmul(wws_flatten, self.Vinterp)\r\n\t\treturn Vouts.reshape([ws.shape[0], self.m, self.m])\r\n\r\n\tdef ww_flatten_size(self):\r\n\t\treturn int(self.n*(self.n+1)/2)\r\n\r\n\tdef extract_upper_triangle_ww(self,ww):\r\n\t\treturn ww[np.triu_indices(self.n)]\r\n\r\n\tdef extract_upper_triangle_ws(self,ws):\r\n\t\tk = ws.shape[0]\r\n\t\twws_flatten = np.zeros([k,self.ww_flatten_size()])\r\n\t\tj0 = 0\r\n\t\tfor i in range(self.n):\r\n\t\t\twws_flatten[:,j0:j0+self.n-i] = ws[:,i:i+1] * ws[:,i:]\r\n\t\t\tj0 += self.n-i\r\n\t\treturn wws_flatten\r\n\r\n\r\nclass cov_interp_BEV_full(cov_interp):\r\n\t#all the same, BEV requires k = 6 points (eg. 4 corners + 2 points on the side)\r\n\tdef __init__(self, W, Vs):\r\n\t\tassert len(W) == 6\r\n\t\tcov_interp.__init__(self, W, Vs) \r\n\r\n\r\nclass cov_interp_3D(cov_interp):\r\n\t#3D is a little bit different, because pitch and roll angle are not active\r\n\t#if take the full triangular matrix, would require 10 points\r\n\t#if ignore the pitch and roll, would require 8 points, eg. 6(BEV, say on the top) points + 2 bottom corner points\r\n\tdef __init__(self, W, Vs):\r\n\t\t#for 3D, only take these cols points\r\n\t\tself.flatten_idx = [0,2,3,4,6,7,8,9]\r\n\t\tcov_interp.__init__(self, W, Vs)\r\n\r\n\tdef ww_flatten_size(self):\r\n\t\treturn len(self.flatten_idx)\r\n\r\n\tdef extract_upper_triangle_ww(self,ww):\r\n\t\tww_flatten = ww[np.triu_indices(self.n)]\r\n\t\treturn ww_flatten[self.flatten_idx]\r\n\r\n\tdef extract_upper_triangle_ws(self,ws):\r\n\t\twws_flatten = cov_interp.extract_upper_triangle_ws(self,ws)\r\n\t\treturn wws_flatten[:,self.flatten_idx]\r\n\r\n\r\n#def bbox_uncertainty_to_spatial_uncertainty_BEV(boxBEV, std):\r\n\t#assume inputs are joint Gaussian, use importance sampling with student distribution to calculate variances of corners\r\n\r\ndef W_Vs_3D_to_BEV_full(W_3D, Vs_diag_3D):\r\n\tassert len(Vs_diag_3D.shape) == 3, 'The Vs shape should be n*8*3.'\r\n\tW_BEV = W_3D[[0,1,2,4,5,7], :][:, [0,2,3]]\r\n\tVs_BEV = np.zeros([Vs_diag_3D.shape[0], 6, 2, 2])\r\n\tfor i in range(Vs_diag_3D.shape[0]):\r\n\t\tVs_diag = Vs_diag_3D[i]\r\n\t\tVs = np.array([np.diag(Vs_diag[i]) for i in range(Vs_diag.shape[0])])\r\n\t\tVs_BEV[i] = Vs[[0,1,2,4,5,7], :, :][:, [0,2], :][:, :, [0,2]]\r\n\treturn W_BEV, Vs_BEV\r\n\r\ndef Hujie_uncertainty_reader(pred_dir, file_lists, max_num=7518):\r\n\timport pickle\r\n\tpickle_dir = pred_dir + 'unc_data/'\r\n\tattrs = ['box3D','corners','points_unc_sigma','ry','homogeneous_w','uncertainty_format']\r\n\tunc_data = {attr:[[] for name in range(max_num)] for attr in attrs}\r\n\tprint('reading data from: {}'.format(pickle_dir))\r\n\tfor file in file_lists:\r\n\t\tfile_num = file.split('.')[0]\r\n\t\tname = file_num\r\n\t\tframe = int(name)\r\n\t\tif int(float(name)) >= max_num:\r\n\t\t\tbreak\r\n\t\tcorner_unc_file_dir = os.path.join(pickle_dir,\"{}_UNC.pickle\".format(file_num))\r\n\t\tunc_info = pickle.load(open(corner_unc_file_dir,\"rb\"))\r\n\t\t# box3D is [x, y_top, z, h, w, l]\r\n\t\tunc_data['box3D'][frame] = unc_info['bbox3d'][:,0:6]\r\n\t\t# Some predictions got negative lengths....\r\n\t\tunc_data['box3D'][frame][:, 3:6] = np.abs(unc_data['box3D'][frame][:, 3:6])\r\n\t\tunc_data['ry'][frame] = unc_info['bbox3d'][:,6]\r\n\t\tunc_data['corners'][frame] = boxes3d_to_corners3d(unc_info['bbox3d'])\r\n\t\tif 'full' in pickle_dir:\r\n\t\t\tunc_data['homogeneous_w'][frame] = np.array([[0.5,-1,0.5,1],[0.5,-1,-0.5,1],[-0.5,-1,-0.5,1],[0.5,0,-0.5,1],[0.5,-1,0,1],[0,-1,-0.5,1],[0.5,-0.5,-0.5,1],[-0.5,-1,0.5,1]]) #8*3\r\n\t\t\tunc_data['uncertainty_format'] = 'full'\r\n\t\telse:\r\n\t\t\tprint('The uncertainty configuration cannot infer full covariance distribution inside the bounding box!')\r\n\t\t\tassert False, 'The warning is treated as error for now.'\r\n\t\t\tunc_data['homogeneous_w'][frame] = np.array([[0.5,-1,0.5,1],[0.5,-1,-0.5,1],[-0.5,-1,-0.5,1],[-0.5,-1,0.5,1],[0.5,0,0.5,1],[0.5,0,-0.5,1],[-0.5,0,-0.5,1],[-0.5,-0.5,0.5,1]]) #8*3\r\n\t\t\tunc_data['uncertainty_format'] = 'corner'\r\n\t\tunc_data['points_unc_sigma'][frame] = unc_info['bbox3d_sigma'].reshape([-1,8,3])\r\n\treturn unc_data\r\n" ]
[ [ "numpy.diag", "numpy.abs", "numpy.triu_indices", "numpy.matmul", "numpy.transpose", "numpy.array", "numpy.zeros" ] ]
jss367/detectron2
[ "085fda47bc49f2cdd9c05a895580b2b31fcdb6c3" ]
[ "projects/DensePose/densepose/engine/trainer.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\nimport logging\nimport os\nfrom collections import OrderedDict\nfrom typing import List, Optional, Union\nimport torch\nfrom torch import nn\n\nfrom detectron2.checkpoint import DetectionCheckpointer\nfrom detectron2.config import CfgNode\nfrom detectron2.engine import DefaultTrainer\nfrom detectron2.evaluation import (\n DatasetEvaluator,\n DatasetEvaluators,\n inference_on_dataset,\n print_csv_format,\n)\nfrom detectron2.solver.build import get_default_optimizer_params, maybe_add_gradient_clipping\nfrom detectron2.utils import comm\nfrom detectron2.utils.events import EventWriter, get_event_storage\n\nfrom densepose import DensePoseDatasetMapperTTA, DensePoseGeneralizedRCNNWithTTA, load_from_cfg\nfrom densepose.data import (\n DatasetMapper,\n build_combined_loader,\n build_detection_test_loader,\n build_detection_train_loader,\n build_inference_based_loaders,\n has_inference_based_loaders,\n)\nfrom densepose.evaluation.d2_evaluator_adapter import Detectron2COCOEvaluatorAdapter\nfrom densepose.evaluation.evaluator import DensePoseCOCOEvaluator, build_densepose_evaluator_storage\nfrom densepose.modeling.cse import Embedder\n\n\nclass SampleCountingLoader:\n def __init__(self, loader):\n self.loader = loader\n\n def __iter__(self):\n it = iter(self.loader)\n storage = get_event_storage()\n while True:\n try:\n batch = next(it)\n num_inst_per_dataset = {}\n for data in batch:\n dataset_name = data[\"dataset\"]\n if dataset_name not in num_inst_per_dataset:\n num_inst_per_dataset[dataset_name] = 0\n num_inst = len(data[\"instances\"])\n num_inst_per_dataset[dataset_name] += num_inst\n for dataset_name in num_inst_per_dataset:\n storage.put_scalar(f\"batch/{dataset_name}\", num_inst_per_dataset[dataset_name])\n yield batch\n except StopIteration:\n break\n\n\nclass SampleCountMetricPrinter(EventWriter):\n def __init__(self):\n self.logger = logging.getLogger(__name__)\n\n def write(self):\n storage = get_event_storage()\n batch_stats_strs = []\n for key, buf in storage.histories().items():\n if key.startswith(\"batch/\"):\n batch_stats_strs.append(f\"{key} {buf.avg(20)}\")\n self.logger.info(\", \".join(batch_stats_strs))\n\n\nclass Trainer(DefaultTrainer):\n @classmethod\n def extract_embedder_from_model(cls, model: nn.Module) -> Optional[Embedder]:\n if isinstance(model, nn.parallel.DistributedDataParallel):\n model = model.module\n if hasattr(model, \"roi_heads\") and hasattr(model.roi_heads, \"embedder\"):\n return model.roi_heads.embedder\n return None\n\n # TODO: the only reason to copy the base class code here is to pass the embedder from\n # the model to the evaluator; that should be refactored to avoid unnecessary copy-pasting\n @classmethod\n def test(\n cls,\n cfg: CfgNode,\n model: nn.Module,\n evaluators: Optional[Union[DatasetEvaluator, List[DatasetEvaluator]]] = None,\n ):\n \"\"\"\n Args:\n cfg (CfgNode):\n model (nn.Module):\n evaluators (DatasetEvaluator, list[DatasetEvaluator] or None): if None, will call\n :meth:`build_evaluator`. Otherwise, must have the same length as\n ``cfg.DATASETS.TEST``.\n\n Returns:\n dict: a dict of result metrics\n \"\"\"\n logger = logging.getLogger(__name__)\n if isinstance(evaluators, DatasetEvaluator):\n evaluators = [evaluators]\n if evaluators is not None:\n assert len(cfg.DATASETS.TEST) == len(evaluators), \"{} != {}\".format(\n len(cfg.DATASETS.TEST), len(evaluators)\n )\n\n results = OrderedDict()\n for idx, dataset_name in enumerate(cfg.DATASETS.TEST):\n data_loader = cls.build_test_loader(cfg, dataset_name)\n # When evaluators are passed in as arguments,\n # implicitly assume that evaluators can be created before data_loader.\n if evaluators is not None:\n evaluator = evaluators[idx]\n else:\n try:\n embedder = cls.extract_embedder_from_model(model)\n evaluator = cls.build_evaluator(cfg, dataset_name, embedder=embedder)\n except NotImplementedError:\n logger.warn(\n \"No evaluator found. Use `DefaultTrainer.test(evaluators=)`, \"\n \"or implement its `build_evaluator` method.\"\n )\n results[dataset_name] = {}\n continue\n if cfg.DENSEPOSE_EVALUATION.DISTRIBUTED_INFERENCE or comm.is_main_process():\n results_i = inference_on_dataset(model, data_loader, evaluator)\n else:\n results_i = {}\n results[dataset_name] = results_i\n if comm.is_main_process():\n assert isinstance(\n results_i, dict\n ), \"Evaluator must return a dict on the main process. Got {} instead.\".format(\n results_i\n )\n logger.info(\"Evaluation results for {} in csv format:\".format(dataset_name))\n print_csv_format(results_i)\n\n if len(results) == 1:\n results = list(results.values())[0]\n return results\n\n @classmethod\n def build_evaluator(\n cls,\n cfg: CfgNode,\n dataset_name: str,\n output_folder: Optional[str] = None,\n embedder: Optional[Embedder] = None,\n ) -> DatasetEvaluators:\n if output_folder is None:\n output_folder = os.path.join(cfg.OUTPUT_DIR, \"inference\")\n evaluators = []\n distributed = cfg.DENSEPOSE_EVALUATION.DISTRIBUTED_INFERENCE\n # Note: we currently use COCO evaluator for both COCO and LVIS datasets\n # to have compatible metrics. LVIS bbox evaluator could also be used\n # with an adapter to properly handle filtered / mapped categories\n # evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type\n # if evaluator_type == \"coco\":\n # evaluators.append(COCOEvaluator(dataset_name, output_dir=output_folder))\n # elif evaluator_type == \"lvis\":\n # evaluators.append(LVISEvaluator(dataset_name, output_dir=output_folder))\n evaluators.append(\n Detectron2COCOEvaluatorAdapter(\n dataset_name, output_dir=output_folder, distributed=distributed\n )\n )\n if cfg.MODEL.DENSEPOSE_ON:\n storage = build_densepose_evaluator_storage(cfg, output_folder)\n evaluators.append(\n DensePoseCOCOEvaluator(\n dataset_name,\n distributed,\n output_folder,\n evaluator_type=cfg.DENSEPOSE_EVALUATION.TYPE,\n min_iou_threshold=cfg.DENSEPOSE_EVALUATION.MIN_IOU_THRESHOLD,\n storage=storage,\n embedder=embedder,\n should_evaluate_mesh_alignment=cfg.DENSEPOSE_EVALUATION.EVALUATE_MESH_ALIGNMENT,\n mesh_alignment_mesh_names=cfg.DENSEPOSE_EVALUATION.MESH_ALIGNMENT_MESH_NAMES,\n )\n )\n return DatasetEvaluators(evaluators)\n\n @classmethod\n def build_optimizer(cls, cfg: CfgNode, model: nn.Module):\n params = get_default_optimizer_params(\n model,\n base_lr=cfg.SOLVER.BASE_LR,\n weight_decay_norm=cfg.SOLVER.WEIGHT_DECAY_NORM,\n bias_lr_factor=cfg.SOLVER.BIAS_LR_FACTOR,\n weight_decay_bias=cfg.SOLVER.WEIGHT_DECAY_BIAS,\n overrides={\n \"features\": {\n \"lr\": cfg.SOLVER.BASE_LR * cfg.MODEL.ROI_DENSEPOSE_HEAD.CSE.FEATURES_LR_FACTOR,\n },\n \"embeddings\": {\n \"lr\": cfg.SOLVER.BASE_LR * cfg.MODEL.ROI_DENSEPOSE_HEAD.CSE.EMBEDDING_LR_FACTOR,\n },\n },\n )\n optimizer = torch.optim.SGD(\n params,\n cfg.SOLVER.BASE_LR,\n momentum=cfg.SOLVER.MOMENTUM,\n nesterov=cfg.SOLVER.NESTEROV,\n weight_decay=cfg.SOLVER.WEIGHT_DECAY,\n )\n return maybe_add_gradient_clipping(cfg, optimizer)\n\n @classmethod\n def build_test_loader(cls, cfg: CfgNode, dataset_name):\n return build_detection_test_loader(cfg, dataset_name, mapper=DatasetMapper(cfg, False))\n\n @classmethod\n def build_train_loader(cls, cfg: CfgNode):\n data_loader = build_detection_train_loader(cfg, mapper=DatasetMapper(cfg, True))\n if not has_inference_based_loaders(cfg):\n return data_loader\n model = cls.build_model(cfg)\n model.to(cfg.BOOTSTRAP_MODEL.DEVICE)\n DetectionCheckpointer(model).resume_or_load(cfg.BOOTSTRAP_MODEL.WEIGHTS, resume=False)\n inference_based_loaders, ratios = build_inference_based_loaders(cfg, model)\n loaders = [data_loader] + inference_based_loaders\n ratios = [1.0] + ratios\n combined_data_loader = build_combined_loader(cfg, loaders, ratios)\n sample_counting_loader = SampleCountingLoader(combined_data_loader)\n return sample_counting_loader\n\n def build_writers(self):\n writers = super().build_writers()\n writers.append(SampleCountMetricPrinter())\n return writers\n\n @classmethod\n def test_with_TTA(cls, cfg: CfgNode, model):\n logger = logging.getLogger(\"detectron2.trainer\")\n # In the end of training, run an evaluation with TTA\n # Only support some R-CNN models.\n logger.info(\"Running inference with test-time augmentation ...\")\n transform_data = load_from_cfg(cfg)\n model = DensePoseGeneralizedRCNNWithTTA(\n cfg, model, transform_data, DensePoseDatasetMapperTTA(cfg)\n )\n evaluators = [\n cls.build_evaluator(\n cfg, name, output_folder=os.path.join(cfg.OUTPUT_DIR, \"inference_TTA\")\n )\n for name in cfg.DATASETS.TEST\n ]\n res = cls.test(cfg, model, evaluators) # pyre-ignore[6]\n res = OrderedDict({k + \"_TTA\": v for k, v in res.items()})\n return res\n" ]
[ [ "torch.optim.SGD" ] ]
mctouch/dlrm_for_pytorch
[ "a6572655053bbca0461af87c5ce30042950282bc" ]
[ "preproc/split_dataset.py" ]
[ "# Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport json\nimport os\nimport math\nfrom shutil import copyfile\n\nfrom tqdm import tqdm\nimport numpy as np\nfrom typing import Sequence\n\n\ndef get_categorical_feature_type(size: int):\n types = (np.int8, np.int16, np.int32)\n\n for numpy_type in types:\n if size < np.iinfo(numpy_type).max:\n return numpy_type\n\n raise RuntimeError(f\"Categorical feature of size {size} is too big for defined types\")\n\n\ndef split_binary_file(\n binary_file_path: str,\n output_dir: str,\n categorical_feature_sizes: Sequence[int],\n num_numerical_features: int,\n batch_size: int,\n source_data_type: str = 'int32',\n):\n record_width = 1 + num_numerical_features + len(categorical_feature_sizes) # label + numerical + categorical\n bytes_per_feature = np.__dict__[source_data_type]().nbytes\n bytes_per_entry = record_width * bytes_per_feature\n\n total_size = os.path.getsize(binary_file_path)\n batches_num = int(math.ceil((total_size // bytes_per_entry) / batch_size))\n\n cat_feature_types = [get_categorical_feature_type(cat_size) for cat_size in categorical_feature_sizes]\n\n file_streams = []\n try:\n input_data_f = open(binary_file_path, \"rb\")\n file_streams.append(input_data_f)\n\n numerical_f = open(os.path.join(output_dir, \"numerical.bin\"), \"wb+\")\n file_streams.append(numerical_f)\n\n label_f = open(os.path.join(output_dir, 'label.bin'), 'wb+')\n file_streams.append(label_f)\n\n categorical_fs = []\n for i in range(len(categorical_feature_sizes)):\n fs = open(os.path.join(output_dir, f'cat_{i}.bin'), 'wb+')\n categorical_fs.append(fs)\n file_streams.append(fs)\n\n for _ in tqdm(range(batches_num)):\n raw_data = np.frombuffer(input_data_f.read(bytes_per_entry * batch_size), dtype=np.int32)\n batch_data = raw_data.reshape(-1, record_width)\n\n numerical_features = batch_data[:, 1:1 + num_numerical_features].view(dtype=np.float32)\n numerical_f.write(numerical_features.astype(np.float16).tobytes())\n\n label = batch_data[:, 0]\n label_f.write(label.astype(np.bool).tobytes())\n\n cat_offset = num_numerical_features + 1\n for cat_idx, cat_feature_type in enumerate(cat_feature_types):\n cat_data = batch_data[:, (cat_idx + cat_offset):(cat_idx + cat_offset + 1)].astype(cat_feature_type)\n categorical_fs[cat_idx].write(cat_data.tobytes())\n finally:\n for stream in file_streams:\n stream.close()\n\n\ndef split_dataset(dataset_dir: str, output_dir: str, batch_size: int, numerical_features: int):\n categorical_sizes_file = os.path.join(dataset_dir, \"model_size.json\")\n with open(categorical_sizes_file) as f:\n categorical_sizes = list(json.load(f).values())\n\n train_file = os.path.join(dataset_dir, \"train_data.bin\")\n test_file = os.path.join(dataset_dir, \"test_data.bin\")\n val_file = os.path.join(dataset_dir, \"val_data.bin\")\n\n target_train = os.path.join(output_dir, \"train\")\n target_test = os.path.join(output_dir, \"test\")\n target_val = os.path.join(output_dir, \"val\")\n\n os.makedirs(output_dir, exist_ok=True)\n os.makedirs(target_train, exist_ok=True)\n os.makedirs(target_test, exist_ok=True)\n os.makedirs(target_val, exist_ok=True)\n\n copyfile(categorical_sizes_file, os.path.join(output_dir, \"model_size.json\"))\n split_binary_file(test_file, target_test, categorical_sizes, numerical_features, batch_size)\n split_binary_file(train_file, target_train, categorical_sizes, numerical_features, batch_size)\n split_binary_file(val_file, target_val, categorical_sizes, numerical_features, batch_size)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--dataset', type=str, required=True)\n parser.add_argument('--output', type=str, required=True)\n parser.add_argument('--batch_size', type=int, default=32768)\n parser.add_argument('--numerical_features', type=int, default=13)\n args = parser.parse_args()\n\n split_dataset(\n dataset_dir=args.dataset,\n output_dir=args.output,\n batch_size=args.batch_size,\n numerical_features=args.numerical_features\n )\n\n" ]
[ [ "numpy.iinfo" ] ]
Artelys/Safer-Roads
[ "ba9eb4b2c0f02c40142caa612ed7998c7ee01155", "ba9eb4b2c0f02c40142caa612ed7998c7ee01155" ]
[ "flask/harmonisation/corporel.py", "flask/training_corporel.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 31 12:54:46 2020\n\n@author: aboutet\n\"\"\"\nimport pandas as pd\nimport sys\nimport os\nimport Get_Location as gl\nfrom datetime import datetime, timedelta\n\nsys.path.append( \"/home/begood/flask/cluster/\")\nfrom functions import list_directory, getContext, find_last_id, get_data_frame_elastic\nfrom get_cluster import get_cluster\nfrom sklearn.preprocessing import Normalizer\nimport pickle\n\n\ndef corporel_before(es, infos, insert): \n print(\"start corporel\")\n path = \"Data/ref_baac/\"\n files_list = list_directory(path, \".csv\")\n dfs = {\"id\": {dic[\"label\"]: pd.read_csv(path+dic[\"label\"], encoding=\"latin-1\") for dic in files_list}}\n \n id_corporel = find_last_id(es, \"id_corpo\", infos[\"accidents\"])\n path = \"/home/begood/flask/cluster/\"\n dic = {\"id_corpo\":id_corporel} \n dic.update(dfs)\n return dic\n\ndef corporel(es, infos, data, documents): \n to_send = []\n for json in data:\n documents[\"id_corpo\"]+=1\n if \"geometry\" in json:\n point = float(json[\"geometry\"][\"lon\"]), float(json[\"geometry\"][\"lat\"])\n else:\n if json[\"GPS_LATITUDE\"] is None:\n continue\n point = [json[\"GPS_LONGITUDE\"], json[\"GPS_LATITUDE\"]]\n #if \"Addr_Type\" in json.keys() and not (json[\"Addr_Type\"] in [\"Postal\", \"PostalCode\"]):\n # continue\n link_ids = gl._get_link_in_envelope(es, point, index_name=infos[\"here\"])\n link_id = gl._get_closest_link(point, link_ids)\n json[\"point\"] = point\n json[\"ID_ACCIDENT\"] = json[\"ID_BAAC\"]\n \n json[\"TYPE\"] = \"CORPOREL\"\n if link_id[2] == 0:\n continue\n\n for name, df in documents[\"id\"].items():\n name = name[4:-4]\n value = json[\"ID_\"+name.upper()]\n if value is None:\n value = 0\n if isinstance(value, str):\n split = value.split(\",\")\n value = int(split[0])\n val = df[df[\"ID_\"+name.upper()] == value][\"LIBELLE\"]\n json[name] = list(val)[0]\n #ADD value of here base\n resp = es.search(index=infos[\"here\"], body={\"query\":{\"bool\":{\"must\":{\"term\":{\"_id\":link_id[2]}}}}})\n j = resp[\"hits\"][\"hits\"][0][\"_source\"]\n if \"Date\" in json.keys() and len(json[\"Date\"]) == 16:\n json[\"Date\"] = json[\"Date\"] +\":00\"\n new_json = {key:value for key, value in list(json.items()) + list(j.items())}\n if \"Tué\" in json[\"gravite\"]:\n new_json[\"mortel\"] = 1\n new_json[\"corporel\"] =0\n else:\n new_json[\"corporel\"] =1\n new_json[\"mortel\"] = 0\n \n #ADD ID\n new_json[\"id_corporel\"] = documents[\"id_corpo\"]\n \n date = datetime.strptime(new_json[\"Date\"], \"%d/%m/%Y %H:%M:%S\")\n if new_json[\"ID_USAGER\"] is None:\n new_json[\"ID_USAGER\"] = 0\n if new_json[\"AGE_USAGER\"] is None:\n new_json[\"AGE_USAGER\"] = 0\n if new_json[\"AGE_VEHICULE\"] is None:\n new_json[\"AGE_VEHICULE\"] = 0\n # Not take it is already present\n query = {\n \"query\":{\n \"bool\":{\n \"must\":[\n {\n \"term\":{\n \"ID_BAAC\":new_json[\"ID_BAAC\"]\n }\n },{\n \"term\":{\n \"AGE_USAGER\":new_json[\"AGE_USAGER\"]\n }\n },{\n \"term\":{\n \"AGE_VEHICULE\":new_json[\"AGE_VEHICULE\"]\n }\n },{\n \"term\":{\n \"ID_USAGER\":new_json[\"ID_USAGER\"]\n }\n }\n ]\n \n }\n }\n }\n r = es.search(index=infos[\"accidents\"], body=query)\n if r[\"hits\"][\"hits\"]:\n continue\n \n \n date_inf = date - timedelta(minutes=15)\n date_sup = date + timedelta(minutes=15)\n\n # If materiel are already present, delete them\n query = {\n \"query\":{\n \"bool\":{\n \"must\":[{\n \"bool\":{\n \"must\":[\n {\n \"range\" : {\n \"Date\" : {\n \"gte\" : str(date_inf),\n \"lte\" : str(date_sup)\n }\n }\n },{\n \"match\":{\n \"LINK_ID\": new_json[\"LINK_ID\"]\n }\n },\n ],\n \"must_not\":{\n \"exists\":{\n \"field\":\"id_corporel\"\n }\n }\n }\n \n }\n ]\n }\n }\n }\n\n r = es.search(index=infos[\"accidents\"], body=query)\n if r[\"hits\"][\"hits\"]:\n for j in r[\"hits\"][\"hits\"]:\n resp = es.delete(index=infos[\"accidents\"], doc_type=\"_doc\", id=j[\"_id\"], ignore=404)\n \n \n \n # Find every document related to the same accident\n hits = es.search(index=infos[\"accidents\"], body={\"size\":10000, \"query\":{\"match\":{\"ID_ACCIDENT\":json[\"ID_BAAC\"]}}})[\"hits\"][\"hits\"]\n if hits:\n mortels = [h[\"_source\"][\"mortel\"] for h in hits]\n if 1 in mortels:\n new_json[\"mortel\"] = 1\n new_json[\"corporel\"] = 0\n else:\n if \"mortel\" in new_json.keys() and new_json[\"mortel\"] == 1:\n to_send_update = []\n for j in hits:\n to_send_update.append({\"update\":{\"_id\":j[\"_id\"]}})\n to_send_update.append({\"doc\":{\"mortel\":1, \"corporel\":0}}) \n \n resp = es.bulk(index=infos[\"accidents\"], body=to_send_update, \n request_timeout=30)\n \n \n # ADD meteo\n date_meteo = date.replace(minute=0, second=0)\n if date.minute > 29:\n date_meteo = date_meteo + timedelta(hours=1)\n query = {\n \"query\":{\n \"bool\":{\n \"must\":{\n \"match\":{\n \"Date\":str(date_meteo)\n }\n }\n }\n }\n }\n \n r = es.search(index=infos[\"meteo\"], body=query)\n if r[\"hits\"][\"hits\"]:\n meteo_json = r[\"hits\"][\"hits\"][0][\"_source\"]\n new_json = {key:value for key, value in list(meteo_json.items()) + list(new_json.items())}\n new_json[\"meteo\"] = True\n # Do not take it if there is no meteo associated\n else:\n new_json[\"meteo\"] = False \n \n \n # Add context\n j = getContext(date)\n new_json = {key:value for key, value in list(j.items()) + list(new_json.items())} \n \n to_send.append({\"index\":{}})\n to_send.append(new_json)\n \n if to_send:\n resp = es.bulk(index=infos[\"accidents\"], body=to_send, request_timeout=300)\ndef corporel_after(es, infos):\n DATA_PATH = \"cluster/\"\n FILE_READY = 'accidents_corporels_pourclustering.csv'\n FILE_ACC = \"Corporels.csv\"\n FILE_PICKLE = \"DecisionTree_clustering_corporels.pkl\"\n FILE_NORMALIZE = \"Normalizer_Quanti.pkl\"\n FILE_LIST = \"list_columns.csv\"\n FILE_ENCODER = \"Encoder_Quali.pkl\"\n FILE_DATA = 'data.csv'\n \n ID_ACC = 'ID_ACCIDENT'\n file_ = open(os.path.join(DATA_PATH, FILE_NORMALIZE), 'rb')\n normalizer = pickle.load(file_)\n \n file = open(os.path.join(DATA_PATH, FILE_PICKLE), 'rb')\n clf = pickle.load(file)\n \n file__ = open(os.path.join(DATA_PATH, FILE_ENCODER), 'rb')\n encoder = pickle.load(file__)\n \n df = pd.read_csv(os.path.join(DATA_PATH, FILE_DATA), sep = ';', decimal = ',')\n \n # Import corporel\n corporels = get_data_frame_elastic(es, \"accidents\", exists=[\"id_corporel\"])\n \n columns = list(df.columns.difference(corporels.columns)) + [\"LINK_ID\"]\n df = corporels.merge(df[columns], on = 'LINK_ID', how = 'left')\n \n \n mappingRef = {\"gravite\":\"ID_GRAVITE\", \"obstacle_fixe\":\"ID_OBSTACLE_FIXE\", \"obstacle_mobile\":\"ID_OBSTACLE_MOBILE\", \n \"trajet\":\"ID_TRAJET\", \"etat_surface\":\"ID_ETAT_SURFACE\", \"condition_atmos\":\"ID_CONDITION_ATMOS\", \"lumiere\":\"ID_LUMIERE\",\n \"intersection\":\"ID_INTERSECTION\", \"facteur_usager\":\"ID_FACTEUR_USAGER\", \"fact_vl\":\"ID_FACT_VL\", \"categorie_usager\":\"ID_CATEGORIE_USAGER\",\"cat_admin\":\"ID_CAT_ADMIN\"}\n \n for key, value in mappingRef.items():\n df[value] = df[key]\n \n df[\"Type_Zone\"] = df[\"Type_Zone_2\"]\n \n cols = ['ID_FACTEUR_USAGER', \"ID_FACT_VL\", \"ID_INTERSECTION\", \"ID_GRAVITE\", \"ID_CAT_ADMIN\", \"ID_TRAJET\", \"ID_CATEGORIE_USAGER\"]\n other_cols = list(df.columns)\n for col in cols:\n other_cols.remove(col)\n \n def feature_engineering_baac(df):\n x = df.reset_index().loc[0,other_cols].copy()\n \n # Facteur usager\n fact = df[\"ID_FACTEUR_USAGER\"].values\n if \"Ivresse apparente\" in fact:\n val = \"Implique ivresse d'un usager\"\n elif \"Malaise - fatigue\" in fact or \"Assoupissement\" in fact:\n val = \"Implique le facteur fatigue\"\n else:\n val = \"Autre\"\n x['ID_FACTEUR_USAGER'] = val\n \n # Facteur véhicule\n fact = df[\"ID_FACT_VL\"].values\n if \"Pneumatique usé\" in fact or \"Éclatement de pneumatique\" in fact or \"Chargement\" in fact or \"Éclairage - signalisation\" in fact or \"Défectuosité mécanique\" in fact:\n val = \"Implique défectuosité d'un véhicule\"\n elif \"Déplacement du véhicule\" in fact or \"Véhicule peu familier au conducteur\" in fact or \"Aide à la conduite défaillante\" in fact:\n val = \"Implique un facteur de manoeuvre du véhicule\"\n elif \"Visibilité restreinte depuis l’habitacle\" in fact:\n \"Implique un facteur de visibilité restreinte dans l'habitacle\"\n else:\n val = \"Autres\"\n x['ID_FACT_VL'] = val\n \n # Intersection\n inter = df[\"ID_INTERSECTION\"].values[0]\n if inter == \"Giratoire\":\n val = \"Giratoire\"\n elif inter in [\"Hors intersection\", \"Non renseigné\", \"Intersection inconnue\"]:\n val = \"Hors intersection\"\n else:\n val = \"Autres intersections\"\n x['ID_INTERSECTION'] = val\n \n # Catégorie véhicule\n fact = df[\"ID_CAT_ADMIN\"].astype(str).values\n sentence = '-'.join(fact)\n if \"Bicyclette\" in sentence:\n val = \"Implique un vélo\"\n elif \"Cyclo\" in sentence or \"Moto\" in sentence or \"Scooter\" in sentence or \"Quad\" in sentence or \"3 RM\" in sentence:\n val = \"Implique un 2RM\"\n elif \"P.L.\" in sentence or \"Tracteur\" in sentence or \"Auto\" in sentence:\n val = \"Implique un poids lourd\"\n elif \"V.U.\" in sentence:\n val = \"Implique un véhicule utilitaire\"\n elif \"Train\" in sentence or \"Tramway\" in sentence:\n val = \"Implique un train ou tramway\"\n else:\n val = \"Implique un véhicule léger\"\n x['ID_CAT_ADMIN'] = val\n \n # Gravité\n fact = df[\"ID_GRAVITE\"].astype(str).values\n sentence = '-'.join(fact)\n if \"Tué\" in sentence:\n val = \"Implique un mort\"\n elif \"hospitalisé\" in sentence:\n val = \"Implique un blessé hospitalisé\"\n else:\n val = \"Tous les usager indemnes ou blessés légers\"\n x['ID_GRAVITE'] = val\n \n # Type de trajet\n fact = df[\"ID_TRAJET\"].astype(str).values\n sentence = '-'.join(fact)\n if \"loisir\" in sentence:\n val = \"Implique un trajet de loisir\"\n elif \"professionnelle\" in sentence:\n val = \"Implique un trajet profesionnel\"\n elif \"Domicile\" in sentence or \"Course\" in sentence:\n val = \"Implique un trajet du quotidien\"\n else:\n val = \"Implique d'autres trajets\"\n x['ID_TRAJET'] = val\n \n # Usagers impliqués\n fact = df[\"ID_CATEGORIE_USAGER\"].astype(str).values\n sentence = '-'.join(fact)\n if \"Piéton\" in sentence:\n val = \"Implique un piéton\"\n elif sum(fact==\"Conducteur\") > 1:\n val = \"Implique plusieurs conducteurs\"\n elif \"Passager\" in fact:\n val = \"Implique un seul conducteur et ses passagers\"\n else:\n val = \"Implique un seul conducteur sans passagers\"\n x['ID_CATEGORIE_USAGER'] = val\n return x\n \n \n df_ = df.groupby(ID_ACC, as_index = False).apply(feature_engineering_baac)\n \n fixe_replace = {'Fossé. talus. paroi rocheuse':'Fossé', 'Bâtiment. mur. pile de pont':'Bâtiment', 'Îlot. refuge. borne haute':'Îlot', \"Obstacle fixe inconnu\":\"Sans objet\"}\n mobile_replace ={\"Obstacle mobile inconnu\":'Autre', '0':\"Non renseigné ou sans objet\"}\n df_['ID_OBSTACLE_FIXE'] = df_['ID_OBSTACLE_FIXE'].fillna('Sans objet').replace(fixe_replace)\n df_['ID_OBSTACLE_MOBILE'] = df_['ID_OBSTACLE_MOBILE'].fillna(\"Non renseigné ou sans objet\").replace(mobile_replace)\n \n colsQuali = ['creneau',\n 'Periode_Specifique',\n 'Type_Voie',\n 'Vitesse_Autorisee',\n 'Type_Zone',\n 'Categorie_Route',\n 'ID_ETAT_SURFACE',\n 'ID_CONDITION_ATMOS',\n 'ID_LUMIERE',\n 'ID_OBSTACLE_FIXE',\n 'ID_OBSTACLE_MOBILE',\n 'ID_FACTEUR_USAGER',\n 'ID_FACT_VL',\n 'ID_INTERSECTION',\n 'ID_GRAVITE',\n 'ID_CAT_ADMIN',\n 'ID_TRAJET',\n 'ID_CATEGORIE_USAGER']\n\n colsQuanti = ['Pluviometrie 6h',\n 'Trafic',\n 'Courbure',\n 'NB_MATERIEL',\n 'Accident',\n 'Chaussée dégradée',\n 'JAM',\n 'ROAD_CLOSED',\n 'Retrecissement',\n 'Visibilité réduite',\n 'Route glissante',\n 'Véhicule arrêté',\n 'WEATHERHAZARD']\n \n cols = colsQuali + colsQuanti + [\"ID_BAAC\"]\n dataset = df_[cols].reset_index(drop = True)\n\n def encoding_from_pickle(dataset, encoder, cols_learning_quanti, cols_learning_quali):\n train = dataset.copy()\n \n ## Colonnes quantitatives\n for col in cols_learning_quanti:\n train[col] = train[col].astype(float)\n \n ## Colonnes qualitatives\n #encoder = OneHotEncoder(drop='first')\n #encoder.fit(train[cols_learning_quali])\n quali = encoder.transform(train[cols_learning_quali]).toarray()\n \n \n # Bien nommer les colonnes par catégories\n train.drop(cols_learning_quali, axis = 1, inplace = True)\n qualiCols = []\n for originalCol, catList in zip(cols_learning_quali, encoder.categories_):\n catList = catList[1:]\n l = [originalCol + '__' + str(cat) for cat in catList]\n qualiCols = qualiCols + l\n \n # Ajout des nouvelles colonnes encodées\n for col in qualiCols:\n train[col] = 0\n \n train[qualiCols] = quali\n \n return train\n dataset_ = dataset[cols]\n train = encoding_from_pickle(dataset_, encoder,colsQuanti, colsQuali)\n train = train.fillna(0)\n train[colsQuanti] = normalizer.transform(train[colsQuanti])\n del train[\"ID_BAAC\"]\n new_clus = clf.predict(train)\n cluster = \"Cluster Accident\"\n dataset[cluster] = new_clus\n short_data = dataset[[\"ID_BAAC\", cluster]]\n del corporels[cluster]\n data_ready = corporels.merge(short_data, how=\"left\", on=\"ID_BAAC\")\n data_ready = data_ready[[\"id\", cluster]]\n to_send = []\n for index, row in data_ready.iterrows():\n to_send.append({\"update\":{\"_id\":row[\"id\"]}})\n to_send.append({\"doc\":{cluster:row[cluster]}})\n \n es.bulk(index=\"accidents\", body=to_send, request_timeout=3000)\n return\n", "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 19 14:51:39 2020\n\n@author: aboutet\n\"\"\"\n\n# Librairies d'apprentissage automatique\nfrom sklearn import tree, ensemble, metrics, model_selection\nfrom sklearn.preprocessing import scale, StandardScaler\nfrom sklearn.tree import export_graphviz\nfrom sklearn.externals.six import StringIO \nfrom sklearn.metrics import make_scorer\nfrom sklearn.metrics import roc_curve, auc, roc_auc_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.model_selection import ShuffleSplit\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.cluster import KMeans\nimport pickle\n\nimport pandas as pd\n\nimport ml_utils\nimport plot\nfrom variables import *\n\ndef training_corporel(dataC):\n dataC = pd.read_csv(\"C:/Users/aboutet/Documents/flask/apprentissage_corporel.csv\", sep = ';', encoding = 'utf-8-sig',decimal = ',')\n\n\n FEATURES_HERE_QUALI_NO_ORDER = [\"PRIORITYRD\",\"AR_AUTO\",\"AR_BUS\",\"AR_TAXIS\",\"AR_CARPOOL\",\"AR_PEDEST\",\"AR_TRUCKS\",\"AR_TRAFF\",\"AR_DELIV\",\"AR_EMERVEH\",\"AR_MOTOR\",\n \"PAVED\",\"PRIVATE\",\"FRONTAGE\",\"BRIDGE\",\"TUNNEL\",\"RAMP\",\"TOLLWAY\",\"POIACCESS\",\"CONTRACC\",\"ROUNDABOUT\",\"INTERINTER\"]\n FEATURES_HERE_QUALI_ORDERED = [\"SPEED_CAT\",\"FUNC_CLASS\"]\n FEATURES_HERE_QUANTI = [\"N_SHAPEPNT\"]\n\n \n aggregation = {\"Trafic redressé\":'mean',\"Total alertes Waze\":'mean', \"N_SHAPEPNT\":'mean',\"Nombre alertes Waze BOUCHONS\":'mean', \"Nombre alertes Waze DANGERROUTE\":'mean',\"Nombre total d'alertes Coyote\":'mean'}\n QUANTI_KEEP = list(aggregation.keys())\n QUALI_ORDERED_KEEP = [\"FUNC_CLASS\",\"SPEED_CAT\"]\n QUALI_NOORDER_KEEP = [\"Contient intersection\",'PAVED','Vitesse adjacente supérieure']\n \n QUANTI_KEEP = QUANTI_KEEP + METEO_QUANTI\n QUALI_ORDERED_KEEP = QUALI_ORDERED_KEEP\n QUALI_NOORDER_KEEP = QUALI_NOORDER_KEEP + [INFO_JOUR,JOUR_SEMAINE, MOIS, CRENEAU]\n \n # MISE A JOUR de la liste des variables après preprocessing\n FEATURES_HERE_QUALI_NO_ORDER = FEATURES_HERE_QUALI_NO_ORDER + [ADJ_SUP, ADJ_INF] + [CONTIENT_INTERSECTION] + [CORINE]\n FEATURES_HERE_QUANTI = FEATURES_HERE_QUANTI + [WAZE_TOTAL, WAZE_ACCIDENT, WAZE_JAM, WAZE_CLOSED, WAZE_WEATHER, WAZE_HAZARD] + ALERTES_COYOTE + [TOTAL_COYOTE] + [TRAFIC]\n \n \n baro_ = barometre_accidents_corporels(dataC, QUANTI_KEEP, QUALI_NOORDER_KEEP, QUALI_ORDERED_KEEP)\n \n baro_.fit(print_results = False)\n \n importance = baro_.feature_importances_(plot = False)\n # Sauvegarde sur disque-dur\n path = 'Barometre_corporel.pkl'\n baro_.save(path)\n return importance, path\n\nclass barometre_accidents_corporels():\n \n def __init__(self, data, quantis, qualiNoOrder, qualiOrder):\n '''\n Constructor\n '''\n \n # Constantes\n self.nTrees = 200\n self.maxDepth = 30\n self.maxLeaves = 30\n self.verbose = 5\n \n self.positive_class = 0\n \n # Attributs passés\n self.quantis = quantis\n self.qualiNoOrder = qualiNoOrder\n self.qualiOrder = qualiOrder\n \n \n # Données d'entrainement: déterminent d'entrée la structure des modèles dans le constructeur\n self.data = data\n self.data['Classes simples'] = [0 if ac > 0 else 1 for ac in self.data[ID_ACC]]\n \n # Formattage pour l'apprentissage\n self.scaler_quanti = StandardScaler(with_mean = True, with_std = True)\n self.scaler_qualiOrder = StandardScaler(with_mean = True, with_std = True)\n self.train, self.target = self.preprocessing_learning()\n \n # Récupération de la liste des variables (colonnes) qu'il faut impérativement donner en entrée de l'algorithme\n self.cols = self.train.columns\n \n # Modele \n self.rf = ensemble.RandomForestClassifier(class_weight = 'balanced', n_estimators = self.nTrees, max_features = None, max_depth = self.maxDepth, max_leaf_nodes = self.maxLeaves, \n min_samples_leaf = 5, min_samples_split = 2, verbose = self.verbose)\n self.importance = None\n \n \n\n \n ## Learning or test data preparation phase\n def preprocessing_learning(self):\n trains = dict()\n targets = dict()\n \n # Choix des variables explicatives et target\n train = self.data[self.quantis+self.qualiNoOrder+self.qualiOrder]\n target = self.data['Classes simples']\n\n # Encoding du qualitatif\n train = ml_utils.preproc_features(train, self.quantis, self.qualiOrder, self.qualiNoOrder)\n\n # Centrage-Normalisation du quantitatif\n #train[self.quantis] = scale(train[self.quantis])\n #train[self.qualiOrder] = scale(train[self.qualiOrder]) \n \n # Scaler should scale the same way all data it will see in the future\n self.scaler_quanti.fit(train[self.quantis])\n self.scaler_qualiOrder.fit(train[self.qualiOrder])\n train[self.quantis] = self.scaler_quanti.transform(train[self.quantis])\n train[self.qualiOrder] = self.scaler_qualiOrder.transform(train[self.qualiOrder]) \n \n return train, target\n \n \n def preprocessing_test(self, data):\n trains = dict()\n targets = dict()\n \n # Choix des variables explicatives et target\n train = data[self.quantis+self.qualiNoOrder+self.qualiOrder]\n\n # Encoding du qualitatif\n train = ml_utils.preproc_features(train, self.quantis, self.qualiOrder, self.qualiNoOrder)\n\n # Centrage-Normalisation du quantitatif\n train[self.quantis] = self.scaler_quanti.transform(train[self.quantis])\n train[self.qualiOrder] = self.scaler_qualiOrder.transform(train[self.qualiOrder]) \n \n return train\n \n ## Proper Learning & Learning Features\n def fit(self, print_results = True, retourne = False):\n # Entrainement du RF\n self.rf = self.rf.fit(self.train, self.target)\n \n # Résultats\n if print_results:\n if retourne:\n mat, confusion, prec,recall,giny = self.predict_with_result(None, None, learning_data = True, print_ = True, retourne = retourne)\n return mat, confusion, prec,recall,giny\n else:\n self.predict_with_result(None, None, learning_data = True, print_ = True, retourne = False)\n \n \n ## Test & Performance Features\n\n def predict_with_result(self, test, y_true, learning_data = False, print_ = True, retourne = False):\n if learning_data:\n y_true = self.target\n y_pred = self.predict(test, probas = False, learning_data = learning_data)\n confusion = metrics.confusion_matrix(y_true, y_pred)\n prec = metrics.accuracy_score(y_true, y_pred)\n \n \n if len(y_true[y_true==self.positive_class]) ==0:\n recall = float('nan')\n giny = float('nan')\n else:\n recall = metrics.recall_score(y_true, y_pred, pos_label = self.positive_class)\n giny = 2*metrics.roc_auc_score(y_true, y_pred)-1\n \n if print_:\n print(\"Matrice de confusion:\")\n print(confusion)\n print(\"Précision:\")\n print(prec)\n print(\"Recall:\")\n print(recall)\n print('Normalized Gini:')\n print(giny)\n \n if retourne:\n return y_pred, confusion, prec, recall, giny\n \n \n def predict(self, test, learning_data = False, probas = False):\n \n # Données de test provenant de l'entrainement ou pas\n if learning_data:\n test = self.train\n else:\n test = self.preprocessing_test(test)\n # Ajout des modalités de variables qualitatives qui ne seraitent pas présents dans l'échantiilon de test: on le met à zéro\n for col in self.cols:\n if col not in test.columns:\n test[col] = 0\n \n # Colonnes dans le bon ordre\n test = test[self.cols]\n \n # Prédiction de classes ou probas\n if probas:\n pred = self.rf.predict_proba(test)\n else:\n pred = self.rf.predict(test)\n\n return pred\n \n \n def feature_importances_(self, plot = True):\n importances = pd.DataFrame(columns=self.train.columns)\n importances.loc[0] = self.rf.feature_importances_\n importances = importances.mean(axis = 0).sort_values(ascending = False)\n self.importance = importances\n if plot:\n importances.plot.bar(figsize = (10,7))\n return importances\n \n \n ## Save & Load Models\n def save(self, path):\n # Open the file to save as pkl file\n file = open(path, 'wb')\n pickle.dump(self, file)\n file.close()\n \n def load(self, path):\n return 0\n" ]
[ [ "pandas.read_csv" ], [ "sklearn.metrics.roc_auc_score", "pandas.read_csv", "sklearn.ensemble.RandomForestClassifier", "sklearn.metrics.confusion_matrix", "pandas.DataFrame", "sklearn.preprocessing.StandardScaler", "sklearn.metrics.recall_score", "sklearn.metrics.accuracy_score" ] ]
paolodidio/flatland-bologna
[ "3a493e686ae5c38f59b9f8230ce541cd0d0f4a9d" ]
[ "src/observations.py" ]
[ "\"\"\"\nCollection of environment-specific ObservationBuilder.\n\"\"\"\nimport collections\nfrom typing import Optional, List, Dict, Tuple\nfrom networkx.classes import graph\nfrom networkx.drawing.nx_pylab import draw\n\nimport numpy as np\n\nfrom flatland.core.env import Environment\n\nfrom flatland.core.env_observation_builder import ObservationBuilder\nfrom flatland.core.env_prediction_builder import PredictionBuilder\nfrom flatland.core.grid.grid4_utils import get_new_position\nfrom flatland.core.grid.grid_utils import coordinate_to_position\nfrom flatland.envs.agent_utils import RailAgentStatus, EnvAgent\nfrom flatland.utils.ordered_set import OrderedSet\nfrom numpy.core.numeric import NaN\nfrom src.graph.graph import Graph\nimport networkx as nx\nfrom flatland.core.grid.grid4 import Grid4TransitionsEnum\n\n\n# Node = collections.namedtuple('Node', 'dist_own_target_encountered '\n# 'dist_other_target_encountered '\n# 'dist_other_agent_encountered '\n# 'dist_potential_conflict '\n# 'dist_unusable_switch '\n# 'dist_to_next_branch '\n# 'dist_min_to_target '\n# 'num_agents_same_direction '\n# 'num_agents_opposite_direction '\n# 'num_agents_malfunctioning '\n# 'speed_min_fractional '\n# 'num_agents_ready_to_depart '\n# 'childs')\nNode = collections.namedtuple('Node', 'dist_own_target_encountered '\n 'dist_other_target_encountered '\n 'dist_other_agent_encountered '\n 'dist_potential_conflict '\n 'dist_unusable_switch '\n 'dist_to_next_branch '\n 'dist_min_to_target '\n 'num_agents_same_direction '\n 'num_agents_opposite_direction '\n 'num_agents_malfunctioning '\n 'speed_min_fractional '\n 'num_agents_ready_to_depart '\n 'is_deadlock '\n 'childs')\n#region TreeObsForRailEnv\nclass TreeObsForRailEnv(ObservationBuilder):\n \"\"\"\n TreeObsForRailEnv object.\n\n This object returns observation vectors for agents in the RailEnv environment.\n The information is local to each agent and exploits the graph structure of the rail\n network to simplify the representation of the state of the environment for each agent.\n\n For details about the features in the tree observation see the get() function.\n \"\"\"\n\n\n tree_explored_actions_char = ['L', 'F', 'R', 'B']\n\n def __init__(self, max_depth: int, predictor: PredictionBuilder = None):\n super().__init__()\n self.max_depth = max_depth\n self.observation_dim = 11\n self.location_has_agent = {}\n self.location_has_agent_direction = {}\n self.predictor = predictor\n self.location_has_target = None\n\n def reset(self):\n self.location_has_target = {tuple(agent.target): 1 for agent in self.env.agents}\n\n def get_many(self, handles: Optional[List[int]] = None) -> Dict[int, Node]:\n \"\"\"\n Called whenever an observation has to be computed for the `env` environment, for each agent with handle\n in the `handles` list.\n \"\"\"\n\n if handles is None:\n handles = []\n if self.predictor:\n self.max_prediction_depth = 0\n self.predicted_pos = {}\n self.predicted_dir = {}\n self.predictions = self.predictor.get()\n if self.predictions:\n for t in range(self.predictor.max_depth + 1):\n pos_list = []\n dir_list = []\n for a in handles:\n if self.predictions[a] is None:\n continue\n pos_list.append(self.predictions[a][t][1:3])\n dir_list.append(self.predictions[a][t][3])\n self.predicted_pos.update({t: coordinate_to_position(self.env.width, pos_list)})\n self.predicted_dir.update({t: dir_list})\n self.max_prediction_depth = len(self.predicted_pos)\n # Update local lookup table for all agents' positions\n # ignore other agents not in the grid (only status active and done)\n # self.location_has_agent = {tuple(agent.position): 1 for agent in self.env.agents if\n # agent.status in [RailAgentStatus.ACTIVE, RailAgentStatus.DONE]}\n\n self.location_has_agent = {}\n self.location_has_agent_direction = {}\n self.location_has_agent_speed = {}\n self.location_has_agent_malfunction = {}\n self.location_has_agent_ready_to_depart = {}\n\n for _agent in self.env.agents:\n if _agent.status in [RailAgentStatus.ACTIVE, RailAgentStatus.DONE] and \\\n _agent.position:\n self.location_has_agent[tuple(_agent.position)] = 1\n self.location_has_agent_direction[tuple(_agent.position)] = _agent.direction\n self.location_has_agent_speed[tuple(_agent.position)] = _agent.speed_data['speed']\n self.location_has_agent_malfunction[tuple(_agent.position)] = _agent.malfunction_data[\n 'malfunction']\n\n if _agent.status in [RailAgentStatus.READY_TO_DEPART] and \\\n _agent.initial_position:\n \n self.location_has_agent_ready_to_depart[tuple(_agent.initial_position)] = \\\n self.location_has_agent_ready_to_depart.get(tuple(_agent.initial_position), 0) + 1\n\n observations = super().get_many(handles)\n\n return observations\n\n def get(self, handle: int = 0) -> Node:\n \"\"\"\n Computes the current observation for agent `handle` in env\n\n The observation vector is composed of 4 sequential parts, corresponding to data from the up to 4 possible\n movements in a RailEnv (up to because only a subset of possible transitions are allowed in RailEnv).\n The possible movements are sorted relative to the current orientation of the agent, rather than NESW as for\n the transitions. The order is::\n\n [data from 'left'] + [data from 'forward'] + [data from 'right'] + [data from 'back']\n\n Each branch data is organized as::\n\n [root node information] +\n [recursive branch data from 'left'] +\n [... from 'forward'] +\n [... from 'right] +\n [... from 'back']\n\n Each node information is composed of 9 features:\n\n #1:\n if own target lies on the explored branch the current distance from the agent in number of cells is stored.\n\n #2:\n if another agents target is detected the distance in number of cells from the agents current location\\\n is stored\n\n #3:\n if another agent is detected the distance in number of cells from current agent position is stored.\n\n #4:\n possible conflict detected\n tot_dist = Other agent predicts to pass along this cell at the same time as the agent, we store the \\\n distance in number of cells from current agent position\n\n 0 = No other agent reserve the same cell at similar time\n\n #5:\n if an not usable switch (for agent) is detected we store the distance.\n\n #6:\n This feature stores the distance in number of cells to the next branching (current node)\n\n #7:\n minimum distance from node to the agent's target given the direction of the agent if this path is chosen\n\n #8:\n agent in the same direction\n n = number of agents present same direction \\\n (possible future use: number of other agents in the same direction in this branch)\n 0 = no agent present same direction\n\n #9:\n agent in the opposite direction\n n = number of agents present other direction than myself (so conflict) \\\n (possible future use: number of other agents in other direction in this branch, ie. number of conflicts)\n 0 = no agent present other direction than myself\n\n #10:\n malfunctioning/blokcing agents\n n = number of time steps the oberved agent remains blocked\n\n #11:\n slowest observed speed of an agent in same direction\n 1 if no agent is observed\n\n min_fractional speed otherwise\n #12:\n number of agents ready to depart but no yet active\n\n Missing/padding nodes are filled in with -inf (truncated).\n Missing values in present node are filled in with +inf (truncated).\n\n\n In case of the root node, the values are [0, 0, 0, 0, distance from agent to target, own malfunction, own speed]\n In case the target node is reached, the values are [0, 0, 0, 0, 0].\n \"\"\"\n\n if handle > len(self.env.agents):\n print(\"ERROR: obs _get - handle \", handle, \" len(agents)\", len(self.env.agents))\n agent = self.env.agents[handle] # TODO: handle being treated as index\n\n if agent.status == RailAgentStatus.READY_TO_DEPART:\n agent_virtual_position = agent.initial_position\n elif agent.status == RailAgentStatus.ACTIVE:\n agent_virtual_position = agent.position\n elif agent.status == RailAgentStatus.DONE:\n agent_virtual_position = agent.target\n else:\n return None\n\n possible_transitions = self.env.rail.get_transitions(*agent_virtual_position, agent.direction)\n num_transitions = np.count_nonzero(possible_transitions)\n\n # Here information about the agent itself is stored\n distance_map = self.env.distance_map.get()\n\n # was referring to TreeObsForRailEnv.Node\n root_node_observation = Node(dist_own_target_encountered=0, dist_other_target_encountered=0,\n dist_other_agent_encountered=0, dist_potential_conflict=0,\n dist_unusable_switch=0, dist_to_next_branch=0,\n dist_min_to_target=distance_map[\n (handle, *agent_virtual_position,\n agent.direction)],\n num_agents_same_direction=0, num_agents_opposite_direction=0,\n num_agents_malfunctioning=agent.malfunction_data['malfunction'],\n speed_min_fractional=agent.speed_data['speed'],\n num_agents_ready_to_depart=0,\n childs={})\n #print(\"root node type:\", type(root_node_observation))\n\n visited = OrderedSet()\n\n # Start from the current orientation, and see which transitions are available;\n # organize them as [left, forward, right, back], relative to the current orientation\n # If only one transition is possible, the tree is oriented with this transition as the forward branch.\n orientation = agent.direction\n\n if num_transitions == 1:\n orientation = np.argmax(possible_transitions)\n for i, branch_direction in enumerate([(orientation + i) % 4 for i in range(-1, 3)]):\n\n if possible_transitions[branch_direction]:\n new_cell = get_new_position(agent_virtual_position, branch_direction)\n\n \n branch_observation, branch_visited = \\\n self._explore_branch(handle, new_cell, branch_direction, 1, 1)\n root_node_observation.childs[self.tree_explored_actions_char[i]] = branch_observation\n\n visited |= branch_visited\n else:\n # add cells filled with infinity if no transition is possible\n root_node_observation.childs[self.tree_explored_actions_char[i]] = -np.inf\n self.env.dev_obs_dict[handle] = visited\n\n return root_node_observation\n\n def _explore_branch(self, handle, position, direction, tot_dist, depth):\n \"\"\"\n Utility function to compute tree-based observations.\n We walk along the branch and collect the information documented in the get() function.\n If there is a branching point a new node is created and each possible branch is explored.\n \"\"\"\n\n # [Recursive branch opened]\n if depth >= self.max_depth + 1:\n return [], []\n\n # Continue along direction until next switch or\n # until no transitions are possible along the current direction (i.e., dead-ends)\n # We treat dead-ends as nodes, instead of going back, to avoid loops\n exploring = True\n last_is_switch = False\n last_is_dead_end = False\n last_is_terminal = False # wrong cell OR cycle; either way, we don't want the agent to land here\n last_is_target = False\n\n visited = OrderedSet()\n agent = self.env.agents[handle]\n time_per_cell = np.reciprocal(agent.speed_data[\"speed\"])\n own_target_encountered = np.inf\n other_agent_encountered = np.inf\n other_target_encountered = np.inf\n potential_conflict = np.inf\n unusable_switch = np.inf\n other_agent_same_direction = 0\n other_agent_opposite_direction = 0\n malfunctioning_agent = 0\n min_fractional_speed = 1.\n num_steps = 1\n other_agent_ready_to_depart_encountered = 0\n while exploring:\n # #############################\n # #############################\n # Modify here to compute any useful data required to build the end node's features. This code is called\n # for each cell visited between the previous branching node and the next switch / target / dead-end.\n if position in self.location_has_agent:\n if tot_dist < other_agent_encountered:\n other_agent_encountered = tot_dist\n\n # Check if any of the observed agents is malfunctioning, store agent with longest duration left\n if self.location_has_agent_malfunction[position] > malfunctioning_agent:\n malfunctioning_agent = self.location_has_agent_malfunction[position]\n\n other_agent_ready_to_depart_encountered += self.location_has_agent_ready_to_depart.get(position, 0)\n\n if self.location_has_agent_direction[position] == direction:\n # Cummulate the number of agents on branch with same direction\n other_agent_same_direction += 1\n\n # Check fractional speed of agents\n current_fractional_speed = self.location_has_agent_speed[position]\n if current_fractional_speed < min_fractional_speed:\n min_fractional_speed = current_fractional_speed\n\n else:\n # If no agent in the same direction was found all agents in that position are other direction\n # Attention this counts to many agents as a few might be going off on a switch.\n other_agent_opposite_direction += self.location_has_agent[position]\n\n # Check number of possible transitions for agent and total number of transitions in cell (type)\n cell_transitions = self.env.rail.get_transitions(*position, direction)\n transition_bit = bin(self.env.rail.get_full_transitions(*position))\n total_transitions = transition_bit.count(\"1\")\n crossing_found = False\n if int(transition_bit, 2) == int('1000010000100001', 2):\n crossing_found = True\n\n # Register possible future conflict\n predicted_time = int(tot_dist * time_per_cell)\n if self.predictor and predicted_time < self.max_prediction_depth:\n int_position = coordinate_to_position(self.env.width, [position])\n if tot_dist < self.max_prediction_depth:\n\n pre_step = max(0, predicted_time - 1)\n post_step = min(self.max_prediction_depth - 1, predicted_time + 1)\n\n # Look for conflicting paths at distance tot_dist\n if int_position in np.delete(self.predicted_pos[predicted_time], handle, 0):\n conflicting_agent = np.where(self.predicted_pos[predicted_time] == int_position)\n for ca in conflicting_agent[0]:\n if direction != self.predicted_dir[predicted_time][ca] and cell_transitions[\n self._reverse_dir(\n self.predicted_dir[predicted_time][ca])] == 1 and tot_dist < potential_conflict:\n potential_conflict = tot_dist\n if self.env.agents[ca].status == RailAgentStatus.DONE and tot_dist < potential_conflict:\n potential_conflict = tot_dist\n\n # Look for conflicting paths at distance num_step-1\n elif int_position in np.delete(self.predicted_pos[pre_step], handle, 0):\n conflicting_agent = np.where(self.predicted_pos[pre_step] == int_position)\n for ca in conflicting_agent[0]:\n if direction != self.predicted_dir[pre_step][ca] \\\n and cell_transitions[self._reverse_dir(self.predicted_dir[pre_step][ca])] == 1 \\\n and tot_dist < potential_conflict: # noqa: E125\n potential_conflict = tot_dist\n if self.env.agents[ca].status == RailAgentStatus.DONE and tot_dist < potential_conflict:\n potential_conflict = tot_dist\n\n # Look for conflicting paths at distance num_step+1\n elif int_position in np.delete(self.predicted_pos[post_step], handle, 0):\n conflicting_agent = np.where(self.predicted_pos[post_step] == int_position)\n for ca in conflicting_agent[0]:\n if direction != self.predicted_dir[post_step][ca] and cell_transitions[self._reverse_dir(\n self.predicted_dir[post_step][ca])] == 1 \\\n and tot_dist < potential_conflict: # noqa: E125\n potential_conflict = tot_dist\n if self.env.agents[ca].status == RailAgentStatus.DONE and tot_dist < potential_conflict:\n potential_conflict = tot_dist\n \n if position in self.location_has_target and position != agent.target:\n if tot_dist < other_target_encountered:\n other_target_encountered = tot_dist\n\n if position == agent.target and tot_dist < own_target_encountered:\n own_target_encountered = tot_dist\n\n # #############################\n # #############################\n if (position[0], position[1], direction) in visited:\n last_is_terminal = True\n break\n visited.add((position[0], position[1], direction))\n\n # If the target node is encountered, pick that as node. Also, no further branching is possible.\n if np.array_equal(position, self.env.agents[handle].target):\n last_is_target = True\n break\n\n # Check if crossing is found --> Not an unusable switch\n if crossing_found:\n # Treat the crossing as a straight rail cell\n total_transitions = 2\n num_transitions = np.count_nonzero(cell_transitions)\n\n exploring = False\n\n # Detect Switches that can only be used by other agents.\n if total_transitions > 2 > num_transitions and tot_dist < unusable_switch:\n unusable_switch = tot_dist\n\n if num_transitions == 1:\n # Check if dead-end, or if we can go forward along direction\n nbits = total_transitions\n if nbits == 1:\n # Dead-end!\n last_is_dead_end = True\n\n if not last_is_dead_end:\n # Keep walking through the tree along `direction`\n exploring = True\n # convert one-hot encoding to 0,1,2,3\n direction = np.argmax(cell_transitions)\n position = get_new_position(position, direction)\n num_steps += 1\n tot_dist += 1\n elif num_transitions > 0:\n # Switch detected\n last_is_switch = True\n break\n\n elif num_transitions == 0:\n # Wrong cell type, but let's cover it and treat it as a dead-end, just in case\n print(\"WRONG CELL TYPE detected in tree-search (0 transitions possible) at cell\", position[0],\n position[1], direction)\n last_is_terminal = True\n break\n\n # `position` is either a terminal node or a switch\n\n # #############################\n # #############################\n # Modify here to append new / different features for each visited cell!\n\n if last_is_target:\n dist_to_next_branch = tot_dist\n dist_min_to_target = 0\n elif last_is_terminal:\n dist_to_next_branch = np.inf\n dist_min_to_target = self.env.distance_map.get()[handle, position[0], position[1], direction]\n else:\n dist_to_next_branch = tot_dist\n dist_min_to_target = self.env.distance_map.get()[handle, position[0], position[1], direction]\n\n # TreeObsForRailEnv.Node\n node = Node(dist_own_target_encountered=own_target_encountered,\n dist_other_target_encountered=other_target_encountered,\n dist_other_agent_encountered=other_agent_encountered,\n dist_potential_conflict=potential_conflict,\n dist_unusable_switch=unusable_switch,\n dist_to_next_branch=dist_to_next_branch,\n dist_min_to_target=dist_min_to_target,\n num_agents_same_direction=other_agent_same_direction,\n num_agents_opposite_direction=other_agent_opposite_direction,\n num_agents_malfunctioning=malfunctioning_agent,\n speed_min_fractional=min_fractional_speed,\n num_agents_ready_to_depart=other_agent_ready_to_depart_encountered,\n childs={})\n\n # #############################\n # #############################\n # Start from the current orientation, and see which transitions are available;\n # organize them as [left, forward, right, back], relative to the current orientation\n # Get the possible transitions\n possible_transitions = self.env.rail.get_transitions(*position, direction)\n for i, branch_direction in enumerate([(direction + 4 + i) % 4 for i in range(-1, 3)]):\n if last_is_dead_end and self.env.rail.get_transition((*position, direction),\n (branch_direction + 2) % 4):\n # Swap forward and back in case of dead-end, so that an agent can learn that going forward takes\n # it back\n new_cell = get_new_position(position, (branch_direction + 2) % 4)\n branch_observation, branch_visited = self._explore_branch(handle,\n new_cell,\n (branch_direction + 2) % 4,\n tot_dist + 1,\n depth + 1)\n node.childs[self.tree_explored_actions_char[i]] = branch_observation\n if len(branch_visited) != 0:\n visited |= branch_visited\n elif last_is_switch and possible_transitions[branch_direction]:\n new_cell = get_new_position(position, branch_direction)\n branch_observation, branch_visited = self._explore_branch(handle,\n new_cell,\n branch_direction,\n tot_dist + 1,\n depth + 1)\n node.childs[self.tree_explored_actions_char[i]] = branch_observation\n if len(branch_visited) != 0:\n visited |= branch_visited\n else:\n # no exploring possible, add just cells with infinity\n node.childs[self.tree_explored_actions_char[i]] = -np.inf\n\n if depth == self.max_depth:\n node.childs.clear()\n return node, visited\n\n def util_print_obs_subtree(self, tree: Node):\n \"\"\"\n Utility function to print tree observations returned by this object.\n \"\"\"\n self.print_node_features(tree, \"root\", \"\")\n for direction in self.tree_explored_actions_char:\n self.print_subtree(tree.childs[direction], direction, \"\\t\")\n\n @staticmethod\n def print_node_features(node: Node, label, indent):\n print(indent, \"Direction \", label, \": \", node.dist_own_target_encountered, \", \",\n node.dist_other_target_encountered, \", \", node.dist_other_agent_encountered, \", \",\n node.dist_potential_conflict, \", \", node.dist_unusable_switch, \", \", node.dist_to_next_branch, \", \",\n node.dist_min_to_target, \", \", node.num_agents_same_direction, \", \", node.num_agents_opposite_direction,\n \", \", node.num_agents_malfunctioning, \", \", node.speed_min_fractional, \", \",\n node.num_agents_ready_to_depart)\n\n def print_subtree(self, node, label, indent):\n if node == -np.inf or not node:\n print(indent, \"Direction \", label, \": -np.inf\")\n return\n\n self.print_node_features(node, label, indent)\n\n if not node.childs:\n return\n\n for direction in self.tree_explored_actions_char:\n self.print_subtree(node.childs[direction], direction, indent + \"\\t\")\n\n def set_env(self, env: Environment):\n super().set_env(env)\n if self.predictor:\n self.predictor.set_env(self.env)\n\n def _reverse_dir(self, direction):\n return int((direction + 2) % 4)\n#endregion\n\nclass TreeObsForRailEnvUsingGraph(ObservationBuilder):\n \"\"\"\n TreeObsForRailEnv object.\n\n This object returns observation vectors for agents in the RailEnv environment.\n The information is local to each agent and exploits the graph structure of the rail\n network to simplify the representation of the state of the environment for each agent.\n\n For details about the features in the tree observation see the get() function.\n \"\"\"\n\n\n tree_explored_actions_char = ['L', 'F', 'R', 'B']\n\n def __init__(self, max_depth: int, \n # map_graph: Graph, \n predictor: PredictionBuilder = None,\n ):\n super().__init__()\n # self.map_graph = map_graph\n self.max_depth = max_depth\n self.observation_dim = 12\n # self.location_has_agent = {}\n # self.location_has_agent_direction = {}\n self.predictor = predictor\n # self.location_has_target = None\n\n # def reset(self):\n # self.location_has_target = {tuple(agent.target): 1 for agent in self.env.agents}\n \n # Reset internal values\n def reset(self):\n self.map_graph = Graph(self.env)\n \n\n def get_many(self, handles: Optional[List[int]] = None) -> Dict[int, Node]:\n \"\"\"\n Called whenever an observation has to be computed for the `env` environment, for each agent with handle\n in the `handles` list.\n \"\"\"\n if self.predictor:\n #TODO: implement switch\n self.node_has_predicted_train = {}\n self.predictions = self.predictor.get()\n if self.predictions:\n for t in range(self.predictor.max_depth + 1):\n for a in handles:\n if self.predictions[a] is None:\n continue\n pos = self.predictions[a][t][1:3]\n dir = self.predictions[a][t][3]\n opposite_dir = (dir+2)%4\n if pos[0] == pos[0] and pos[1] == pos[1]: \n pos = (int(pos[0]), int(pos[1]))\n full_transitions = bin(self.env.rail.get_full_transitions(*pos))\n for direction in Grid4TransitionsEnum:\n if full_transitions.count('1') > 2 and direction == dir:\n continue\n if dir != direction:\n if (pos, direction) in self.map_graph.cell_connected_to_node:\n node, distance = self.map_graph.cell_connected_to_node[(pos, direction)]\n if node not in self.node_has_predicted_train:\n self.node_has_predicted_train[node] = {}\n if a not in self.node_has_predicted_train[node]:\n \n self.node_has_predicted_train[node][a] = (t, t, distance)\n else:\n t_min, t_max, distance_min = self.node_has_predicted_train[node][a]\n if t < t_min:\n self.node_has_predicted_train[node][a] = (t, t_max, distance)\n elif t > t_max:\n self.node_has_predicted_train[node][a] = (t_min, t, distance_min)\n else:\n self.node_has_predicted_train[node][a] = (t_min, t_max, distance_min) \n # pos_list.append(self.predictions[a][t][1:3])\n # dir_list.append(self.predictions[a][t][3])\n # self.predicted_pos.update({t: coordinate_to_position(self.env.width, pos_list)})\n # self.predicted_dir.update({t: dir_list})\n\n self.node_has_agent_going_to_switch = {}\n self.node_has_agent_coming_from_switch = {}\n # self.node_has_agent_on_switch = {}\n self.node_has_malfunction_agent = {}\n self.node_has_slower_agent_speed_same_direction = {}\n self.node_has_agents_ready_to_depart = {}\n \n #dictionary of dictionaries: for every node, for every agent is given the distance from the target\n self.node_has_target_of_agent = {} \n # suppose that has been implemented a dictionary in map_graph cell_connected_to_node which, given the cell, returns the node\n # suppose to have a dictionary in map_graph is_switch that, given a cell, is 1 if the cell is a switch\n for _agent in self.env.agents:\n # NOTE: should we include RailAgentStatus.DONE?\n if _agent.status in [RailAgentStatus.ACTIVE, RailAgentStatus.DONE] and _agent.position:\n for direction in Grid4TransitionsEnum:\n if (_agent.position, direction) in self.map_graph.cell_connected_to_node:\n # opposite_agent_direction = _agent.direction+2%4\n coming_from_switch = (direction != _agent.direction)\n node, distance = self.map_graph.cell_connected_to_node[(_agent.position, direction)]\n if coming_from_switch:\n #if the agent is in the switch, it does not count as coming from it, as it is not sure where it will move (not true for going to switch)\n if distance>0:\n if not node in self.node_has_agent_coming_from_switch:\n self.node_has_agent_coming_from_switch[node] = []\n self.node_has_agent_coming_from_switch[node].append((_agent.handle, distance)) \n else:\n if not node in self.node_has_agent_going_to_switch:\n self.node_has_agent_going_to_switch[node] = []\n self.node_has_agent_going_to_switch[node].append((_agent.handle, distance))\n \n #copy pasted the already existing algorithm (adapting it a bit)\n if _agent.malfunction_data['malfunction'] > 0:\n if not node in self.node_has_malfunction_agent:\n self.node_has_malfunction_agent[node] = []\n self.node_has_malfunction_agent[node].append((_agent.malfunction_data['malfunction'], distance))\n \n # if not node in self.slower_agent_speed_same_direction:\n # self.slower_agent_speed_same_direction[node] = []\n # self.slower_agent_speed_same_direction[node].append(_agent.speed_data['speed'], distance)\n target_position = _agent.target\n for direction in Grid4TransitionsEnum:\n if (target_position, direction) in self.map_graph.cell_connected_to_node:\n #FIXME: typo? _agent.position instead of target_position\n # node, distance = self.map_graph.cell_connected_to_node[(_agent.position, int(direction))]\n node, distance = self.map_graph.cell_connected_to_node[(target_position, int(direction))]\n if not node in self.node_has_target_of_agent:\n self.node_has_target_of_agent[node] = {}\n self.node_has_target_of_agent[node][_agent.handle] = distance\n # target_position = _agent.target\n # for direction in Grid4TransitionsEnum:\n # if (target_position, direction) in self.map_graph.cell_connected_to_node:\n # node, distance = self.map_graph.cell_connected_to_node[(_agent.position, int(direction))]\n # if not node in self.node_h(as_target_of_agent:\n # self.node_has_target_of_agent[node] = {}\n # self.node_has_target_of_agent[node][_agent.handle] = distance\n\n\n # if _agent.position in self.map_graph.is_switch:\n # for direction in Grid4TransitionsEnum:\n # self.node_has_agent_on_switch\n if _agent.status in [RailAgentStatus.READY_TO_DEPART] and _agent.initial_position:\n if (_agent.initial_position, _agent.direction) in self.map_graph.cell_connected_to_node:\n #NOTE: should i use _agent.initial_direction?\n node, distance = self.map_graph.cell_connected_to_node[(_agent.initial_position, _agent.direction)]\n if not node in self.node_has_agents_ready_to_depart:\n self.node_has_agents_ready_to_depart[node] = []\n self.node_has_agents_ready_to_depart[node].append((_agent.handle, distance))\n elif (_agent.handle, distance) not in self.node_has_agents_ready_to_depart[node]:\n self.node_has_agents_ready_to_depart[node].append((_agent.handle, distance))\n # if _agent.status in [RailAgentStatus.ACTIVE, RailAgentStatus.DONE] and _agent.position:\n # for direction in Grid4TransitionsEnum:\n # if (_agent.initial_position, direction) in self.map_graph.cell_connected_to_node:\n # node, distance = self.map_graph.cell_connected_to_node[(_agent.initial_position, direction)]\n # if not node in self.node_has_agents_ready_to_depart:\n # self.node_has_agents_ready_to_depart[node] = []\n # self.node_has_agents_ready_to_depart[node].append(_agent.handle, distance)\n \n\n\n\n\n\n observations = super().get_many(handles)\n\n return observations\n\n def get(self, handle: int = 0) -> Node:\n \"\"\"\n Computes the current observation for agent `handle` in env\n\n The observation vector is composed of 4 sequential parts, corresponding to data from the up to 4 possible\n movements in a RailEnv (up to because only a subset of possible transitions are allowed in RailEnv).\n The possible movements are sorted relative to the current orientation of the agent, rather than NESW as for\n the transitions. The order is::\n\n [data from 'left'] + [data from 'forward'] + [data from 'right'] + [data from 'back']\n\n Each branch data is organized as::\n\n [root node information] +\n [recursive branch data from 'left'] +\n [... from 'forward'] +\n [... from 'right] +\n [... from 'back']\n\n Each node information is composed of 9 features:\n\n #1:\n if own target lies on the explored branch the current distance from the agent in number of cells is stored.\n\n #2:\n if another agents target is detected the distance in number of cells from the agents current location\\\n is stored\n\n #3:\n if another agent is detected the distance in number of cells from current agent position is stored.\n\n #4:\n possible conflict detected\n tot_dist = Other agent predicts to pass along this cell at the same time as the agent, we store the \\\n distance in number of cells from current agent position\n\n 0 = No other agent reserve the same cell at similar time\n\n #5:\n if an not usable switch (for agent) is detected we store the distance.\n\n #6:\n This feature stores the distance in number of cells to the next branching (current node)\n\n #7:\n minimum distance from node to the agent's target given the direction of the agent if this path is chosen\n\n #8:\n agent in the same direction\n n = number of agents present same direction \\\n (possible future use: number of other agents in the same direction in this branch)\n 0 = no agent present same direction\n\n #9:\n agent in the opposite direction\n n = number of agents present other direction than myself (so conflict) \\\n (possible future use: number of other agents in other direction in this branch, ie. number of conflicts)\n 0 = no agent present other direction than myself\n\n #10:\n malfunctioning/blokcing agents\n n = number of time steps the oberved agent remains blocked\n\n #11:\n slowest observed speed of an agent in same direction\n 1 if no agent is observed\n\n min_fractional speed otherwise\n #12:\n number of agents ready to depart but no yet active\n\n #13:\n deadlock present in this node (if the current train will reach this node, it will cause a deadlock)\n\n Missing/padding nodes are filled in with -inf (truncated).\n Missing values in present node are filled in with +inf (truncated).\n\n\n In case of the root node, the values are [0, 0, 0, 0, distance from agent to target, own malfunction, own speed]\n In case the target node is reached, the values are [0, 0, 0, 0, 0].\n \"\"\"\n\n if handle > len(self.env.agents):\n print(\"ERROR: obs _get - handle \", handle, \" len(agents)\", len(self.env.agents))\n agent = self.env.agents[handle] # TODO: handle being treated as index\n\n if agent.status == RailAgentStatus.READY_TO_DEPART:\n agent_virtual_position = agent.initial_position\n elif agent.status == RailAgentStatus.ACTIVE:\n agent_virtual_position = agent.position\n elif agent.status == RailAgentStatus.DONE:\n agent_virtual_position = agent.target\n else:\n return None\n\n transitions = bin(self.env.rail.get_full_transitions(*agent_virtual_position))\n possible_transitions = self.env.rail.get_transitions(*agent_virtual_position, agent.direction)\n num_transitions = transitions.count('1')\n\n # Here information about the agent itself is stored\n distance_map = self.env.distance_map.get()\n \n # was referring to TreeObsForRailEnv.Node\n root_node_observation = Node(dist_own_target_encountered=0, dist_other_target_encountered=0,\n dist_other_agent_encountered=0, dist_potential_conflict=0,\n dist_unusable_switch=0, dist_to_next_branch=0,\n dist_min_to_target=distance_map[\n (handle, *agent_virtual_position,\n agent.direction)],\n num_agents_same_direction=0, num_agents_opposite_direction=0,\n num_agents_malfunctioning=agent.malfunction_data['malfunction'],\n speed_min_fractional=agent.speed_data['speed'],\n num_agents_ready_to_depart=0,\n is_deadlock=0,\n childs={})\n #print(\"root node type:\", type(root_node_observation))\n\n visited = OrderedSet()\n \n # Start from the current orientation, and see which transitions are available;\n # organize them as [left, forward, right, back], relative to the current orientation\n # If only one transition is possible, the tree is oriented with this transition as the forward branch.\n orientation = agent.direction\n if num_transitions == 2:\n orientation = np.argmax(possible_transitions)\n # (node, node_distance) = ((agent_virtual_position[0], agent_virtual_position[1], orientation), 0)\n if ((agent_virtual_position), orientation) not in self.map_graph.cell_connected_to_node:\n pass\n (node, node_distance) = self.map_graph.cell_connected_to_node[((agent_virtual_position), agent.direction)]\n\n root_node_observation.childs[self.tree_explored_actions_char[0]] = -np.inf\n root_node_observation.childs[self.tree_explored_actions_char[1]] = -np.inf\n root_node_observation.childs[self.tree_explored_actions_char[2]] = -np.inf\n root_node_observation.childs[self.tree_explored_actions_char[3]] = -np.inf\n \n out_edges = self.map_graph.graph.out_edges(node, data=True)\n if len(out_edges) > 0:\n for (_, _, in_node_direction),(out_node_row, out_node_col, out_node_direction), c in out_edges:\n #only one possible transaction, direction is always forward\n if num_transitions == 2:\n direction = 1\n else:\n #converting the in and out cardinal point to a relative direction\n direction = self._cardinal_to_action(in_node_direction, c['direction'])\n #the agent isn't in a switch, so it should start from the first switch\n if num_transitions == 2:\n branch_observation, branch_visited = \\\n self._explore_branch(handle, orientation, node, 0, 1, node_distance)\n #the agent is already in a switch, so it should start exploring from the next one (avoid exploring the first switch two times)\n else:\n branch_observation, branch_visited = \\\n self._explore_branch(handle, orientation, (out_node_row, out_node_col, out_node_direction), 0, 1, node_distance)\n \n root_node_observation.childs[self.tree_explored_actions_char[direction]] = branch_observation\n visited |= branch_visited \n # for i, branch_direction in enumerate([(orientation + i) % 4 for i in range(-1, 3)]):\n \n # if possible_transitions[branch_direction] and (agent_virtual_position , agent.direction) in self.map_graph.cell_connected_to_node:\n # # new_cell = get_new_position(agent_virtual_position, branch_direction)\n # (node, node_distance) = self.map_graph.cell_connected_to_node[((agent_virtual_position), agent.direction)]\n # branch_observation, branch_visited = \\\n # self._explore_branch(handle, branch_direction, node, 1, 1, node_distance)\n # root_node_observation.childs[self.tree_explored_actions_char[i]] = branch_observation\n # # branch_observation, branch_visited = \\\n # # self._explore_branch(handle, node, 1, 1, node_distance)\n # # root_node_observation.childs[self.tree_explored_actions_char[i]] = branch_observation\n\n # visited |= branch_visited\n # else:\n # # add cells filled with infinity if no transition is possible\n # root_node_observation.childs[self.tree_explored_actions_char[i]] = -np.inf\n self.env.dev_obs_dict[handle] = visited\n\n return root_node_observation\n\n def _explore_branch(self, handle, direction, graph_node, tot_dist, depth, agent_to_node_distance = np.inf):\n # def _explore_branch(self, handle, graph_node, tot_dist, depth, agent_to_node_distance = np.inf):\n \"\"\"\n Utility function to compute tree-based observations.\n We walk along the branch and collect the information documented in the get() function.\n If there is a branching point a new node is created and each possible branch is explored.\n \n ATTENTION!\n TODO: must also be considered the first case (between root node and the first switch)\n \"\"\"\n\n # [Recursive branch opened]\n if depth >= self.max_depth + 1:\n return [], []\n\n # Continue along direction until next switch or\n # until no transitions are possible along the current direction (i.e., dead-ends)\n # We treat dead-ends as nodes, instead of going back, to avoid loops\n # exploring = True\n # last_is_switch = False\n # last_is_dead_end = False\n # last_is_terminal = False # wrong cell OR cycle; either way, we don't want the agent to land here\n # last_is_target = False\n\n visited = OrderedSet()\n agent = self.env.agents[handle]\n time_per_cell = np.reciprocal(agent.speed_data[\"speed\"])\n own_target_encountered = np.inf\n other_agent_encountered = np.inf\n other_target_encountered = np.inf\n potential_conflict = np.inf\n unusable_switch = np.inf\n other_agent_same_direction = 0\n other_agent_opposite_direction = 0\n malfunctioning_agent = 0\n min_fractional_speed = 1.\n num_steps = 1\n other_agent_ready_to_depart_encountered = 0\n\n #total distance including also the distance of the current node\n in_edges = self.map_graph.graph.in_edges(graph_node, data=True)\n\n\n if len(in_edges) > 0:\n #there could be more than one in edge... to check if the graph is oriented\n for u,v,c in in_edges:\n #TODO: improve\n if tot_dist != 0:\n tot_dist_next = tot_dist + c['distance']\n else:\n tot_dist_next = agent_to_node_distance\n break\n agent_to_node_distance = tot_dist_next\n \n #region #1: \n # if own target lies on the explored branch the current distance from the agent in number of cells is stored.\n if graph_node in self.node_has_target_of_agent:\n if handle in self.node_has_target_of_agent[graph_node]:\n distance = self.node_has_target_of_agent[graph_node][handle]\n if distance < agent_to_node_distance:\n own_target_encountered = tot_dist_next - distance\n #endregion\n #region #2:\n # if another agents target is detected the distance in number of cells from the agents current location\\ is stored\n distances = list(self.node_has_target_of_agent[graph_node].values())\n distances = list(filter(lambda x: x < agent_to_node_distance, distances))\n if len(distances) > 0:\n other_target_encountered = tot_dist_next - np.max(distances)\n #endregion\n #region #3: \n # if another agent is detected the distance in number of cells from current agent position is stored.\n # NOTE: only opposite direction or also same direction?\n if graph_node in self.node_has_agent_coming_from_switch:\n # if len(self.node_has_agent_coming_from_switch) > 0 and graph_node in self.node_has_agent_coming_from_switch:\n # handles, distances = zip(*self.node_has_agent_coming_from_switch[graph_node])\n handle_distances = list(filter(lambda x: x[0]!=handle and x[1] < agent_to_node_distance, self.node_has_agent_coming_from_switch[graph_node]))\n if len(handle_distances) > 0:\n _, distances = zip(*handle_distances)\n potential_conflict = tot_dist_next - np.max(distances)\n #endregion\n #region #4:\n # possible conflict detected\n # tot_dist = Other agent predicts to pass along this cell at the same time as the agent, we store the \\\n # distance in number of cells from current agent position\n\n # 0 = No other agent reserve the same cell at similar time\n predicted_time = int(tot_dist * time_per_cell)\n if self.predictor:\n # pre_step = int(tot_dist * time_per_cell)\n # post_step = int(tot_dist_next * time_per_cell)\n if graph_node in self.node_has_predicted_train:\n for a in self.env.agents:\n if a.handle == handle:\n continue\n if a.handle in self.node_has_predicted_train[graph_node]:\n time_min, time_max, distance = self.node_has_predicted_train[graph_node][a.handle]\n #to exclude the case where the predicted train has already passed the root node\n if distance < agent_to_node_distance:\n if predicted_time in range(time_min, time_max):\n potential_conflict = tot_dist_next - distance\n \n # if self.predictor and predicted_time < self.max_prediction_depth:\n # int_position = coordinate_to_position(self.env.width, [position])\n # if tot_dist < self.max_prediction_depth:\n # pre_step = max(0, predicted_time - 1)\n # post_step = min(self.max_prediction_depth - 1, predicted_time + 1)\n\n # # Look for conflicting paths at distance tot_dist\n # if int_position in np.delete(self.predicted_pos[predicted_time], handle, 0):\n # conflicting_agent = np.where(self.predicted_pos[predicted_time] == int_position)\n # for ca in conflicting_agent[0]:\n # if direction != self.predicted_dir[predicted_time][ca] and cell_transitions[\n # self._reverse_dir(\n # self.predicted_dir[predicted_time][ca])] == 1 and tot_dist < potential_conflict:\n # potential_conflict = tot_dist\n # if self.env.agents[ca].status == RailAgentStatus.DONE and tot_dist < potential_conflict:\n # potential_conflict = tot_dist\n # # Look for conflicting paths at distance num_step-1\n # elif int_position in np.delete(self.predicted_pos[pre_step], handle, 0):\n # conflicting_agent = np.where(self.predicted_pos[pre_step] == int_position)\n # for ca in conflicting_agent[0]:\n # if direction != self.predicted_dir[pre_step][ca] \\\n # and cell_transitions[self._reverse_dir(self.predicted_dir[pre_step][ca])] == 1 \\\n # and tot_dist < potential_conflict: # noqa: E125\n # potential_conflict = tot_dist\n # if self.env.agents[ca].status == RailAgentStatus.DONE and tot_dist < potential_conflict:\n # potential_conflict = tot_dist\n # # Look for conflicting paths at distance num_step+1\n # elif int_position in np.delete(self.predicted_pos[post_step], handle, 0):\n # conflicting_agent = np.where(self.predicted_pos[post_step] == int_position)\n # for ca in conflicting_agent[0]:\n # if direction != self.predicted_dir[post_step][ca] and cell_transitions[self._reverse_dir(\n # self.predicted_dir[post_step][ca])] == 1 \\\n # and tot_dist < potential_conflict: # noqa: E125\n # potential_conflict = tot_dist\n # if self.env.agents[ca].status == RailAgentStatus.DONE and tot_dist < potential_conflict:\n # potential_conflict = tot_dist\n \n #endregion\n #region #5:\n # if an not usable switch (for agent) is detected we store the distance.\n # this point is useless, as we are changing the nodes such that also non usable switch is encoded as a node\n #endregion\n #region #6:\n # This feature stores the distance in number of cells to the next branching (current node)\n # NOTE: is this feature really useful?\n dist_to_next_branch = min(tot_dist_next - tot_dist, agent_to_node_distance)\n #endregion\n #region #7:\n # minimum distance from node to the agent's target given the direction of the agent if this path is chosen\n # NOTE: is this feature really useful?\n if own_target_encountered != np.inf:\n dist_to_next_branch = own_target_encountered\n dist_min_to_target = 0\n else:\n # dist_to_next_branch = tot_dist\n #TODO: direction?\n row_num, col_num, direction = graph_node\n dist_min_to_target = self.env.distance_map.get()[handle, row_num, col_num, direction]\n #endregion\n #region #8:\n # agent in the same direction\n # n = number of agents present same direction \\\n # (possible future use: number of other agents in the same direction in this branch)\n # 0 = no agent present same direction\n if graph_node in self.node_has_agent_going_to_switch:\n distances = list(zip(*self.node_has_agent_going_to_switch[graph_node]))[1]\n distances = list(filter(lambda x: x < agent_to_node_distance, distances))\n other_agent_same_direction = len(distances)\n #endregion\n #region #9:\n # agent in the opposite direction\n # n = number of agents present other direction than myself (so conflict) \\\n # (possible future use: number of other agents in other direction in this branch, ie. number of conflicts)\n # 0 = no agent present other direction than myself\n if graph_node in self.node_has_agent_coming_from_switch:\n distances = list(zip(*self.node_has_agent_coming_from_switch[graph_node]))[1]\n distances = list(filter(lambda x: x < agent_to_node_distance, distances))\n other_agent_opposite_direction = len(distances)\n #endregion\n #region #10:\n # malfunctioning/blokcing agents\n # n = number of time steps the oberved agent remains blocked\n if graph_node in self.node_has_malfunction_agent:\n if len(self.node_has_malfunction_agent[graph_node]) > 0:\n for malfunction, distance in self.node_has_malfunction_agent[graph_node]:\n if distance < agent_to_node_distance:\n if malfunctioning_agent < malfunction:\n malfunctioning_agent = malfunction\n #endregion\n #region #11:\n # slowest observed speed of an agent in same direction\n # 1 if no agent is observed\n if len(self.node_has_slower_agent_speed_same_direction) > 0:\n min_fractional_speed = self.node_has_slower_agent_speed_same_direction[graph_node]\n # min_fractional speed otherwise\n #endregion\n #region #12:\n # number of agents ready to depart but no yet active\n if len(self.node_has_agents_ready_to_depart) > 0:\n other_agent_ready_to_depart_encountered = self.node_has_agents_ready_to_depart.get(graph_node, 0)\n #endregion\n #region #13:\n # deadlock present in this node (if the current train will reach this node, it will cause a deadlock)\n # can be true or false (0 or 1)\n out_edges = self.map_graph.graph.out_edges(graph_node, data=True)\n deadlock = 1\n # if a train is in current node, there is deadlock\n if other_agent_opposite_direction == 0:\n #check connected nodes, if all of them have a train, it is a deadlock\n x_switch, y_switch, direction_switch = graph_node\n position_switch = (x_switch, y_switch)\n iherent_directions = self.get_deadlock_inherent_directions(position_switch, direction_switch, [0, 0, 0 ,0])\n for direction in Grid4TransitionsEnum:\n # get_new_position(position, direction)\n # xxx\n if direction!= (direction_switch + 2) % 4 and iherent_directions[direction]:\n new_position = get_new_position(position_switch, direction)\n if (new_position, direction) not in self.map_graph.cell_connected_to_node:\n raise Exception(\"this should not be a possibl situation\")\n next_node, _ = self.map_graph.cell_connected_to_node[(new_position, direction)]\n #must check that the agent is not \"blocking itself\" and the blocking agent are \"other agents\"\n other_agent_found = False\n if next_node in self.node_has_agent_coming_from_switch:\n for other_handle, _ in self.node_has_agent_coming_from_switch[next_node]:\n if other_handle != handle:\n other_agent_found = True\n continue\n if not other_agent_found:\n deadlock = 0\n continue\n else:\n deadlock = 0\n continue\n #TODO: add new features to normalize_observation\n\n\n \n # TreeObsForRailEnv.Node\n node = Node(dist_own_target_encountered=own_target_encountered,\n dist_other_target_encountered=other_target_encountered,\n dist_other_agent_encountered=other_agent_encountered,\n dist_potential_conflict=potential_conflict,\n dist_unusable_switch=unusable_switch,\n dist_to_next_branch=dist_to_next_branch,\n dist_min_to_target=dist_min_to_target,\n num_agents_same_direction=other_agent_same_direction,\n num_agents_opposite_direction=other_agent_opposite_direction,\n # num_agents_opposite_direction=deadlock,\n num_agents_malfunctioning=malfunctioning_agent,\n speed_min_fractional=min_fractional_speed,\n num_agents_ready_to_depart=other_agent_ready_to_depart_encountered,\n is_deadlock=0,\n # is_deadlock=deadlock,\n childs={})\n\n # #############################\n # #############################\n # Start from the current orientation, and see which transitions are available;\n # organize them as [left, forward, right, back], relative to the current orientation\n # Get the possible transitions\n visited.add(graph_node)\n \n node.childs[self.tree_explored_actions_char[0]] = -np.inf\n node.childs[self.tree_explored_actions_char[1]] = -np.inf\n node.childs[self.tree_explored_actions_char[2]] = -np.inf\n node.childs[self.tree_explored_actions_char[3]] = -np.inf\n\n out_edges = self.map_graph.graph.out_edges(graph_node, data=True)\n if len(out_edges) > 0:\n for (in_node_row, in_node_col, in_node_direction),(out_node_row, out_node_col, out_node_direction), c in out_edges:\n \n direction = self._cardinal_to_action(in_node_direction, c['direction'])\n # possible_transitions = self.env.rail.get_transitions(*(in_node_row, in_node_col), direction)\n branch_observation, branch_visited = self._explore_branch(handle,c['direction'], (out_node_row, out_node_col, out_node_direction), tot_dist_next, depth+1, tot_dist_next)\n # branch_observation, branch_visited = self._explore_branch(handle, (out_node_row, out_node_col, out_node_direction), tot_dist_next, depth+1, tot_dist_next)\n node.childs[self.tree_explored_actions_char[direction]] = branch_observation\n if len(branch_visited) != 0:\n visited |= branch_visited\n \n if depth == self.max_depth:\n node.childs.clear()\n return node, visited\n # possible_transitions = self.env.rail.get_transitions(*position, direction)\n # for i, branch_direction in enumerate([(direction + 4 + i) % 4 for i in range(-1, 3)]):\n # if last_is_dead_end and self.env.rail.get_transition((*position, direction),\n # (branch_direction + 2) % 4):\n # # Swap forward and back in case of dead-end, so that an agent can learn that going forward takes\n # # it back\n # new_cell = get_new_position(position, (branch_direction + 2) % 4)\n # branch_observation, branch_visited = self._explore_branch(handle,\n # new_cell,\n # (branch_direction + 2) % 4,\n # tot_dist + 1,\n # depth + 1)\n # node.childs[self.tree_explored_actions_char[i]] = branch_observation\n # if len(branch_visited) != 0:\n # visited |= branch_visited\n # elif last_is_switch and possible_transitions[branch_direction]:\n # new_cell = get_new_position(position, branch_direction)\n # branch_observation, branch_visited = self._explore_branch(handle,\n # new_cell,\n # branch_direction,\n # tot_dist + 1,\n # depth + 1)\n # node.childs[self.tree_explored_actions_char[i]] = branch_observation\n # if len(branch_visited) != 0:\n # visited |= branch_visited\n # else:\n # # no exploring possible, add just cells with infinity\n # node.childs[self.tree_explored_actions_char[i]] = -np.inf\n\n # if depth == self.max_depth:\n # node.childs.clear()\n # return node, visited\n\n def get_deadlock_inherent_directions(self, switch_position, direction, inherent_directions):\n \"\"\"\n Given the position of a switch and an initial direction, \n gives all directions that interests the trains going from the given direction\n Example: if there is a crossing and the train is going north, all directions are connected to rails,\n but only trins coming from north or south could interest our train\n \"\"\"\n possible_transitions = self.env.rail.get_transitions(*switch_position, direction)\n for new_direction in Grid4TransitionsEnum:\n if possible_transitions[new_direction]:\n if not inherent_directions[new_direction]:\n inherent_directions[new_direction] = 1\n inherent_directions = self.get_deadlock_inherent_directions(switch_position, (new_direction + 2) % 4 , inherent_directions)\n return inherent_directions\n \n def util_print_obs_subtree(self, tree: Node):\n \"\"\"\n Utility function to print tree observations returned by this object.\n \"\"\"\n self.print_node_features(tree, \"root\", \"\")\n for direction in self.tree_explored_actions_char:\n self.print_subtree(tree.childs[direction], direction, \"\\t\")\n\n @staticmethod\n def print_node_features(node: Node, label, indent):\n print(indent, \"Direction \", label, \": \", node.dist_own_target_encountered, \", \",\n node.dist_other_target_encountered, \", \", node.dist_other_agent_encountered, \", \",\n node.dist_potential_conflict, \", \", node.dist_unusable_switch, \", \", node.dist_to_next_branch, \", \",\n node.dist_min_to_target, \", \", node.num_agents_same_direction, \", \", node.num_agents_opposite_direction,\n \", \", node.num_agents_malfunctioning, \", \", node.speed_min_fractional, \", \",\n node.num_agents_ready_to_depart)\n\n def print_subtree(self, node, label, indent):\n if node == -np.inf or not node:\n print(indent, \"Direction \", label, \": -np.inf\")\n return\n\n self.print_node_features(node, label, indent)\n\n if not node.childs:\n return\n\n for direction in self.tree_explored_actions_char:\n self.print_subtree(node.childs[direction], direction, indent + \"\\t\")\n\n def set_env(self, env: Environment):\n super().set_env(env)\n if self.predictor:\n self.predictor.set_env(self.env)\n\n def _reverse_dir(self, direction):\n return int((direction + 2) % 4)\n\n #TODO: how to improve?\n def _cardinal_to_action(self, in_dir, out_dir):\n if in_dir == out_dir:\n return 1\n elif (in_dir + 1) % 4 == out_dir:\n return 2\n elif (in_dir + 2) % 4 == out_dir:\n return 3\n else:\n return 0\n#region GlobalsObsForRailEnv\nclass GlobalObsForRailEnv(ObservationBuilder):\n \"\"\"\n Gives a global observation of the entire rail environment.\n The observation is composed of the following elements:\n\n - transition map array with dimensions (env.height, env.width, 16),\\\n assuming 16 bits encoding of transitions.\n\n - obs_agents_state: A 3D array (map_height, map_width, 5) with\n - first channel containing the agents position and direction\n - second channel containing the other agents positions and direction\n - third channel containing agent/other agent malfunctions\n - fourth channel containing agent/other agent fractional speeds\n - fifth channel containing number of other agents ready to depart\n\n - obs_targets: Two 2D arrays (map_height, map_width, 2) containing respectively the position of the given agent\\\n target and the positions of the other agents targets (flag only, no counter!).\n \"\"\"\n\n def __init__(self):\n super(GlobalObsForRailEnv, self).__init__()\n\n def set_env(self, env: Environment):\n super().set_env(env)\n\n def reset(self):\n self.rail_obs = np.zeros((self.env.height, self.env.width, 16))\n for i in range(self.rail_obs.shape[0]):\n for j in range(self.rail_obs.shape[1]):\n bitlist = [int(digit) for digit in bin(self.env.rail.get_full_transitions(i, j))[2:]]\n bitlist = [0] * (16 - len(bitlist)) + bitlist\n self.rail_obs[i, j] = np.array(bitlist)\n\n def get(self, handle: int = 0) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n\n agent = self.env.agents[handle]\n if agent.status == RailAgentStatus.READY_TO_DEPART:\n agent_virtual_position = agent.initial_position\n elif agent.status == RailAgentStatus.ACTIVE:\n agent_virtual_position = agent.position\n elif agent.status == RailAgentStatus.DONE:\n agent_virtual_position = agent.target\n else:\n return None\n\n obs_targets = np.zeros((self.env.height, self.env.width, 2))\n obs_agents_state = np.zeros((self.env.height, self.env.width, 5)) - 1\n\n # TODO can we do this more elegantly?\n # for r in range(self.env.height):\n # for c in range(self.env.width):\n # obs_agents_state[(r, c)][4] = 0\n obs_agents_state[:, :, 4] = 0\n\n obs_agents_state[agent_virtual_position][0] = agent.direction\n obs_targets[agent.target][0] = 1\n\n for i in range(len(self.env.agents)):\n other_agent: EnvAgent = self.env.agents[i]\n\n # ignore other agents not in the grid any more\n if other_agent.status == RailAgentStatus.DONE_REMOVED:\n continue\n\n obs_targets[other_agent.target][1] = 1\n\n # second to fourth channel only if in the grid\n if other_agent.position is not None:\n # second channel only for other agents\n if i != handle:\n obs_agents_state[other_agent.position][1] = other_agent.direction\n obs_agents_state[other_agent.position][2] = other_agent.malfunction_data['malfunction']\n obs_agents_state[other_agent.position][3] = other_agent.speed_data['speed']\n # fifth channel: all ready to depart on this position\n if other_agent.status == RailAgentStatus.READY_TO_DEPART:\n obs_agents_state[other_agent.initial_position][4] += 1\n return self.rail_obs, obs_agents_state, obs_targets\n#endregion\n\n#region LocalsObsForRailEnv\nclass LocalObsForRailEnv(ObservationBuilder):\n \"\"\"\n !!!!!!WARNING!!! THIS IS DEPRACTED AND NOT UPDATED TO FLATLAND 2.0!!!!!\n Gives a local observation of the rail environment around the agent.\n The observation is composed of the following elements:\n\n - transition map array of the local environment around the given agent, \\\n with dimensions (view_height,2*view_width+1, 16), \\\n assuming 16 bits encoding of transitions.\n\n - Two 2D arrays (view_height,2*view_width+1, 2) containing respectively, \\\n if they are in the agent's vision range, its target position, the positions of the other targets.\n\n - A 2D array (view_height,2*view_width+1, 4) containing the one hot encoding of directions \\\n of the other agents at their position coordinates, if they are in the agent's vision range.\n\n - A 4 elements array with one hot encoding of the direction.\n\n Use the parameters view_width and view_height to define the rectangular view of the agent.\n The center parameters moves the agent along the height axis of this rectangle. If it is 0 the agent only has\n observation in front of it.\n\n .. deprecated:: 2.0.0\n \"\"\"\n\n def __init__(self, view_width, view_height, center):\n\n super(LocalObsForRailEnv, self).__init__()\n self.view_width = view_width\n self.view_height = view_height\n self.center = center\n self.max_padding = max(self.view_width, self.view_height - self.center)\n\n def reset(self):\n # We build the transition map with a view_radius empty cells expansion on each side.\n # This helps to collect the local transition map view when the agent is close to a border.\n self.max_padding = max(self.view_width, self.view_height)\n self.rail_obs = np.zeros((self.env.height,\n self.env.width, 16))\n for i in range(self.env.height):\n for j in range(self.env.width):\n bitlist = [int(digit) for digit in bin(self.env.rail.get_full_transitions(i, j))[2:]]\n bitlist = [0] * (16 - len(bitlist)) + bitlist\n self.rail_obs[i, j] = np.array(bitlist)\n\n def get(self, handle: int = 0) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n agents = self.env.agents\n agent = agents[handle]\n\n # Correct agents position for padding\n # agent_rel_pos[0] = agent.position[0] + self.max_padding\n # agent_rel_pos[1] = agent.position[1] + self.max_padding\n\n # Collect visible cells as set to be plotted\n visited, rel_coords = self.field_of_view(agent.position, agent.direction, )\n local_rail_obs = None\n\n # Add the visible cells to the observed cells\n self.env.dev_obs_dict[handle] = set(visited)\n\n # Locate observed agents and their coresponding targets\n local_rail_obs = np.zeros((self.view_height, 2 * self.view_width + 1, 16))\n obs_map_state = np.zeros((self.view_height, 2 * self.view_width + 1, 2))\n obs_other_agents_state = np.zeros((self.view_height, 2 * self.view_width + 1, 4))\n _idx = 0\n for pos in visited:\n curr_rel_coord = rel_coords[_idx]\n local_rail_obs[curr_rel_coord[0], curr_rel_coord[1], :] = self.rail_obs[pos[0], pos[1], :]\n if pos == agent.target:\n obs_map_state[curr_rel_coord[0], curr_rel_coord[1], 0] = 1\n else:\n for tmp_agent in agents:\n if pos == tmp_agent.target:\n obs_map_state[curr_rel_coord[0], curr_rel_coord[1], 1] = 1\n if pos != agent.position:\n for tmp_agent in agents:\n if pos == tmp_agent.position:\n obs_other_agents_state[curr_rel_coord[0], curr_rel_coord[1], :] = np.identity(4)[\n tmp_agent.direction]\n\n _idx += 1\n\n direction = np.identity(4)[agent.direction]\n return local_rail_obs, obs_map_state, obs_other_agents_state, direction\n\n def get_many(self, handles: Optional[List[int]] = None) -> Dict[\n int, Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]]:\n \"\"\"\n Called whenever an observation has to be computed for the `env` environment, for each agent with handle\n in the `handles` list.\n \"\"\"\n\n return super().get_many(handles)\n\n def field_of_view(self, position, direction, state=None):\n # Compute the local field of view for an agent in the environment\n data_collection = False\n if state is not None:\n temp_visible_data = np.zeros(shape=(self.view_height, 2 * self.view_width + 1, 16))\n data_collection = True\n if direction == 0:\n origin = (position[0] + self.center, position[1] - self.view_width)\n elif direction == 1:\n origin = (position[0] - self.view_width, position[1] - self.center)\n elif direction == 2:\n origin = (position[0] - self.center, position[1] + self.view_width)\n else:\n origin = (position[0] + self.view_width, position[1] + self.center)\n visible = list()\n rel_coords = list()\n for h in range(self.view_height):\n for w in range(2 * self.view_width + 1):\n if direction == 0:\n if 0 <= origin[0] - h < self.env.height and 0 <= origin[1] + w < self.env.width:\n visible.append((origin[0] - h, origin[1] + w))\n rel_coords.append((h, w))\n # if data_collection:\n # temp_visible_data[h, w, :] = state[origin[0] - h, origin[1] + w, :]\n elif direction == 1:\n if 0 <= origin[0] + w < self.env.height and 0 <= origin[1] + h < self.env.width:\n visible.append((origin[0] + w, origin[1] + h))\n rel_coords.append((h, w))\n # if data_collection:\n # temp_visible_data[h, w, :] = state[origin[0] + w, origin[1] + h, :]\n elif direction == 2:\n if 0 <= origin[0] + h < self.env.height and 0 <= origin[1] - w < self.env.width:\n visible.append((origin[0] + h, origin[1] - w))\n rel_coords.append((h, w))\n # if data_collection:\n # temp_visible_data[h, w, :] = state[origin[0] + h, origin[1] - w, :]\n else:\n if 0 <= origin[0] - w < self.env.height and 0 <= origin[1] - h < self.env.width:\n visible.append((origin[0] - w, origin[1] - h))\n rel_coords.append((h, w))\n # if data_collection:\n # temp_visible_data[h, w, :] = state[origin[0] - w, origin[1] - h, :]\n if data_collection:\n return temp_visible_data\n else:\n return visible, rel_coords\n#endregion" ]
[ [ "numpy.array_equal", "numpy.max", "numpy.delete", "numpy.argmax", "numpy.identity", "numpy.count_nonzero", "numpy.reciprocal", "numpy.array", "numpy.zeros", "numpy.where" ] ]
qrsforever/torchcv
[ "e2e17f730497fb838237357a1df4bf6ca278f107", "e2e17f730497fb838237357a1df4bf6ca278f107" ]
[ "model/det/layers/rpn_detection_layer.py", "model/cls/loss/agent_center_loss.py" ]
[ "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author: Donny You([email protected])\n\n\nimport torch\nimport torch.nn as nn\n\n\nclass RPNDetectionLayer(nn.Module):\n def __init__(self, configer):\n super(RPNDetectionLayer, self).__init__()\n self.configer = configer\n self.num_anchors = self.configer.get('rpn', 'num_anchor_list')\n self.num_features = configer.get('rpn', 'num_feature_list')\n self.rpn_head_index = configer.get('rpn', 'head_index_list')\n\n self.loc_layers = nn.ModuleList()\n self.conf_layers = nn.ModuleList()\n\n for i in range(max(self.rpn_head_index) + 1):\n self.loc_layers.append(\n nn.Conv2d(self.num_features[i], self.num_anchors[i] * 4, kernel_size=1, padding=0)\n )\n self.conf_layers.append(\n nn.Conv2d(self.num_features[i], self.num_anchors[i] * 2, kernel_size=1, padding=0)\n )\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 0.01)\n if m.bias is not None:\n m.bias.data.zero_()\n\n def forward(self, feat_list):\n y_locs = []\n y_confs = []\n\n for i, x in enumerate(feat_list):\n y_loc = self.loc_layers[self.rpn_head_index[i]](x)\n N = y_loc.size(0)\n y_loc = y_loc.permute(0, 2, 3, 1).contiguous()\n y_loc = y_loc.view(N, -1, 4)\n y_locs.append(y_loc)\n\n y_conf = self.conf_layers[self.rpn_head_index[i]](x)\n y_conf = y_conf.permute(0, 2, 3, 1).contiguous()\n y_conf = y_conf.view(N, -1, 2)\n y_confs.append(y_conf)\n\n rpn_locs = torch.cat(y_locs, 1)\n rpn_scores = torch.cat(y_confs, 1)\n\n return rpn_locs, rpn_scores\n", "\"\"\"\r\n@desc: the variety of center loss, which use the class weight as the class center and normalize both the weight and feature,\r\n in this way, the cos distance of weight and feature can be used as the supervised signal.\r\n It's similar with torch.nn.CosineEmbeddingLoss, x_1 means weight_i, x_2 means feature_i.\r\n\"\"\"\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\n\r\nclass AgentCenterLoss(nn.Module):\r\n\r\n def __init__(self, num_classes, feat_dim, scale):\r\n super(AgentCenterLoss, self).__init__()\r\n self.num_classes = num_classes\r\n self.feat_dim = feat_dim\r\n self.scale = scale\r\n\r\n self.centers = nn.Parameter(torch.randn(self.num_classes, self.feat_dim))\r\n\r\n def forward(self, x, labels):\r\n '''\r\n Parameters:\r\n x: input tensor with shape (batch_size, feat_dim)\r\n labels: ground truth label with shape (batch_size)\r\n Return:\r\n loss of centers\r\n '''\r\n cos_dis = F.linear(F.normalize(x), F.normalize(self.centers)) * self.scale\r\n\r\n one_hot = torch.zeros_like(cos_dis)\r\n one_hot.scatter_(1, labels.view(-1, 1), 1.0)\r\n\r\n # loss = 1 - cosine(i)\r\n loss = one_hot * self.scale - (one_hot * cos_dis)\r\n\r\n return loss.mean()\r\n" ]
[ [ "torch.nn.ModuleList", "torch.nn.Conv2d", "torch.cat" ], [ "torch.nn.functional.normalize", "torch.randn", "torch.zeros_like" ] ]
Nikunj-Gupta/voi
[ "ba7e3f887e92ccb97b11172831bdda33b57dbb13" ]
[ "utils/agent.py" ]
[ "import torch\n\nimport utils\nfrom .other import device\nfrom value import VoI\n\n\nclass Agent:\n \"\"\"An agent.\n\n It is able:\n - to choose an action given an observation,\n - to analyze the feedback (i.e. reward and done state) of its action.\"\"\"\n\n def __init__(self, obs_space, action_space, model_dir,\n argmax=False, num_envs=1, use_memory=False, use_text=False, use_hammer=False, learn_voi=False):\n obs_space, self.preprocess_obss = utils.get_obss_preprocessor(obs_space)\n self.acmodel = VoI(obs_space, action_space, use_memory=use_memory, use_text=use_text, use_hammer=use_hammer, learn_voi=learn_voi)\n self.argmax = argmax\n self.num_envs = num_envs\n\n if self.acmodel.recurrent:\n self.memories = torch.zeros(self.num_envs, self.acmodel.memory_size, device=device)\n\n self.acmodel.load_state_dict(utils.get_model_state(model_dir))\n self.acmodel.to(device)\n self.acmodel.eval()\n if hasattr(self.preprocess_obss, \"vocab\"):\n self.preprocess_obss.vocab.load_vocab(utils.get_vocab(model_dir))\n\n def get_actions(self, obss):\n preprocessed_obss = self.preprocess_obss(obss, device=device)\n\n with torch.no_grad():\n if self.acmodel.recurrent:\n dist, _, cost, self.memories = self.acmodel(preprocessed_obss, self.memories)\n else:\n dist, _, cost = self.acmodel(preprocessed_obss)\n\n if self.argmax:\n actions = dist.probs.max(1, keepdim=True)[1]\n else:\n actions = dist.sample()\n\n return actions.cpu().numpy(), cost.cpu().numpy()\n\n def get_action(self, obs):\n return self.get_actions([obs])[0]\n\n def analyze_feedbacks(self, rewards, dones):\n if self.acmodel.recurrent:\n masks = 1 - torch.tensor(dones, dtype=torch.float, device=device).unsqueeze(1)\n self.memories *= masks\n\n def analyze_feedback(self, reward, done):\n return self.analyze_feedbacks([reward], [done])\n" ]
[ [ "torch.tensor", "torch.no_grad", "torch.zeros" ] ]
ucfnlp/summarization-sing-pair-mix
[ "994f6246431255bb2cabbfd515d07c84cf94e870" ]
[ "decode.py" ]
[ "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n# Modifications Copyright 2017 Abigail See\n# Modifications made 2018 by Logan Lebanoff\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#\t\t 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\"\"\"This file contains code to run beam search decoding, including running ROUGE evaluation and producing JSON datafiles for the in-browser attention visualizer, which can be found here https://github.com/abisee/attn_vis\"\"\"\nimport glob\nimport os\nimport time\n\nimport tensorflow as tf\nimport beam_search\nimport data\nimport json\nimport util\nfrom tqdm import tqdm\nfrom absl import flags\nfrom absl import logging\nimport rouge_functions\n\nfrom batcher import create_batch\nimport ssi_functions\n\nFLAGS = flags.FLAGS\n\nSECS_UNTIL_NEW_CKPT = 60\t# max number of seconds before loading new checkpoint\n\n\nclass BeamSearchDecoder(object):\n \"\"\"Beam search decoder.\"\"\"\n\n def __init__(self, model, batcher, vocab):\n \"\"\"Initialize decoder.\n\n Args:\n model: a Seq2SeqAttentionModel object.\n batcher: a Batcher object.\n vocab: Vocabulary object\n \"\"\"\n self._model = model\n self._model.build_graph()\n self._batcher = batcher\n self._vocab = vocab\n self._saver = tf.train.Saver() # we use this to load checkpoints for decoding\n self._sess = tf.Session(config=util.get_config())\n\n # Load an initial checkpoint to use for decoding\n ckpt_path = util.load_ckpt(self._saver, self._sess)\n\n if FLAGS.single_pass:\n # Make a descriptive decode directory name\n ckpt_name = \"ckpt-\" + ckpt_path.split('-')[-1] # this is something of the form \"ckpt-123456\"\n self._decode_dir = os.path.join(FLAGS.log_root, get_decode_dir_name(ckpt_name))\n\n else: # Generic decode dir name\n self._decode_dir = os.path.join(FLAGS.log_root, \"decode\")\n\n # Make the decode dir if necessary\n if not os.path.exists(self._decode_dir): os.makedirs(self._decode_dir)\n\n if FLAGS.single_pass:\n # Make the dirs to contain output written in the correct format for pyrouge\n self._rouge_ref_dir = os.path.join(self._decode_dir, \"reference\")\n if not os.path.exists(self._rouge_ref_dir): os.mkdir(self._rouge_ref_dir)\n self._rouge_dec_dir = os.path.join(self._decode_dir, \"decoded\")\n if not os.path.exists(self._rouge_dec_dir): os.mkdir(self._rouge_dec_dir)\n self._human_dir = os.path.join(self._decode_dir, \"human_readable\")\n if not os.path.exists(self._human_dir): os.mkdir(self._human_dir)\n self._highlight_dir = os.path.join(self._decode_dir, \"highlight\")\n if not os.path.exists(self._highlight_dir): os.mkdir(self._highlight_dir)\n\n\n def decode(self):\n \"\"\"Decode examples until data is exhausted (if FLAGS.single_pass) and return, or decode indefinitely, loading latest checkpoint at regular intervals\"\"\"\n t0 = time.time()\n counter = 0\n total = len(glob.glob(self._batcher._data_path)) * 1000\n pbar = tqdm(total=total)\n while True:\n batch = self._batcher.next_batch()\t# 1 example repeated across batch\n if batch is None: # finished decoding dataset in single_pass mode\n assert FLAGS.single_pass, \"Dataset exhausted, but we are not in single_pass mode\"\n logging.info(\"Decoder has finished reading dataset for single_pass.\")\n logging.info(\"Output has been saved in %s and %s.\", self._rouge_ref_dir, self._rouge_dec_dir)\n if len(os.listdir(self._rouge_ref_dir)) != 0:\n logging.info(\"Now starting ROUGE eval...\")\n results_dict = rouge_functions.rouge_eval(self._rouge_ref_dir, self._rouge_dec_dir)\n rouge_functions.rouge_log(results_dict, self._decode_dir)\n return\n\n original_article = batch.original_articles[0]\t# string\n original_abstract = batch.original_abstracts[0]\t# string\n all_original_abstract_sents = batch.all_original_abstracts_sents[0]\n raw_article_sents = batch.raw_article_sents[0]\n\n article_withunks = data.show_art_oovs(original_article, self._vocab) # string\n abstract_withunks = data.show_abs_oovs(original_abstract, self._vocab, (batch.art_oovs[0] if FLAGS.pointer_gen else None)) # string\n\n decoded_words, decoded_output, best_hyp = decode_example(self._sess, self._model, self._vocab, batch, counter, self._batcher._hps)\n\n if FLAGS.single_pass:\n if counter < 1000:\n self.write_for_human(raw_article_sents, all_original_abstract_sents, decoded_words, counter)\n rouge_functions.write_for_rouge(all_original_abstract_sents, None, counter, self._rouge_ref_dir, self._rouge_dec_dir, decoded_words=decoded_words) # write ref summary and decoded summary to file, to eval with pyrouge later\n if FLAGS.attn_vis:\n self.write_for_attnvis(article_withunks, abstract_withunks, decoded_words, best_hyp.attn_dists, best_hyp.p_gens, counter) # write info to .json file for visualization tool\n\n counter += 1 # this is how many examples we've decoded\n else:\n print_results(article_withunks, abstract_withunks, decoded_output) # log output to screen\n self.write_for_attnvis(article_withunks, abstract_withunks, decoded_words, best_hyp.attn_dists, best_hyp.p_gens, counter) # write info to .json file for visualization tool\n\n # Check if SECS_UNTIL_NEW_CKPT has elapsed; if so return so we can load a new checkpoint\n t1 = time.time()\n if t1-t0 > SECS_UNTIL_NEW_CKPT:\n logging.info('We\\'ve been decoding with same checkpoint for %i seconds. Time to load new checkpoint', t1-t0)\n _ = util.load_ckpt(self._saver, self._sess)\n t0 = time.time()\n pbar.update(1)\n pbar.close()\n\n def decode_iteratively(self, example_generator, total, names_to_types, ssi_list, hps):\n for example_idx, example in enumerate(tqdm(example_generator, total=total)):\n raw_article_sents, groundtruth_similar_source_indices_list, groundtruth_summary_text = util.unpack_tf_example(\n example, names_to_types)\n article_sent_tokens = [util.process_sent(sent) for sent in raw_article_sents]\n groundtruth_summ_sents = [[sent.strip() for sent in groundtruth_summary_text.strip().split('\\n')]]\n\n if ssi_list is None: # this is if we are doing the upper bound evaluation (ssi_list comes straight from the groundtruth)\n sys_ssi = groundtruth_similar_source_indices_list\n if FLAGS.singles_and_pairs == 'singles':\n sys_ssi = util.enforce_sentence_limit(sys_ssi, 1)\n elif FLAGS.singles_and_pairs == 'both':\n sys_ssi = util.enforce_sentence_limit(sys_ssi, 2)\n sys_ssi = util.replace_empty_ssis(sys_ssi, raw_article_sents)\n else:\n gt_ssi, sys_ssi, ext_len = ssi_list[example_idx]\n if FLAGS.singles_and_pairs == 'singles':\n sys_ssi = util.enforce_sentence_limit(sys_ssi, 1)\n groundtruth_similar_source_indices_list = util.enforce_sentence_limit(groundtruth_similar_source_indices_list, 1)\n gt_ssi = util.enforce_sentence_limit(gt_ssi, 1)\n elif FLAGS.singles_and_pairs == 'both':\n sys_ssi = util.enforce_sentence_limit(sys_ssi, 2)\n groundtruth_similar_source_indices_list = util.enforce_sentence_limit(groundtruth_similar_source_indices_list, 2)\n gt_ssi = util.enforce_sentence_limit(gt_ssi, 2)\n if gt_ssi != groundtruth_similar_source_indices_list:\n print('Warning: Example %d has different groundtruth source indices: ' + str(groundtruth_similar_source_indices_list) + ' || ' + str(gt_ssi))\n if FLAGS.dataset_name == 'xsum':\n sys_ssi = [sys_ssi[0]]\n\n final_decoded_words = []\n final_decoded_outpus = ''\n best_hyps = []\n highlight_html_total = ''\n for ssi_idx, ssi in enumerate(sys_ssi):\n selected_raw_article_sents = util.reorder(raw_article_sents, ssi)\n selected_article_text = ' '.join( [' '.join(sent) for sent in util.reorder(article_sent_tokens, ssi)] )\n selected_doc_indices_str = '0 ' * len(selected_article_text.split())\n if FLAGS.upper_bound:\n selected_groundtruth_summ_sent = [[groundtruth_summ_sents[0][ssi_idx]]]\n else:\n selected_groundtruth_summ_sent = groundtruth_summ_sents\n\n batch = create_batch(selected_article_text, selected_groundtruth_summ_sent, selected_doc_indices_str, selected_raw_article_sents, FLAGS.batch_size, hps, self._vocab)\n\n decoded_words, decoded_output, best_hyp = decode_example(self._sess, self._model, self._vocab, batch, example_idx, hps)\n best_hyps.append(best_hyp)\n final_decoded_words.extend(decoded_words)\n final_decoded_outpus += decoded_output\n\n if example_idx < 1000:\n min_matched_tokens = 2\n selected_article_sent_tokens = [util.process_sent(sent) for sent in selected_raw_article_sents]\n highlight_summary_sent_tokens = [decoded_words]\n highlight_ssi_list, lcs_paths_list, highlight_smooth_article_lcs_paths_list = ssi_functions.get_simple_source_indices_list(\n highlight_summary_sent_tokens,\n selected_article_sent_tokens, None, 2, min_matched_tokens)\n highlighted_html = ssi_functions.html_highlight_sents_in_article(highlight_summary_sent_tokens,\n highlight_ssi_list,\n selected_article_sent_tokens,\n lcs_paths_list=lcs_paths_list,\n article_lcs_paths_list=highlight_smooth_article_lcs_paths_list)\n highlight_html_total += '<u>System Summary</u><br><br>' + highlighted_html + '<br><br>'\n\n if len(final_decoded_words) >= 100:\n break\n\n if example_idx < 1000:\n self.write_for_human(raw_article_sents, groundtruth_summ_sents, final_decoded_words, example_idx)\n ssi_functions.write_highlighted_html(highlight_html_total, self._highlight_dir, example_idx)\n\n rouge_functions.write_for_rouge(groundtruth_summ_sents, None, example_idx, self._rouge_ref_dir, self._rouge_dec_dir, decoded_words=final_decoded_words, log=False) # write ref summary and decoded summary to file, to eval with pyrouge later\n example_idx += 1 # this is how many examples we've decoded\n\n logging.info(\"Decoder has finished reading dataset for single_pass.\")\n logging.info(\"Output has been saved in %s and %s.\", self._rouge_ref_dir, self._rouge_dec_dir)\n if len(os.listdir(self._rouge_ref_dir)) != 0:\n l_param = 100\n logging.info(\"Now starting ROUGE eval...\")\n results_dict = rouge_functions.rouge_eval(self._rouge_ref_dir, self._rouge_dec_dir, l_param=l_param)\n rouge_functions.rouge_log(results_dict, self._decode_dir)\n\n\n\n def write_for_human(self, raw_article_sents, all_reference_sents, decoded_words, ex_index):\n\n decoded_sents = []\n while len(decoded_words) > 0:\n try:\n fst_period_idx = decoded_words.index(\".\")\n except ValueError: # there is text remaining that doesn't end in \".\"\n fst_period_idx = len(decoded_words)\n sent = decoded_words[:fst_period_idx+1] # sentence up to and including the period\n decoded_words = decoded_words[fst_period_idx+1:] # everything else\n decoded_sents.append(' '.join(sent))\n\n # pyrouge calls a perl script that puts the data into HTML files.\n # Therefore we need to make our output HTML safe.\n decoded_sents = [make_html_safe(w) for w in decoded_sents]\n all_reference_sents = [[make_html_safe(w) for w in abstract] for abstract in all_reference_sents]\n\n # Write to file\n human_file = os.path.join(self._human_dir, '%06d_human.txt' % ex_index)\n\n with open(human_file, \"w\") as f:\n f.write('Human Summary:\\n--------------------------------------------------------------\\n')\n for abs_idx, abs in enumerate(all_reference_sents):\n for idx,sent in enumerate(abs):\n f.write(sent+\"\\n\")\n f.write('\\nSystem Summary:\\n--------------------------------------------------------------\\n')\n for sent in decoded_sents:\n f.write(sent + '\\n')\n f.write('\\nArticle:\\n--------------------------------------------------------------\\n')\n for sent in raw_article_sents:\n f.write(sent + '\\n')\n\n def write_for_attnvis(self, article, abstract, decoded_words, attn_dists, p_gens, ex_index, ssi=None):\n \"\"\"Write some data to json file, which can be read into the in-browser attention visualizer tool:\n https://github.com/abisee/attn_vis\n\n Args:\n article: The original article string.\n abstract: The human (correct) abstract string.\n attn_dists: List of arrays; the attention distributions.\n decoded_words: List of strings; the words of the generated summary.\n p_gens: List of scalars; the p_gen values. If not running in pointer-generator mode, list of None.\n \"\"\"\n article_lst = article.split() # list of words\n decoded_lst = decoded_words # list of decoded words\n to_write = {\n 'article_lst': [make_html_safe(t) for t in article_lst],\n 'decoded_lst': [make_html_safe(t) for t in decoded_lst],\n 'abstract_str': make_html_safe(abstract),\n 'attn_dists': attn_dists\n }\n if FLAGS.pointer_gen:\n to_write['p_gens'] = p_gens\n if ssi is not None:\n to_write['ssi'] = ssi\n util.create_dirs(os.path.join(self._decode_dir, 'attn_vis_data'))\n output_fname = os.path.join(self._decode_dir, 'attn_vis_data', '%06d.json' % ex_index)\n with open(output_fname, 'w') as output_file:\n json.dump(to_write, output_file)\n # logging.info('Wrote visualization data to %s', output_fname)\n\ndef decode_example(sess, model, vocab, batch, counter, hps):\n # Run beam search to get best Hypothesis\n best_hyp = beam_search.run_beam_search(sess, model, vocab, batch, counter, hps)\n\n # Extract the output ids from the hypothesis and convert back to words\n output_ids = [int(t) for t in best_hyp.tokens[1:]]\n decoded_words = data.outputids2words(output_ids, vocab, (batch.art_oovs[0] if FLAGS.pointer_gen else None))\n\n # Remove the [STOP] token from decoded_words, if necessary\n try:\n fst_stop_idx = decoded_words.index(data.STOP_DECODING) # index of the (first) [STOP] symbol\n decoded_words = decoded_words[:fst_stop_idx]\n except ValueError:\n decoded_words = decoded_words\n decoded_output = ' '.join(decoded_words) # single string\n return decoded_words, decoded_output, best_hyp\n\n\ndef print_results(article, abstract, decoded_output):\n \"\"\"Prints the article, the reference summmary and the decoded summary to screen\"\"\"\n print(\"\")\n logging.info('ARTICLE:\t%s', article)\n logging.info('REFERENCE SUMMARY: %s', abstract)\n logging.info('GENERATED SUMMARY: %s', decoded_output)\n print(\"\")\n\n\ndef make_html_safe(s):\n \"\"\"Replace any angled brackets in string s to avoid interfering with HTML attention visualizer.\"\"\"\n s.replace(\"<\", \"&lt;\")\n s.replace(\">\", \"&gt;\")\n return s\n\n\ndef get_decode_dir_name(ckpt_name):\n \"\"\"Make a descriptive name for the decode dir, including the name of the checkpoint we use to decode. This is called in single_pass mode.\"\"\"\n\n if \"train\" in FLAGS.data_path: dataset = \"train\"\n elif \"val\" in FLAGS.data_path: dataset = \"val\"\n elif \"test\" in FLAGS.data_path: dataset = \"test\"\n else: raise ValueError(\"FLAGS.data_path %s should contain one of train, val or test\" % (FLAGS.data_path))\n dirname = \"decode_%s_%imaxenc_%ibeam_%imindec_%imaxdec\" % (dataset, FLAGS.max_enc_steps, FLAGS.beam_size, FLAGS.min_dec_steps, FLAGS.max_dec_steps)\n if ckpt_name is not None:\n dirname += \"_%s\" % ckpt_name\n return dirname\n" ]
[ [ "tensorflow.train.Saver" ] ]
nibrunie/thegameia
[ "e320aef799da44d61087099527c57dc3a518e6bd" ]
[ "strategy/nn_utils.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport numpy as np\n\n\ndef value_to_one_hot(value):\n \"\"\" covert index @p value to a one-hot vector of size 60 (card state)\n encoding index \"\"\"\n vector = new_empty_vector()\n vector[value-1] = 1\n return vector\n\ndef new_empty_vector():\n return np.zeros(60)\n\ndef stack_state_to_vector(stack_state):\n assert len(stack_state) == 2\n vector = np.zeros(2 * 60)\n for index, card in enumerate(stack_state):\n vector[index * 60 + card.value - 1] = 1\n return vector\n\ndef full_state_to_vector(state):\n \"\"\" Translate a list of [increasing stack top, decreasing stack top, hand cards]\n to the concatenation of 8 60-wide one hot vectors \"\"\"\n # complementary vector completes hand to 6 cards\n complementary_vector = new_empty_vector() * (8 - len(state))\n return sum([value_to_one_hot(card.value) for card in state], []) + complementary_vector\n" ]
[ [ "numpy.zeros" ] ]
odidev/mpld3
[ "7bb37b9a9e6d1c90dd9f83075d1987541bb087d5", "7bb37b9a9e6d1c90dd9f83075d1987541bb087d5" ]
[ "mpld3/test_plots/test_mouse_events.py", "examples/linked_brush.py" ]
[ "\"\"\"Plot to test mouse events\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport mpld3, mpld3.plugins as plugins\n\nrandom_x = [0.037984906849671374, 0.5880357008425118, 0.47736125281329767, 0.010304252492200239, 0.35796828706754447, 0.23109561146897417, 0.8631302372372742, 0.13444834717909937, 0.5056397861230668, 0.024528122585731227, 0.5372864367524129, 0.058924358084960105, 0.2631680487666277, 0.6814702489039445, 0.11034531955119298, 0.4299675665498215, 0.0631667742233506, 0.10316683922592784, 0.19692341232102673, 0.3353885162702046, 0.9152346663864552, 0.11198196158519313, 0.8799975132010748, 0.7960293867412321, 0.9295540537314296, 0.3958725715755408, 0.035255608999481325, 0.0054287463568508665, 0.7517682039494487, 0.5385301522985431, 0.30208986270541394, 0.18467091269007285, 0.6218806664279364, 0.6877500188861776, 0.546811722807477, 0.3140703221286578, 0.989234786215092, 0.41888939305739137, 0.33314667920077945, 0.345491646148014, 0.6755566139855378, 0.955322435733609, 0.8673785689480379, 0.31111198199765544, 0.025862944203813854, 0.8359219522933756, 0.47622910878639735, 0.41210620978548884, 0.9941003162789824, 0.17550975368294885]\n\nrandom_y = [0.45402157945566135, 0.16864929140625728, 0.5111076100380816, 0.41026380763175285, 0.3971396415356726, 0.5812543312682149, 0.32639546372485917, 0.9794503784387796, 0.5393582722581963, 0.49968700001151, 0.13357111737556648, 0.9563556753027254, 0.3734508445972159, 0.3644342446362956, 0.32761929072245144, 0.12402062932059743, 0.872807150749212, 0.844186788071371, 0.37936922460029165, 0.18200905951561552, 0.779773690605089, 0.5963142521743686, 0.5522500805846032, 0.051824827070525936, 0.06473610523722362, 0.04522228562224817, 0.8933476377595784, 0.4748328124416784, 0.1520450481465807, 0.8200682148351869, 0.4581154746719148, 0.8991510174008752, 0.33249486911216286, 0.8320338099832485, 0.8549033533974582, 0.16978769781277792, 0.2315533412315509, 0.037676231224115564, 0.3719505107401978, 0.37076483058680243, 0.774208501240394, 0.5930470039583583, 0.15492566806379704, 0.43094178354006774, 0.6257337718514595, 0.5325297011058135, 0.5360600203459467, 0.43296583733953886, 0.35999596815150825, 0.43044674586992837] \n\n\nclass ClickInfo(plugins.PluginBase):\n \"\"\"Plugin for getting info on click\"\"\"\n\n JAVASCRIPT = \"\"\"\n mpld3.register_plugin(\"clickinfo\", ClickInfo);\n ClickInfo.prototype = Object.create(mpld3.Plugin.prototype);\n ClickInfo.prototype.constructor = ClickInfo;\n ClickInfo.prototype.requiredProps = [\"id\"];\n function ClickInfo(fig, props){\n mpld3.Plugin.call(this, fig, props);\n };\n\n ClickInfo.prototype.draw = function(){\n var obj = mpld3.get_element(this.props.id);\n obj.elements().on(\"click\",\n function(d, i){alert(\"clicked on points[\" + i + \"]\");});\n }\n \"\"\"\n def __init__(self, points):\n self.dict_ = {\"type\": \"clickinfo\",\n \"id\": mpld3.utils.get_id(points)}\n\ndef create_plot():\n fig, ax = plt.subplots()\n points = ax.scatter(random_x, random_y, \n s=500, alpha=0.3)\n\n plugins.clear(fig)\n ax.set_title('Click info', size=14)\n plugins.connect(fig, plugins.Reset(), plugins.Zoom(), ClickInfo(points))\n return fig\n\n\ndef test_mouse_events():\n fig = create_plot()\n html = mpld3.fig_to_html(fig)\n plt.close(fig)\n\n\nif __name__ == \"__main__\":\n mpld3.show(create_plot())\n", "\"\"\"\nLinked Brushing Example\n=======================\nThis example uses the standard Iris dataset and plots it with a linked brushing\ntool for dynamically exploring the data. The paintbrush button at the bottom\nleft can be used to enable and disable the behavior.\n\"\"\"\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_iris\n\nimport mpld3\nfrom mpld3 import plugins, utils\n\n\ndata = load_iris()\nX = data.data\ny = data.target\n\n# dither the data for clearer plotting\nX += 0.1 * np.random.random(X.shape)\n\nfig, ax = plt.subplots(4, 4, sharex=\"col\", sharey=\"row\", figsize=(8, 8))\nfig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95,\n hspace=0.1, wspace=0.1)\n\nfor i in range(4):\n for j in range(4):\n points = ax[3 - i, j].scatter(X[:, j], X[:, i],\n c=y, s=40, alpha=0.6)\n\n# remove tick labels\nfor axi in ax.flat:\n for axis in [axi.xaxis, axi.yaxis]:\n axis.set_major_formatter(plt.NullFormatter())\n\n# Here we connect the linked brush plugin\nplugins.connect(fig, plugins.LinkedBrush(points))\n\nmpld3.show()\n" ]
[ [ "matplotlib.pyplot.subplots", "matplotlib.pyplot.close" ], [ "matplotlib.pyplot.NullFormatter", "numpy.random.random", "sklearn.datasets.load_iris", "matplotlib.pyplot.subplots" ] ]
MRXLT/PaddleHub
[ "f92d0edd18057044ef248d7f2c42d8f347b62fbf" ]
[ "demo/senta/predict.py" ]
[ "#coding:utf-8\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport ast\nimport numpy as np\nimport os\nimport time\n\nimport paddle\nimport paddle.fluid as fluid\nimport paddlehub as hub\n\n# yapf: disable\nparser = argparse.ArgumentParser(__doc__)\nparser.add_argument(\"--checkpoint_dir\", type=str, default=None, help=\"Directory to model checkpoint\")\nparser.add_argument(\"--use_gpu\", type=ast.literal_eval, default=True, help=\"Whether use GPU for finetuning, input should be True or False\")\nparser.add_argument(\"--use_pyreader\", type=ast.literal_eval, default=False, help=\"Whether use pyreader to feed data.\")\nargs = parser.parse_args()\n# yapf: enable.\n\nif __name__ == '__main__':\n # loading Paddlehub senta pretrained model\n module = hub.Module(name=\"senta_bilstm\")\n inputs, outputs, program = module.context(trainable=True)\n\n # Sentence classification dataset reader\n dataset = hub.dataset.ChnSentiCorp()\n reader = hub.reader.LACClassifyReader(\n dataset=dataset, vocab_path=module.get_vocab_path())\n\n strategy = hub.AdamWeightDecayStrategy(\n weight_decay=0.01,\n warmup_proportion=0.1,\n learning_rate=5e-5,\n lr_scheduler=\"linear_decay\",\n optimizer_name=\"adam\")\n\n config = hub.RunConfig(\n use_data_parallel=False,\n use_pyreader=args.use_pyreader,\n use_cuda=args.use_gpu,\n batch_size=1,\n enable_memory_optim=False,\n checkpoint_dir=args.checkpoint_dir,\n strategy=strategy)\n\n sent_feature = outputs[\"sentence_feature\"]\n\n feed_list = [inputs[\"words\"].name]\n\n cls_task = hub.TextClassifierTask(\n data_reader=reader,\n feature=sent_feature,\n feed_list=feed_list,\n num_classes=dataset.num_labels,\n config=config)\n\n data = [\"这家餐厅很好吃\", \"这部电影真的很差劲\"]\n\n run_states = cls_task.predict(data=data)\n results = [run_state.run_results for run_state in run_states]\n index = 0\n for batch_result in results:\n batch_result = np.argmax(batch_result, axis=2)[0]\n for result in batch_result:\n print(\"%s\\tpredict=%s\" % (data[index], result))\n index += 1\n" ]
[ [ "numpy.argmax" ] ]
DarkContact/m.css
[ "a56227e89de90d0ea5751d0ebfa96734a5e55b96" ]
[ "plugins/m/plots.py" ]
[ "#\n# This file is part of m.css.\n#\n# Copyright © 2017, 2018, 2019 Vladimír Vondruš <[email protected]>\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n#\n\nimport re\n\nfrom docutils import nodes, utils\nfrom docutils.parsers import rst\nfrom docutils.parsers.rst import directives\nfrom docutils.parsers.rst.roles import set_classes\n\nimport matplotlib as mpl\nmpl.use('Agg') # otherwise it will attempt to use X11\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport io\n\nmpl.rcParams['font.size'] = '11'\nmpl.rcParams['axes.titlesize'] = '13'\n\n# Plot background. Replaced with .m-plot .m-background later, equivalent to\n# --default-filled-background-color\nmpl.rcParams['axes.facecolor'] = '#cafe01'\n\n# All of these should match --color, replaced with .m-plot .m-text\nmpl.rcParams['text.color'] = '#cafe02'\nmpl.rcParams['axes.labelcolor'] = '#cafe02'\nmpl.rcParams['xtick.color'] = '#cafe02'\nmpl.rcParams['ytick.color'] = '#cafe02'\n\n# no need to have a border around the plot\nmpl.rcParams['axes.spines.left'] = False\nmpl.rcParams['axes.spines.right'] = False\nmpl.rcParams['axes.spines.top'] = False\nmpl.rcParams['axes.spines.bottom'] = False\n\nmpl.rcParams['svg.fonttype'] = 'none' # otherwise it renders text to paths\nmpl.rcParams['figure.autolayout'] = True # so it relayouts everything to fit\n\n# Gets increased for every graph on a page to (hopefully) ensure unique SVG IDs\nmpl.rcParams['svg.hashsalt'] = 0\n\n# Color codes for bars. Keep in sync with latex2svgextra.\nstyle_mapping = {\n 'default': '#cafe03',\n 'primary': '#cafe04',\n 'success': '#cafe05',\n 'warning': '#cafe06',\n 'danger': '#cafe07',\n 'info': '#cafe08',\n 'dim': '#cafe09'\n}\n\n# Patch to remove preamble and hardcoded sizes. Matplotlib 2.2 has a http URL\n# while matplotlib 3 has a https URL, check for both.\n_patch_src = re.compile(r\"\"\"<\\?xml version=\"1\\.0\" encoding=\"utf-8\" standalone=\"no\"\\?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1\\.1//EN\"\n \"http://www\\.w3\\.org/Graphics/SVG/1\\.1/DTD/svg11\\.dtd\">\n<!-- Created with matplotlib \\(https?://matplotlib.org/\\) -->\n<svg height=\"\\d+(\\.\\d+)?pt\" version=\"1.1\" (?P<viewBox>viewBox=\"0 0 \\d+ \\d+(\\.\\d+)?\") width=\"\\d+(\\.\\d+)?pt\" xmlns=\"http://www\\.w3\\.org/2000/svg\" xmlns:xlink=\"http://www\\.w3\\.org/1999/xlink\">\n\"\"\")\n_patch_dst = r\"\"\"<svg \\g<viewBox>>\n\"\"\"\n\n# Remove needless newlines and trailing space in path data\n_path_patch_src = re.compile('(?P<prev>[\\\\dz]) ?\\n(?P<next>[LMz])', re.MULTILINE)\n_path_patch_dst = '\\\\g<prev> \\\\g<next>'\n_path_patch2_src = re.compile(' ?\\n\"')\n_path_patch2_dst = '\"'\n\n# Mapping from color codes to CSS classes\n_class_mapping = [\n # Graph background\n ('style=\"fill:#cafe01;\"', 'class=\"m-background\"'),\n\n # Tick <path> definition in <defs>\n ('style=\"stroke:#cafe02;stroke-width:0.8;\"', 'class=\"m-line\"'),\n # <use>, everything is defined in <defs>, no need to repeat\n ('<use style=\"fill:#cafe02;stroke:#cafe02;stroke-width:0.8;\"', '<use'),\n\n # Label text on left\n ('style=\"fill:#cafe02;font-family:{font};font-size:11px;font-style:normal;font-weight:normal;\"', 'class=\"m-label\"'),\n # Label text on bottom (has extra style params)\n ('style=\"fill:#cafe02;font-family:{font};font-size:11px;font-style:normal;font-weight:normal;', 'class=\"m-label\" style=\"'),\n # Secondary label text\n ('style=\"fill:#cafe0b;font-family:{font};font-size:11px;font-style:normal;font-weight:normal;\"', 'class=\"m-label m-dim\"'),\n # Title text\n ('style=\"fill:#cafe02;font-family:{font};font-size:13px;font-style:normal;font-weight:normal;', 'class=\"m-title\" style=\"'),\n\n # Bar colors. Keep in sync with latex2svgextra.\n ('style=\"fill:#cafe03;\"', 'class=\"m-bar m-default\"'),\n ('style=\"fill:#cafe04;\"', 'class=\"m-bar m-primary\"'),\n ('style=\"fill:#cafe05;\"', 'class=\"m-bar m-success\"'),\n ('style=\"fill:#cafe06;\"', 'class=\"m-bar m-warning\"'),\n ('style=\"fill:#cafe07;\"', 'class=\"m-bar m-danger\"'),\n ('style=\"fill:#cafe08;\"', 'class=\"m-bar m-info\"'),\n ('style=\"fill:#cafe09;\"', 'class=\"m-bar m-dim\"'),\n\n # Error bar line\n ('style=\"fill:none;stroke:#cafe0a;stroke-width:1.5;\"', 'class=\"m-error\"'),\n # Error bar <path> definition in <defs>\n ('style=\"stroke:#cafe0a;\"', 'class=\"m-error\"'),\n # <use>, everything is defined in <defs>, no need to repeat\n ('<use style=\"fill:#cafe0a;stroke:#cafe0a;\"', '<use'),\n]\n\n# Titles for bars\n_bar_titles_src = '<g id=\"plot{}-value{}-{}\">'\n_bar_titles_dst = '<g id=\"plot{}-value{}-{}\"><title>{} {}</title>'\n_bar_titles_dst_error = '<g id=\"plot{}-value{}-{}\"><title>{} ± {} {}</title>'\n\nclass Plot(rst.Directive):\n required_arguments = 1\n optional_arguments = 0\n final_argument_whitespace = True\n option_spec = {'class': directives.class_option,\n 'name': directives.unchanged,\n 'type': directives.unchanged_required,\n 'labels': directives.unchanged_required,\n 'labels_extra': directives.unchanged,\n 'units': directives.unchanged_required,\n 'values': directives.unchanged_required,\n 'errors': directives.unchanged,\n 'colors': directives.unchanged,\n 'bar_height': directives.unchanged}\n has_content = False\n\n def run(self):\n set_classes(self.options)\n\n # Type\n assert self.options['type'] == 'barh'\n\n # Graph title and axis labels. Value labels are one per line.\n title = self.arguments[0]\n units = self.options['units']\n labels = self.options['labels'].split('\\n')\n\n # Optional extra labels\n if 'labels_extra' in self.options:\n labels_extra = self.options['labels_extra'].split('\\n')\n assert len(labels_extra) == len(labels)\n else:\n labels_extra = None\n\n # Values. Should be one for each label, if there are multiple lines\n # then the values get stacked.\n value_sets = []\n for row in self.options['values'].split('\\n'):\n values = [float(v) for v in row.split()]\n assert len(values) == len(labels)\n value_sets += [values]\n\n # Optional errors\n if 'errors' in self.options:\n error_sets = []\n for row in self.options['errors'].split('\\n'):\n errors = [float(e) for e in row.split()]\n assert len(errors) == len(values)\n error_sets += [errors]\n assert len(error_sets) == len(value_sets)\n else:\n error_sets = [None]*len(value_sets)\n\n # Colors. Should be either one for all or one for every value\n if 'colors' in self.options:\n color_sets = []\n for row in self.options['colors'].split('\\n'):\n colors = [style_mapping[c] for c in row.split()]\n if len(colors) == 1: colors = colors[0]\n else: assert len(colors) == len(labels)\n color_sets += [colors]\n assert len(color_sets) == len(value_sets)\n else:\n color_sets = [style_mapping['default']]*len(value_sets)\n\n # Bar height\n bar_height = float(self.options.get('bar_height', '0.4'))\n\n # Increase hashsalt for every plot to ensure (hopefully) unique SVG IDs\n mpl.rcParams['svg.hashsalt'] = int(mpl.rcParams['svg.hashsalt']) + 1\n\n # Setup the graph\n fig, ax = plt.subplots()\n # TODO: let matplotlib calculate the height somehow\n fig.set_size_inches(8, 0.78 + len(labels)*bar_height)\n yticks = np.arange(len(labels))\n left = np.array([0.0]*len(labels))\n for i in range(len(value_sets)):\n plot = ax.barh(yticks, value_sets[i], xerr=error_sets[i],\n align='center', color=color_sets[i], ecolor='#cafe0a', capsize=5*bar_height/0.4, left=left)\n left += np.array(value_sets[i])\n for j, v in enumerate(plot):\n v.set_gid('plot{}-value{}-{}'.format(mpl.rcParams['svg.hashsalt'], i, j))\n ax.set_yticks(yticks)\n ax.invert_yaxis() # top-to-bottom\n ax.set_xlabel(units)\n ax.set_title(title)\n\n # Value labels. If extra label is specified, create two multiline texts\n # with first having the second line empty and second having the first\n # line empty.\n if labels_extra:\n ax.set_yticklabels([y + ('' if labels_extra[i] == '..' else '\\n') for i, y in enumerate(labels)])\n for i, label in enumerate(ax.get_yticklabels()):\n if labels_extra[i] == '..': continue\n ax.text(0, i + 0.05, '\\n' + labels_extra[i],\n va='center', ha='right',\n transform=label.get_transform(), color='#cafe0b')\n else: ax.set_yticklabels(labels)\n\n # Export to SVG\n fig.patch.set_visible(False) # hide the white background\n imgdata = io.StringIO()\n fig.savefig(imgdata, format='svg')\n plt.close() # otherwise it consumes a lot of memory in autoreload mode\n\n # Patch the rendered output: remove preable and hardcoded size\n imgdata = _patch_src.sub(_patch_dst, imgdata.getvalue())\n # Remove needless newlines and trailing whitespace in path data\n imgdata = _path_patch2_src.sub(_path_patch2_dst, _path_patch_src.sub(_path_patch_dst, imgdata))\n # Replace color codes with CSS classes\n for src, dst in _class_mapping: imgdata = imgdata.replace(src, dst)\n # Add titles for bars\n for i in range(len(value_sets)):\n for j in range(len(labels)):\n id = i*len(labels) + j\n if error_sets[i]: imgdata = imgdata.replace(\n _bar_titles_src.format(mpl.rcParams['svg.hashsalt'], i, j),\n _bar_titles_dst_error.format(mpl.rcParams['svg.hashsalt'], i, j, value_sets[i][j], error_sets[i][j], units))\n else: imgdata = imgdata.replace(\n _bar_titles_src.format(mpl.rcParams['svg.hashsalt'], i, j),\n _bar_titles_dst.format(mpl.rcParams['svg.hashsalt'], i, j, value_sets[i][j], units))\n\n container = nodes.container(**self.options)\n container['classes'] += ['m-plot']\n node = nodes.raw('', imgdata, format='html')\n container.append(node)\n return [container]\n\ndef new_page(*args, **kwargs):\n mpl.rcParams['svg.hashsalt'] = 0\n\ndef register_mcss(mcss_settings, hooks_pre_page, **kwargs):\n font = mcss_settings.get('M_PLOTS_FONT', 'Source Sans Pro')\n for i in range(len(_class_mapping)):\n src, dst = _class_mapping[i]\n _class_mapping[i] = (src.format(font=font), dst)\n mpl.rcParams['font.family'] = font\n\n hooks_pre_page += [new_page]\n\n rst.directives.register_directive('plot', Plot)\n\n# Below is only Pelican-specific functionality. If Pelican is not found, these\n# do nothing.\n\ndef _pelican_configure(pelicanobj):\n register_mcss(mcss_settings=pelicanobj.settings, hooks_pre_page=[])\n\ndef register(): # for Pelican\n import pelican.signals\n\n pelican.signals.initialized.connect(_pelican_configure)\n pelican.signals.content_object_init.connect(new_page)\n" ]
[ [ "matplotlib.use", "numpy.array", "matplotlib.pyplot.subplots", "matplotlib.pyplot.close" ] ]
qianpeisheng/SRFBN_CVPR19
[ "6ace659b743cea7ae1fc20ba4a505ee2fd7c75f9" ]
[ "networks/edsr_arch.py" ]
[ "# Enhanced Deep Residual Networks for Single Image Super-Resolution\n# https://arxiv.org/abs/1707.02921\n\nimport math\n\nimport torch\nimport torch.nn as nn\n\ndef default_conv(in_channels, out_channels, kernel_size, bias=True):\n return nn.Conv2d(\n in_channels, out_channels, kernel_size,\n padding=(kernel_size//2), bias=bias)\n\nclass MeanShift(nn.Conv2d):\n def __init__(\n self, rgb_range=255,\n rgb_mean=(0.4488, 0.4371, 0.4040), rgb_std=(1.0, 1.0, 1.0), sign=-1):\n\n super(MeanShift, self).__init__(3, 3, kernel_size=1)\n std = torch.Tensor(rgb_std)\n self.weight.data = torch.eye(3).view(3, 3, 1, 1) / std.view(3, 1, 1, 1)\n self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean) / std\n for p in self.parameters():\n p.requires_grad = False\n\nclass BasicBlock(nn.Sequential):\n def __init__(\n self, conv, in_channels, out_channels, kernel_size, stride=1, bias=False,\n bn=True, act=nn.ReLU(True)):\n\n m = [conv(in_channels, out_channels, kernel_size, bias=bias)]\n if bn:\n m.append(nn.BatchNorm2d(out_channels))\n if act is not None:\n m.append(act)\n\n super(BasicBlock, self).__init__(*m)\n\nclass ResBlock(nn.Module):\n def __init__(\n self, conv, n_feats, kernel_size,\n bias=True, bn=False, act=nn.ReLU(True), res_scale=1):\n\n super(ResBlock, self).__init__()\n m = []\n for i in range(2):\n m.append(conv(n_feats, n_feats, kernel_size, bias=bias))\n if bn:\n m.append(nn.BatchNorm2d(n_feats))\n if i == 0:\n m.append(act)\n\n self.body = nn.Sequential(*m)\n self.res_scale = res_scale\n\n def forward(self, x):\n res = self.body(x).mul(self.res_scale)\n res += x\n\n return res\n\nclass Upsampler(nn.Sequential):\n def __init__(self, conv, scale, n_feats, bn=False, act=False, bias=True):\n\n m = []\n if (scale & (scale - 1)) == 0: # Is scale = 2^n?\n for _ in range(int(math.log(scale, 2))):\n m.append(conv(n_feats, 4 * n_feats, 3, bias))\n m.append(nn.PixelShuffle(2))\n if bn:\n m.append(nn.BatchNorm2d(n_feats))\n if act == 'relu':\n m.append(nn.ReLU(True))\n elif act == 'prelu':\n m.append(nn.PReLU(n_feats))\n\n elif scale == 3:\n m.append(conv(n_feats, 9 * n_feats, 3, bias))\n m.append(nn.PixelShuffle(3))\n if bn:\n m.append(nn.BatchNorm2d(n_feats))\n if act == 'relu':\n m.append(nn.ReLU(True))\n elif act == 'prelu':\n m.append(nn.PReLU(n_feats))\n else:\n raise NotImplementedError\n\n super(Upsampler, self).__init__(*m)\n\nclass EDSR(nn.Module):\n def __init__(self, in_channels, out_channels, num_features, num_blocks, res_scale, upscale_factor, conv=default_conv):\n super(EDSR, self).__init__()\n\n n_resblocks = num_blocks\n n_feats = num_features\n kernel_size = 3 \n scale = upscale_factor\n act = nn.ReLU(True)\n self.sub_mean = MeanShift()\n self.add_mean = MeanShift(sign=1)\n\n # define head module\n m_head = [conv(in_channels, n_feats, kernel_size)]\n\n # define body module\n m_body = [\n ResBlock(\n conv, n_feats, kernel_size, act=act, res_scale=res_scale\n ) for _ in range(n_resblocks)\n ]\n m_body.append(conv(n_feats, n_feats, kernel_size))\n\n # define tail module\n m_tail = [\n Upsampler(conv, scale, n_feats, act=False),\n conv(n_feats, out_channels, kernel_size)\n ]\n\n self.head = nn.Sequential(*m_head)\n self.body = nn.Sequential(*m_body)\n self.tail = nn.Sequential(*m_tail)\n\n def forward(self, x):\n x = self.sub_mean(x)\n x = self.head(x)\n\n res = self.body(x)\n res += x\n\n x = self.tail(res)\n x = self.add_mean(x)\n\n return x \n\n def load_state_dict(self, state_dict, strict=True):\n own_state = self.state_dict()\n for name, param in state_dict.items():\n if name in own_state:\n if isinstance(param, nn.Parameter):\n param = param.data\n try:\n own_state[name].copy_(param)\n except Exception:\n if name.find('tail') == -1:\n raise RuntimeError('While copying the parameter named {}, '\n 'whose dimensions in the model are {} and '\n 'whose dimensions in the checkpoint are {}.'\n .format(name, own_state[name].size(), param.size()))\n elif strict:\n if name.find('tail') == -1:\n raise KeyError('unexpected key \"{}\" in state_dict'\n .format(name))\n\n" ]
[ [ "torch.nn.Sequential", "torch.Tensor", "torch.nn.PReLU", "torch.nn.Conv2d", "torch.eye", "torch.nn.PixelShuffle", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ] ]
gabrielesartor/td_learning_maze
[ "c7b561c88b68eee3f87aa723ab182c592ebc440a" ]
[ "td_learning_maze.py" ]
[ "import sys\nimport numpy as np\nimport math\nimport random\nimport time\nimport matplotlib.pyplot as plt\nimport pickle\n\nimport gym\nimport gym_maze\n\n\"\"\"\nImplementation of TD methods for the maze environment.\n(you can find the environment here: https://github.com/MattChanTK/gym-maze)\n\"\"\"\n\n#Simulation parameters\nNUM_EPISODES = 10000\nMAX_T = 100\nALPHA = 0.5\nGAMMA = 0.9\nEPSILON = 0.2\n\n#Test flgas\nDEBUG = False\nRENDER_POLICY = True\nMEAN_RANGE = 10\nMIN_REWARD = -0.1\nMAX_REWARD = 1.0\nNUM_EPISODES_PLOT = 1000\nALGORITHM = \"sarsa\" # \"q-learning\", \"sarsa\" or \"expected-sarsa\"\n\ndef select_action_e_greedy(env, s, Q_values, epsilon = 0.5):\n \"\"\"\n It selects a random action with probability epsilon, otherwise the best learned until now.\n \"\"\"\n if np.random.rand() < epsilon:\n return env.ACTION[np.random.randint(len(env.ACTION))]\n else:\n return env.ACTION[np.argmax(Q_values[s[0],s[1],:])]\n\ndef learning_episode(env, Q_values, algorithm = \"q-learning\"):\n \"\"\"\n It calculates a whole simulation episode using the algorithm passed as argument.\n \"\"\"\n total_reward = 0\n\n for t in range(MAX_T):\n s = [env.maze_view.robot[0], env.maze_view.robot[1]]\n a = select_action_e_greedy(env, s, Q_values, epsilon = EPSILON)\n\n s_new, reward, done, _ = env.step(a)\n\n Q_prev = Q_values[s[0],s[1],env.ACTION.index(a)]\n\n #updata rule\n if algorithm == \"q-learning\":\n next_max_Q = np.max(Q_values[s_new[0],s_new[1],:])\n Q_values[s[0],s[1],env.ACTION.index(a)] = Q_prev + ALPHA*(reward + GAMMA*next_max_Q - Q_prev)\n elif algorithm == \"sarsa\":\n next_a = Q_values[s_new[0],s_new[1],np.random.randint(len(env.ACTION))]\n Q_values[s[0],s[1],env.ACTION.index(a)] = Q_prev + ALPHA*(reward + GAMMA*next_a - Q_prev)\n elif algorithm == \"expected-sarsa\":\n next_expected_value = np.mean(Q_values[s_new[0],s_new[1],:]) #it is not correct because the actions don't have the same p of being executed but it is quite reasonable\n Q_values[s[0],s[1],env.ACTION.index(a)] = Q_prev + ALPHA*(reward + GAMMA*next_expected_value - Q_prev)\n else:\n raise NameError('Unknown algorithm name!')\n\n if DEBUG:\n print(\"action: \", a)\n print(\"s_new: \", s_new)\n print(\"q_values\", Q_values[s_new[0],s_new[1],:])\n print(\"max q: \", np.max(Q_values[s_new[0],s_new[1],:]))\n print(\"actions: \", env.ACTION)\n print(\"index a: \", env.ACTION.index(a))\n print(\"Q_prev: \", Q_prev)\n print(\"Q_succ: \", Q_values[s[0],s[1],env.ACTION.index(a)])\n print(\"reward :\", reward)\n\n total_reward = total_reward + reward\n\n if done:\n break\n\n return total_reward\n\ndef training(env, Q_values, rewards, algorithm = \"q-learning\"):\n \"\"\"\n It carries out the training phase executing NUM_EPISODES of trials in the environment.\n \"\"\"\n for episode in range(NUM_EPISODES):\n env.reset()\n\n episode_reward = learning_episode(env, Q_values, algorithm)\n rewards[episode] = episode_reward\n\n if episode % NUM_EPISODES_PLOT == 0 and episode!=0:\n plt.plot(range(episode+1), [np.mean(rewards[max(0,i-MEAN_RANGE):min(i+MEAN_RANGE,episode+1)]) for i in range(episode+1)], \"b\")\n plt.axis([0, episode+1, MIN_REWARD, MAX_REWARD])\n plt.pause(0.05)\n\n if RENDER_POLICY:\n render_policy(env, Q_values)\n\ndef render_policy(env, Q_values, epsilon = 0):\n \"\"\"\n It shows the current learned behaviour on the GUI\n \"\"\"\n env.reset()\n\n for t in range(MAX_T):\n env.render()\n\n s = [env.maze_view.robot[0], env.maze_view.robot[1]]\n a = select_action_e_greedy(env, s, Q_values, epsilon)\n s_new, reward, done, _ = env.step(a)\n\n time.sleep(0.1)\n\n if done:\n print(\"I've reached the goal!\")\n break\n\n print(\"Policy executed.\")\n env.render()\n\n#COPY THE ENVIRONMENT YOU PREFER!\n# env = gym.make(\"maze-random-10x10-v0\")\n# env = gym.make(\"maze-random-20x20-plus-v0\")\n# env = gym.make(\"maze-random-30x30-plus-v0\")\n# env = gym.make(\"maze-random-100x100-v0\")\n\nif __name__ == \"__main__\":\n # Initialize the \"maze\" environment\n env = gym.make(\"maze-random-20x20-plus-v0\")\n\n env_dim = [env.maze_size[0],env.maze_size[1]]\n rewards = np.zeros(NUM_EPISODES)\n Q_values = np.zeros((env_dim[0], env_dim[1], len(env.ACTION)))\n\n training(env, Q_values, rewards, algorithm = ALGORITHM)\n\n print(\"Execute final policy...\")\n render_policy(env, Q_values)\n print(\"Everything is done!\")\n\n plt.show()\n" ]
[ [ "numpy.max", "numpy.argmax", "numpy.mean", "numpy.random.rand", "matplotlib.pyplot.axis", "matplotlib.pyplot.show", "numpy.zeros", "matplotlib.pyplot.pause" ] ]
LBNL-UCB-STI/activitysim
[ "7d88cf34c833d68068987bf8bf6af48a6ad706ec" ]
[ "activitysim/abm/models/trip_mode_choice.py" ]
[ "# ActivitySim\n# See full license in LICENSE.txt.\nfrom builtins import zip\nfrom builtins import range\n\nimport logging\n\nimport pandas as pd\n\nfrom activitysim.core import simulate\nfrom activitysim.core import tracing\nfrom activitysim.core import config\nfrom activitysim.core import inject\nfrom activitysim.core import pipeline\nfrom activitysim.core import orca\nfrom activitysim.core.mem import force_garbage_collect\n\nfrom .util.expressions import annotate_preprocessors\n\nfrom activitysim.core import assign\nfrom activitysim.core.util import assign_in_place\n\nfrom .util.expressions import skim_time_period_label\n\nfrom .util.mode import mode_choice_simulate\n\nlogger = logging.getLogger(__name__)\n\n\[email protected]()\ndef trip_mode_choice(\n trips,\n tours_merged,\n skim_dict, skim_stack,\n chunk_size, trace_hh_id):\n \"\"\"\n Trip mode choice - compute trip_mode (same values as for tour_mode) for each trip.\n\n Modes for each primary tour putpose are calculated separately because they have different\n coefficient values (stored in trip_mode_choice_coeffs.csv coefficient file.)\n\n Adds trip_mode column to trip table\n \"\"\"\n trace_label = 'trip_mode_choice'\n model_settings = config.read_model_settings('trip_mode_choice.yaml')\n\n logsum_column_name = model_settings.get('MODE_CHOICE_LOGSUM_COLUMN_NAME')\n mode_column_name = 'trip_mode'\n\n model_spec = \\\n simulate.read_model_spec(file_name=model_settings['SPEC'])\n omnibus_coefficients = \\\n assign.read_constant_spec(config.config_file_path(model_settings['COEFFICIENTS']))\n\n trips_df = trips.to_frame()\n logger.info(\"Running %s with %d trips\", trace_label, trips_df.shape[0])\n\n tours_merged = tours_merged.to_frame()\n tours_merged = tours_merged[model_settings['TOURS_MERGED_CHOOSER_COLUMNS']]\n\n nest_spec = config.get_logit_model_settings(model_settings)\n\n tracing.print_summary('primary_purpose',\n trips_df.primary_purpose, value_counts=True)\n\n # - trips_merged - merge trips and tours_merged\n trips_merged = pd.merge(\n trips_df,\n tours_merged,\n left_on='tour_id',\n right_index=True,\n how=\"left\")\n assert trips_merged.index.equals(trips.index)\n\n # setup skim keys\n assert ('trip_period' not in trips_merged)\n trips_merged['trip_period'] = skim_time_period_label(trips_merged.depart)\n\n orig_col = 'origin'\n dest_col = 'destination'\n\n odt_skim_stack_wrapper = skim_stack.wrap(left_key=orig_col, right_key=dest_col,\n skim_key='trip_period')\n dot_skim_stack_wrapper = skim_stack.wrap(left_key=dest_col, right_key=orig_col,\n skim_key='trip_period')\n od_skim_wrapper = skim_dict.wrap('origin', 'destination')\n\n skims = {\n \"odt_skims\": odt_skim_stack_wrapper,\n \"dot_skims\": dot_skim_stack_wrapper,\n \"od_skims\": od_skim_wrapper,\n }\n\n constants = config.get_model_constants(model_settings)\n constants.update({\n 'ORIGIN': orig_col,\n 'DESTINATION': dest_col\n })\n\n choices_list = []\n for primary_purpose, trips_segment in trips_merged.groupby('primary_purpose'):\n# print(primary_purpose, trips_segment)\n\n segment_trace_label = tracing.extend_trace_label(trace_label, primary_purpose)\n# print(segment_trace_label)\n\n logger.info(\"trip_mode_choice tour_type '%s' (%s trips)\" %\n (primary_purpose, len(trips_segment.index), ))\n\n # name index so tracing knows how to slice\n assert trips_segment.index.name == 'trip_id'\n\n locals_dict = assign.evaluate_constants(omnibus_coefficients[primary_purpose],\n constants=constants)\n locals_dict.update(constants)\n\n annotate_preprocessors(\n trips_segment, locals_dict, skims,\n model_settings, segment_trace_label)\n\n locals_dict.update(skims)\n\n choices = mode_choice_simulate(\n choosers=trips_segment,\n spec=model_spec,\n nest_spec=nest_spec,\n skims=skims,\n locals_d=locals_dict,\n chunk_size=chunk_size,\n mode_column_name=mode_column_name,\n logsum_column_name=logsum_column_name,\n trace_label=trace_label,\n trace_choice_name='trip_mode_choice')\n\n if trace_hh_id:\n # trace the coefficients\n tracing.trace_df(pd.Series(locals_dict),\n label=tracing.extend_trace_label(segment_trace_label, 'constants'),\n transpose=False,\n slicer='NONE')\n\n # so we can trace with annotations\n assign_in_place(trips_segment, choices)\n\n tracing.trace_df(trips_segment,\n label=tracing.extend_trace_label(segment_trace_label, 'trip_mode'),\n slicer='tour_id',\n index_label='tour_id',\n warn_if_empty=True)\n\n choices_list.append(choices)\n\n # FIXME - force garbage collection\n force_garbage_collect()\n\n choices = pd.concat(choices_list)\n\n # keep mode_choice and (optionally) logsum columns\n trips_df = trips.to_frame()\n assign_in_place(trips_df, choices)\n\n tracing.print_summary('tour_modes',\n trips_merged.tour_mode, value_counts=True)\n\n tracing.print_summary('trip_mode_choice choices',\n trips_df[mode_column_name], value_counts=True)\n\n assert not trips_df[mode_column_name].isnull().any()\n\n pipeline.replace_table(\"trips\", trips_df)\n \n if trace_hh_id:\n tracing.trace_df(trips_df,\n label=tracing.extend_trace_label(trace_label, 'trip_mode'),\n slicer='trip_id',\n index_label='trip_id',\n warn_if_empty=True)\n" ]
[ [ "pandas.merge", "pandas.concat", "pandas.Series" ] ]
HumanCompatibleAI/evaluating_rewards
[ "7b99ec9b415d805bd77041f2f7807d112dec9802" ]
[ "src/evaluating_rewards/analysis/distances/transformations.py" ]
[ "# Copyright 2019, 2020 DeepMind Technologies Limited, Adam Gleave\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\"\"\"Helper methods for transforming configs and indices to more easily human interpretable values.\"\"\"\n\nimport re\n\nimport pandas as pd\n\nfrom evaluating_rewards.analysis import results\n\nTRANSFORMATIONS = {\n r\"^evaluating_rewards[_/](.*)-v0\": r\"\\1\",\n r\"^imitation[_/](.*)-v0\": r\"\\1\",\n \"^Zero\": r\"\\\\zeroreward{}\",\n \"^PointMassDense\": r\"\\\\dense{}\",\n \"^PointMassGroundTruth\": r\"\\\\magnitude{}\\\\controlpenalty{}\",\n \"^PointMassSparse\": r\"\\\\sparse{}\",\n \"^PointMazeGroundTruth\": \"GT\",\n r\"(.*)(Hopper|HalfCheetah)GroundTruth(.*)\": r\"\\1\\2\\\\running{}\\3\",\n r\"(.*)(Hopper|HalfCheetah)Backflip(.*)\": r\"\\1\\2\\\\backflipping{}\\3\",\n r\"^Hopper(.*)\": r\"\\1\",\n r\"^HalfCheetah(.*)\": r\"\\1\",\n r\"^(.*)Backward(.*)\": r\"\\\\backward{\\1\\2}\",\n r\"^(.*)Forward(.*)\": r\"\\\\forward{\\1\\2}\",\n r\"^(.*)WithCtrl(.*)\": r\"\\1\\\\controlpenalty{}\\2\",\n r\"^(.*)NoCtrl(.*)\": r\"\\1\\\\nocontrolpenalty{}\\2\",\n \"sparse_goal\": r\"\\\\sparsegoal{}\",\n \"transformed_goal\": r\"\\\\densegoal{}\",\n \"center_goal\": r\"\\\\centergoal{}\",\n \"sparse_penalty\": r\"\\\\sparsepenalty{}\",\n \"dirt_path\": r\"\\\\dirtpath{}\",\n \"cliff_walk\": r\"\\\\cliffwalk{}\",\n}\nLEVEL_NAMES = {\n # Won't normally use both type and path in one plot\n \"source_reward_type\": \"Source\",\n \"source_reward_path\": \"Source\",\n \"target_reward_type\": \"Target\",\n \"target_reward_path\": \"Target\",\n}\nWHITELISTED_LEVELS = [\"source_reward_type\", \"target_reward_type\"] # never remove these levels\n\n\ndef pretty_rewrite(x):\n if not isinstance(x, str):\n return x\n\n for pattern, repl in TRANSFORMATIONS.items():\n x = re.sub(pattern, repl, x)\n return x\n\n\ndef rewrite_index(series: pd.Series) -> pd.Series:\n \"\"\"Replace `source_reward_path` with info extracted from config at that path.\"\"\"\n if \"source_reward_path\" in series.index.names:\n new_index = series.index.to_frame(index=False)\n source_reward = results.path_to_config(\n new_index[\"source_reward_type\"], new_index[\"source_reward_path\"]\n )\n new_index = new_index.drop(columns=[\"source_reward_type\", \"source_reward_path\"])\n new_index = pd.concat([source_reward, new_index], axis=1)\n new_index = pd.MultiIndex.from_frame(new_index)\n series.index = new_index\n return series\n\n\ndef remove_constant_levels(index: pd.MultiIndex) -> pd.MultiIndex:\n index = index.copy()\n levels = index.names\n for level in levels:\n if len(index.get_level_values(level).unique()) == 1 and level not in WHITELISTED_LEVELS:\n index = index.droplevel(level=level)\n return index\n\n\ndef index_reformat(series: pd.Series, preserve_order: bool) -> pd.DataFrame:\n \"\"\"Helper to reformat labels for ease of interpretability.\"\"\"\n series = series.copy()\n series = rewrite_index(series)\n series.index = remove_constant_levels(series.index)\n series.index.names = [LEVEL_NAMES.get(name, name) for name in series.index.names]\n series = series.rename(index=pretty_rewrite)\n\n # Preserve order of inputs\n df = series.unstack(\"Target\")\n if preserve_order:\n df = df.reindex(columns=series.index.get_level_values(\"Target\").unique())\n for level in series.index.names:\n kwargs = {}\n if isinstance(df.index, pd.MultiIndex):\n kwargs = dict(level=level)\n if level != \"Target\":\n df = df.reindex(index=series.index.get_level_values(level).unique(), **kwargs)\n else:\n df = df.sort_index()\n return df\n" ]
[ [ "pandas.concat", "pandas.MultiIndex.from_frame" ] ]
dssg/mlpolicylab_fall20_schools3_public
[ "f8eff4c56e9bada1eb81ddaca03686d7ef53c2c4" ]
[ "schools3/data/explorers/labels_explorer.py" ]
[ "import pandas as pd\nfrom schools3.data.explorers.explorer import Explorer\nfrom schools3.data import common_queries\n\n\nclass LabelsExplorer(Explorer):\n def __init__(self, debug=False):\n super(LabelsExplorer, self).__init__(debug)\n self.labels_df = pd.DataFrame(columns=[\n 'label',\n 'num_students',\n 'gender_dist',\n 'ethnicity_dist',\n 'discipline_incidents_rate',\n 'absenteeism_rate',\n 'unexcused_absenteeism_rate',\n 'disabilities_dist',\n 'num_disabilities',\n 'disadvantagements_dist',\n 'latest_gpa',\n 'total_classes',\n 'inv_groups_dist',\n 'avg_academic_inv',\n 'avg_extracurr_inv'\n ])\n\n def explore(self):\n all_students_info_q = common_queries.get_student_data([9, 12])\n labels = self.query(common_queries.get_labels())\n\n for l in labels['label']:\n students_q = common_queries.get_students_with_label(l)\n cur_students_info = self.query(\n common_queries.get_query_with_students(\n all_students_info_q,\n students_q\n )\n )\n self.labels_df = self.append_label_info(cur_students_info, self.labels_df, l)\n\n return self.labels_df\n\n def append_label_info(self, cur_students_info, labels_df, label):\n labels_df = labels_df.append(pd.Series(), ignore_index=True)\n\n new_row = labels_df.iloc[-1]\n\n new_row.label = label\n new_row.num_students = cur_students_info.shape[0]\n\n new_row.gender_dist = self.get_dist(cur_students_info.gender)\n new_row.ethnicity_dist = self.get_dist(cur_students_info.ethnicity)\n\n new_row.discipline_incidents_rate = cur_students_info.discipline_incidents_rate.fillna(0).mean()\n new_row.absenteeism_rate = cur_students_info.absenteeism_rate.mean()\n new_row.unexcused_absenteeism_rate = cur_students_info.unexcused_absenteeism_rate.mean()\n\n new_row.disabilities_dist = self.get_dist(cur_students_info.disabilities, is_element_list=True, normalize=False)\n new_row.num_disabilities = cur_students_info.disabilities.apply(\n lambda x : len([e for e in x if e and e != 'none'])\n ).mean()\n new_row.disadvantagements_dist = self.get_dist(cur_students_info.disadvantagements, is_element_list=True, normalize=False)\n\n new_row.latest_gpa = cur_students_info.gpas.apply(\n lambda x : x if x is None else x[-1]\n ).mean()\n new_row.total_classes = cur_students_info.num_classes.apply(\n lambda x : x if x is None else sum(x)\n ).mean()\n\n new_row.inv_groups_dist = self.get_dist(\n cur_students_info.inv_groups,\n is_element_list=True,\n normalize=False\n )\n\n new_row.avg_academic_inv = cur_students_info.inv_groups.apply(\n lambda x : 0 if not x else x.count('academic_inv')\n ).mean()\n\n new_row.avg_extracurr_inv = cur_students_info.inv_groups.apply(\n lambda x: 0 if x is None else x.count('atheletics') + x.count('extracurr_program')\n ).mean()\n\n return labels_df\n\n def get_dist(self, series, is_element_list=False, normalize=True, normalize_by=None):\n if not is_element_list:\n if normalize_by is None:\n d = series.value_counts(normalize=normalize).to_dict()\n elif normalize:\n d = series.value_counts().to_dict()\n for k in d:\n d[k] /= normalize_by\n return d\n\n d = {}\n for s in series:\n if s:\n for e in s:\n if e and e.lower() != 'none':\n if e in d:\n d[e] += 1\n else:\n d[e] = 1\n\n if normalize:\n total = sum(d.values()) if not normalize_by else normalize_by\n for k in d:\n d[k] /= total\n\n return d\n" ]
[ [ "pandas.Series", "pandas.DataFrame" ] ]
mlvc-lab/AIChallenge_4th_Round1
[ "2a7cd64254540a5779bc3d9accdb21ddaa38aa51" ]
[ "quantization/lsq/iqnn.py" ]
[ "import math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.parameter import Parameter\n\nfrom .quantizer import LSQ\n\n\nclass QuantConv2d(nn.Conv2d):\n def __init__(self, in_channels, out_channels, kernel_size, stride=1,\n padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros',\n nbits=32, symmetric=False, do_mask=False):\n super(QuantConv2d, self).__init__(in_channels, out_channels, kernel_size, stride,\n padding, dilation, groups, bias, padding_mode)\n self.step = Parameter(torch.Tensor(1))\n\n def forward(self, x):\n quantized_weight = self.weight * self.step\n return self._conv_forward(x, quantized_weight)\n\n\nclass QuantLinear(nn.Linear):\n def __init__(self, in_features, out_features, bias=True, nbits=32, symmetric=False, do_mask=False):\n super(QuantLinear, self).__init__(in_features, out_features, bias)\n self.step = Parameter(torch.Tensor(1))\n\n def forward(self, x):\n quantized_weight = self.weight * self.step\n return F.linear(x, quantized_weight, self.bias)\n" ]
[ [ "torch.nn.functional.linear", "torch.Tensor" ] ]
neerajwagh/eeg-self-supervision
[ "fb0a1bf357b0e553aab9c4ccfc2973156dc8a9e7" ]
[ "evaluation/ablation_models_eval.py" ]
[ "import argparse\nimport parser\nimport sys\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom sklearn.metrics import (balanced_accuracy_score, classification_report,\n f1_score, precision_score, recall_score,\n roc_auc_score, roc_curve)\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\n\nfrom ablation_models import (BarlowTwinsContrastiveTripletNet,\n BarlowTwinsDBRatioNet, ContrastiveTripletNet,\n DBRatioContrastiveNet, FullSSLNet)\nfrom datasets import Dataset\nfrom utils import _get_subject_level_split, _map_age, get_patient_prediction\n\nstats_test_data = { }\n\n# features of the models\nargs_p = dict({\n\t# data loading\n\t\"batch_size\": 4096, # CAUTION: actual batch sent to gpu varies depending on # bad epochs (training) and # windows in subject (inference)\n\t\"num_workers\": 16,\n\t\"pin_memory\": True, # CAUTION: =True leads to slower data loading on Vivaldi - don't know why.\n\t\"prefetch_factor\": 2,\n\t\"persistent_workers\": False, # =True crashs after first epoch\n\n\t# model architecture and loss function\n\t\"feature_type\": 'topo',\n\t\"input_channels\": 7,\n\t\"flattened_features_per_sample\": 7*32*32,\n\t\"projector\": '512-512-512',\n\n\t\"loss_margin\": 0.2, # ignored for eval\n\t\"loss_norm\": 2, # ignored for eval\n\t# for BT loss\n\t\"lambda\": 2e-3,\n})\n\n# This function is used to collect final metrics.\ndef collect_metrics_heldout(y_probs_test, y_true_test, y_pred_test, sample_indices_test, _INDEX_DF, dataset):\n\n\tdataset_index = _INDEX_DF\n\t\n\tif dataset == \"lemon\":\n\t\ttitle = \"subject_id\"\n\telif dataset == \"tuh\":\n\t\ttitle = \"patient_id\"\n\telse:\n\t\traise ValueError(\"unknown dataset\")\n\t# create patient-level train and test dataframes\n\trows = [ ]\n\tfor i in range(len(sample_indices_test)):\n\t\tidx = sample_indices_test[i]\n\t\ttemp = { }\n\t\ttemp[title] = str(dataset_index.loc[idx, title])\n\t\ttemp[\"raw_file_path\"] = str(dataset_index.loc[idx, \"raw_file_path\"])\n\t\ttemp[\"sample_idx\"] = idx\n\t\ttemp[\"y_true\"] = y_true_test[i]\n\t\ttemp[\"y_probs_0\"] = y_probs_test[i, 0]\n\t\ttemp[\"y_probs_1\"] = y_probs_test[i, 1]\n\t\ttemp[\"y_pred\"] = y_pred_test[i]\n\t\trows.append(temp)\n\ttest_patient_df = pd.DataFrame(rows)\n\n\t# get patient-level metrics from window-level dataframes\n\ty_probs_test_patient, y_true_test_patient, y_pred_test_patient = get_patient_prediction(test_patient_df, dataset)\n\tauc_patient_history, prec_history, recall_history, f1_history, bacc_history = [], [], [], [], []\n\t\n\tfor i in tqdm(range(len(y_probs_test_patient))):\n\t\ty_prob = np.copy(y_probs_test_patient)\n\t\ty_prob = np.delete(y_prob, i, axis=0)\n\n\t\ty_true_s = np.copy(y_true_test_patient)\n\t\ty_true_s = np.delete(y_true_s, i)\n\t\t\n\t\tstats_test_data[f\"probs_0\"] = y_prob[:, 0]\n\t\tstats_test_data[f\"probs_1\"] = y_prob[:, 1]\n\n\t\tpatient_csv_dict = { }\n\n\t\t# PATIENT-LEVEL ROC PLOT - select optimal threshold for this, and get patient-level precision, recall, f1\n\t\tfpr, tpr, thresholds = roc_curve(y_true_s, y_prob[:,1], pos_label=1)\n\t\tpatient_csv_dict[f\"fpr_fold\"] = fpr\n\t\tpatient_csv_dict[f\"tpr_fold\"] = tpr\n\t\tpatient_csv_dict[f\"thres_fold\"] = thresholds\n\n\t\t# select an optimal threshold using the ROC curve\n\t\t# Youden's J statistic to obtain the optimal probability threshold and this method gives equal weights to both false positives and false negatives\n\t\toptimal_proba_cutoff = sorted(list(zip(np.abs(tpr - fpr), thresholds)), key=lambda i: i[0], reverse=True)[0][1]\n\n\t\t# calculate class predictions and confusion-based metrics using the optimal threshold\n\t\troc_predictions = [1 if i >= optimal_proba_cutoff else 0 for i in y_prob[:,1]]\n\n\t\tprecision_patient_test = precision_score(y_true_s, roc_predictions, pos_label=1)\n\t\trecall_patient_test = recall_score(y_true_s, roc_predictions, pos_label=1)\n\t\tf1_patient_test = f1_score(y_true_s, roc_predictions, pos_label=1)\n\t\tbal_acc_patient_test = balanced_accuracy_score(y_true_s, roc_predictions)\n\n\t\t# PATIENT-LEVEL AUROC\n\t\tauroc_patient_test = roc_auc_score(y_true_s, y_prob[:,1])\n\n\t\tauc_patient_history.append(auroc_patient_test)\n\t\tprec_history.append(precision_patient_test)\n\t\trecall_history.append(recall_patient_test)\n\t\tf1_history.append(f1_patient_test)\n\t\tbacc_history.append(bal_acc_patient_test)\n\t\n\treturn auc_patient_history, prec_history, recall_history, f1_history, bacc_history\n\nif __name__ == '__main__':\n\t\n\tparser = argparse.ArgumentParser(description=\"Execute heldout evaluation.\")\n\tparser.add_argument('--gpu_idx', type=int, help=\"Index of GPU device. Default is 0.\")\n\tparser.add_argument('--task', type=str, help=\"choose from ...\")\n\tparser.add_argument('--mode', type=str, help=\"choose a mode\")\n\tparser.add_argument('--dataset', type=str, help=\"choose between tuh and leomon\")\n\targs = parser.parse_args()\n\t\n\t_GPU_IDX = args.gpu_idx\n\t_MODE = args.mode\n\t_TASK = args.task\n\tdataset=args.dataset\n\n\tif dataset == \"lemon\":\n\t\t_INDEX_PATH = \"../resources/lemon_window_index.csv\"\n\t\t_INDEX_DF = pd.read_csv(_INDEX_PATH)\n\telif dataset == \"tuh\":\n\t\t_INDEX_PATH = \"../resources/abnormal_corpus_window_index.csv\"\n\t\t_INDEX_DF = pd.read_csv(_INDEX_PATH)\n\t\t_INDEX_DF['parsed_age_binary'] = _INDEX_DF['parsed_age'].map(_map_age)\n\telse:\n\t\traise ValueError(\"unknown dataset\")\n\n\t_RANDOM_SEED = 42\n\n\t#Set seed for numpy and torch\n\tnp.random.seed(_RANDOM_SEED)\n\ttorch.manual_seed(_RANDOM_SEED)\n\tprint(f\"Numpy and PyTorch seed set to {_RANDOM_SEED} for reproducibility.\")\n\n\t#set cuda device\n\t_TORCH_DEVICE = torch.device(f'cuda:{_GPU_IDX}' if torch.cuda.is_available() else 'cpu')\n\ttorch.cuda.set_device(_TORCH_DEVICE)\n\ttorch.cuda.empty_cache()\n\n\t#select moodel \n\tif _MODE == \"FULLSSL\":\n\t\tmodel = FullSSLNet(args_p)\n\telif _MODE == \"DBRTriplet\":\n\t\tmodel = DBRatioContrastiveNet(args_p)\n\telif _MODE == \"BTTriplet\":\n\t\tmodel = BarlowTwinsContrastiveTripletNet(args_p)\n\telif _MODE == \"BTDBR\":\n\t\tmodel = BarlowTwinsDBRatioNet(args_p)\n\telif _MODE == \"Triplet\":\n\t\tmodel = ContrastiveTripletNet(args_p)\n\telif _MODE == \"DBR\":\n\t\tmodel = BarlowTwinsDBRatioNet(args_p)\n\telif _MODE == \"BT\":\n\t\tmodel = FullSSLNet(args_p)\n\telse:\n\t\traise ValueError('unknown model!')\n\t\n\t# add 512->2 linear layer to backbone\n\tmodel = model.to(_TORCH_DEVICE)\n\tmodel = model.embedder[0]\n\tmodel.fc = torch.nn.Linear(512, 2)\n\tmodel.fc.weight.data.normal_(mean=0.0, std=0.01)\n\tmodel.fc.bias.data.zero_()\n\n\t# load trained model states\n\tfile = f\"../resources/finetuned_models/{dataset}_{_TASK}_{_MODE}.ckpt\"\n\tckpt = torch.load(file, map_location=_TORCH_DEVICE)\n\tmodel.load_state_dict(ckpt['model_state'])\n\tmodel = model.to(_TORCH_DEVICE)\n\n\t# Cross Entropy loss function\n\tloss_function = torch.nn.CrossEntropyLoss()\n\n\t#load X, y\n\tprint(\"Loading data...\")\n\tX = np.load(f'../resources/topo_data_{dataset}.npy', mmap_mode='r').astype(np.float32)\t\t\n\tprint(\"Loading done.\")\n\n\tif dataset == 'tuh':\n\t\tif _TASK == \"gender\":\n\t\t\ty = _INDEX_DF['parsed_gender'].to_numpy()\n\t\t\t_INDEX_DF = _INDEX_DF.loc[_INDEX_DF[\"parsed_gender\"].isin([\"Male\", \"Female\"])]\n\t\telif _TASK == \"age\":\n\t\t\ty = _INDEX_DF['parsed_age_binary'].to_numpy()\n\t\t\t_INDEX_DF = _INDEX_DF.loc[_INDEX_DF[\"parsed_age_binary\"].isin([\"young\", \"old\"])]\n\t\telif _TASK == \"condition\":\n\t\t\ty = _INDEX_DF[\"text_label\"].to_numpy()\n\t\t\t_INDEX_DF = _INDEX_DF.loc[_INDEX_DF[\"text_label\"].isin([\"normal\", \"abnormal\"])]\n\t\telse:\n\t\t\traise ValueError('unknown task!')\n\n\t\tkeep_idx = _INDEX_DF.index\n\t\tX = X[keep_idx, ...]\n\t\ty = y[keep_idx, ...]\n\t\t_INDEX_DF.reset_index(drop=True, inplace=True)\n\t\t_INDEX_DF.sort_index(inplace=True)\n\t\t_INDEX_DF['new_window_idx'] = _INDEX_DF.index\n\t\n\telif dataset == \"lemon\":\n\t\tif _TASK == \"gender\":\n\t\t\ty = _INDEX_DF['gender'].to_numpy()\n\t\telif _TASK == \"age\":\n\t\t\ty = _INDEX_DF['age'].to_numpy()\n\t\telif _TASK == \"condition\":\n\t\t\ty = _INDEX_DF[\"condition\"].to_numpy()\n\t\telse:\n\t\t\traise ValueError('unknown task!')\n\telse:\n\t\traise ValueError('unknown dataset!')\n\t\n\t# map labels to 0/1\n\tlabel_mapping, y = np.unique(y, return_inverse=True)\n\tprint(f\"Unique labels 0/1 mapping: {label_mapping}\")\n\n\t# make train, test, heldout splits. Only heldout set is used for evaluation. Random see is used to ensure reproductability.\n\tall_subjects, train_subjects, val_subjects, heldout_subjects, train_window_idx, val_window_idx, heldout_window_idx = _get_subject_level_split(_INDEX_DF, _RANDOM_SEED,dataset, _TASK)\n\tprint(\"train_subjects: \", len(train_subjects), \" val subjects: \", len(val_subjects), \\\n\t\t\" heldout_subjects: \", len(heldout_subjects), \" all subjects: \", len(all_subjects))\n\tprint(f\"len train_window_idx: {len(train_window_idx)}, len val_window_idx: {len(val_window_idx)}, len heldout_window_idx:{len(heldout_window_idx)}\")\n\n\n\t# This is for lemon dataset, condition task only. \n\tif _TASK == \"condition\" and dataset == \"lemon\":\n\t\theldout_indices_all = []\n\t\tfor i in tqdm(range(len(heldout_subjects))):\n\t\t\theldout_subjects_resample = np.copy(heldout_subjects)\n\t\t\theldout_subjects_resample = np.delete(heldout_subjects_resample, i)\n\n\t\t\theldout_indices = _INDEX_DF.index[_INDEX_DF[\"subject_id\"].astype(\"str\").isin(heldout_subjects_resample)].tolist()\n\t\t\theldout_indices_all.append(heldout_indices)\n\t\t\n\t\t# Datasets, dataloaders\n\t\tdataset_list, dataloader_list = [],[]\n\n\t\tfor i in tqdm(range(len(heldout_indices_all))):\n\t\t\theldout_dataset = Dataset(window_idx=heldout_indices_all[i],X=X, y=y)\n\t\t\tdataset_list.append(heldout_dataset)\n\t\t\theldout_loader = DataLoader(heldout_dataset, batch_size=512, shuffle=False, num_workers=8)\n\t\t\tdataloader_list.append(heldout_loader)\n\n\t\t#initialize metrics lists\n\t\tall_auc, all_auc_patient, all_prec, all_recall, all_f1, all_bacc = [],[],[],[],[],[]\n\t\t# start evaluation process\n\t\tfor j in tqdm(range(len(heldout_indices_all))):\n\t\t\tmodel.eval()\n\t\t\twith torch.no_grad():\n\t\t\t\ty_probs = torch.empty(0, 2).to(_TORCH_DEVICE)\n\t\t\t\ty_true = [ ]\n\t\t\t\ty_pred = [ ]\n\t\t\t\twindow_indices = [ ]\n\t\t\t\t\n\t\t\t\tfor i, batch in enumerate(dataloader_list[j]):\n\t\t\t\t\t\n\t\t\t\t\twindow_indices += batch['window_idx'].tolist()\n\t\t\t\t\tX_batch = batch['feature_data'].to(device=_TORCH_DEVICE, non_blocking=True).float()\n\t\t\t\t\ty_batch = batch['label'].to(device=_TORCH_DEVICE, non_blocking=True)\n\t\t\t\t\toutputs = model(X_batch)\n\n\t\t\t\t\t_, predicted = torch.max(outputs.data, 1)\n\t\t\t\t\ty_pred += predicted.cpu().numpy().tolist()\n\n\t\t\t\t\t# concatenate along 0th dimension\n\t\t\t\t\ty_probs = torch.cat((y_probs, outputs.data), 0)\n\t\t\t\t\ty_true += y_batch.cpu().numpy().tolist()\n\n\t\t\t# returning prob distribution over target classes, take softmax across the 1st dimension\n\t\t\ty_probs = torch.nn.functional.softmax(y_probs, dim=1).cpu().numpy()\n\t\t\ty_true = np.array(y_true)\n\n\t\t\tauroc_test = roc_auc_score(y_true, y_probs[:,1])\n\t\t\tbacc_test = balanced_accuracy_score(y_true, y_pred)\n\t\t\tall_auc.append(auroc_test)\n\t\t\tall_bacc.append(bacc_test)\n\n\t\t\treport = classification_report(y_true, y_pred, output_dict=True)\n\t\t\tall_prec.append(report['1']['precision'])\n\t\t\tall_recall.append(report['1']['recall'])\n\t\t\tall_f1.append(report['1']['f1-score'])\n\t\t\n\t\tprint(\"Report-------------------------------\")\n\t\tprint(f\"heldout test AUROC: {np.mean(all_auc):.3f}({np.std(all_auc):.3f})\")\n\t\tprint(f\"heldout test PRECISION: {np.mean(all_prec):.3f}({np.std(all_prec):.3f})\")\n\t\tprint(f\"heldout test RECALL: {np.mean(all_recall):.3f}({np.std(all_recall):.3f})\")\n\t\tprint(f\"heldout test F-1: {np.mean(all_f1):.3f}({np.std(all_f1):.3f})\")\n\t\tprint(f\"heldout test BALANCED ACCURACY: {np.mean(all_bacc):.3f}({np.std(all_bacc):.3f})\")\n\n\t\t# calculate interval percentile\n\t\talpha = 0.95\n\t\tp = ((1.0-alpha)/2.0) * 100\n\t\tlower = max(0.0, np.percentile(all_auc, p))\n\t\tp = (alpha+((1.0-alpha)/2.0)) * 100\n\t\tupper = min(1.0, np.percentile(all_auc, p))\n\t\n\t\t# confidence interval\n\t\tprint('%.1f%% AUC confidence interval %.1f%% and %.1f%%' % (alpha*100, lower*100, upper*100))\n\t\tprint(\"[MAIN] exiting...\")\n\t\tsys.exit()\n\t\n\n\t# leave-1-out sampling for other tasks\n\theldout_dataset = Dataset(window_idx=heldout_window_idx, X=X, y=y)\n\theldout_loader = DataLoader(heldout_dataset, batch_size=4096, shuffle=False, num_workers=8)\n\n\t# evaluation\n\tmodel.eval()\n\twith torch.no_grad():\n\t\ty_probs = torch.empty(0, 2).to(_TORCH_DEVICE)\n\t\ty_true = [ ]\n\t\ty_pred = [ ]\n\t\twindow_indices = [ ]\n\t\tfor i, batch in enumerate(heldout_loader):\n\t\t\t\n\t\t\twindow_indices += batch['window_idx'].tolist()\n\t\t\tX_batch = batch['feature_data'].to(device=_TORCH_DEVICE, non_blocking=True).float()\n\t\t\ty_batch = batch['label'].to(device=_TORCH_DEVICE, non_blocking=True)\n\t\t\toutputs = model(X_batch)\n\n\t\t\t_, predicted = torch.max(outputs.data, 1)\n\t\t\ty_pred += predicted.cpu().numpy().tolist()\n\n\t\t\t# concatenate along 0th dimension\n\t\t\ty_probs = torch.cat((y_probs, outputs.data), 0)\n\t\t\ty_true += y_batch.cpu().numpy().tolist()\n\n\t\t# returning prob distribution over target classes, take softmax across the 1st dimension\n\t\ty_probs = torch.nn.functional.softmax(y_probs, dim=1).cpu().numpy()\n\t\ty_true = np.array(y_true)\n\n\t\tauc_patient_history, prec_history, recall_history, f1_history, bacc_history = collect_metrics_heldout(y_probs_test=y_probs,\n\t\t\t\t\t\t\ty_true_test=y_true,\n\t\t\t\t\t\t\ty_pred_test=y_pred,\n\t\t\t\t\t\t\tdataset=dataset,\n\t\t\t\t\t\t\tsample_indices_test = window_indices, _INDEX_DF=_INDEX_DF)\n\t\n\t# confidence interval\n\talpha = 0.95\n\n\tprint(\"Report-------------------------------\")\n\tprint(f\"heldout test patient AUROC: {np.mean(auc_patient_history):.3f}({np.std(auc_patient_history):.4f})\")\n\tprint(f\"heldout test patient PRECISION: {np.mean(prec_history):.3f}({np.std(prec_history):.4f})\")\n\tprint(f\"heldout test patient RECALL: {np.mean(recall_history):.3f}({np.std(recall_history):.4f})\")\n\tprint(f\"heldout test patient F-1: {np.mean(f1_history):.3f}({np.std(f1_history):.4f})\")\n\tprint(f\"heldout test patient BALANCED ACCURACY: {np.mean(bacc_history):.3f}({np.std(bacc_history):.4f})\")\n\n\t# calculate interval percentile\n\tp = ((1.0-alpha)/2.0) * 100\n\tlower = max(0.0, np.percentile(auc_patient_history, p))\n\tp = (alpha+((1.0-alpha)/2.0)) * 100\n\tupper = min(1.0, np.percentile(auc_patient_history, p))\n\t\n\t# confidence interval\n\tprint('%.1f%% AUC confidence interval %.2f%% and %.2f%%' % (alpha*100, lower*100, upper*100))\n\n\tprint(\"[MAIN] exiting...\")\n" ]
[ [ "sklearn.metrics.roc_auc_score", "torch.nn.functional.softmax", "torch.max", "torch.load", "torch.cat", "torch.utils.data.DataLoader", "pandas.DataFrame", "torch.no_grad", "numpy.mean", "torch.cuda.is_available", "sklearn.metrics.f1_score", "sklearn.metrics.classification_report", "torch.nn.CrossEntropyLoss", "pandas.read_csv", "numpy.unique", "numpy.copy", "numpy.std", "numpy.load", "torch.empty", "sklearn.metrics.precision_score", "torch.cuda.empty_cache", "sklearn.metrics.roc_curve", "torch.nn.Linear", "numpy.delete", "numpy.array", "sklearn.metrics.recall_score", "numpy.abs", "torch.cuda.set_device", "numpy.random.seed", "torch.manual_seed", "sklearn.metrics.balanced_accuracy_score", "numpy.percentile" ] ]
Faudil/sound-encoding-neural-network
[ "daadaddd53881f656b097398b48eac90340132f1" ]
[ "src/classifiers/digit/mlp.py" ]
[ "import keras\nimport numpy as np\nfrom keras_preprocessing.sequence import pad_sequences\nfrom keras.layers import Dense, Dropout, Conv1D, Activation, Flatten, MaxPooling1D, BatchNormalization, LSTM\nfrom keras.models import Sequential\nfrom python_speech_features import mfcc\n\nfrom src.sound.SoundTransformer import SoundTransformer\nfrom src.classifiers.KerasClassifier import KerasClassifier\n\n\nclass DigitClassifier(KerasClassifier):\n def __init__(self, file_path=None):\n super().__init__(file_path)\n\n def predict(self, x):\n #x = np.expand_dims(np.array([x]), axis=2)\n return self._model.predict(x)\n\n def build(self):\n model = Sequential()\n model.add(Dense(128))\n model.add(Activation('relu'))\n model.add(Dense(10, activation='softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n self._model = model\n\n def transform(self, x, samplerate):\n to_process = mfcc(x, samplerate, nfft=551)\n to_process = np.mean(to_process, axis=1)\n to_process = pad_sequences([to_process], maxlen=128, padding='post')[0]\n # to_process = np.expand_dims(to_process, axis=2)\n return to_process\n" ]
[ [ "numpy.mean" ] ]
ScottyLectronica/kubric
[ "31930b4a8517d1fc5987bb1502e47f130209505a" ]
[ "kubric/simulator/pybullet.py" ]
[ "# Copyright 2022 The Kubric 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\r\n# pylint: disable=function-redefined\r\n\r\nimport logging\r\nimport pathlib\r\nimport sys\r\nimport tempfile\r\nfrom typing import Dict, List, Optional, Tuple, Union\r\n\r\nimport tensorflow as tf\r\nfrom singledispatchmethod import singledispatchmethod\r\n\r\nfrom kubric import core\r\nfrom kubric.redirect_io import RedirectStream\r\n\r\n# --- hides the \"pybullet build time: May 26 2021 18:52:36\" message on import\r\nwith RedirectStream(stream=sys.stderr):\r\n import pybullet as pb\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\nclass PyBullet(core.View):\r\n \"\"\"Adds physics simulation on top of kb.Scene using PyBullet.\"\"\"\r\n\r\n def __init__(self, scene: core.Scene, scratch_dir=tempfile.mkdtemp()):\r\n self.scratch_dir = scratch_dir\r\n self.physics_client = pb.connect(pb.DIRECT) # pb.GUI\r\n\r\n # --- Set some parameters to fix the sticky-walls problem; see\r\n # https://github.com/bulletphysics/bullet3/issues/3094\r\n pb.setPhysicsEngineParameter(restitutionVelocityThreshold=0.,\r\n warmStartingFactor=0.,\r\n useSplitImpulse=True,\r\n contactSlop=0.,\r\n enableConeFriction=False,\r\n deterministicOverlappingPairs=True)\r\n # TODO: setTimeStep if scene.step_rate != 240 Hz\r\n super().__init__(scene, scene_observers={\r\n \"gravity\": [lambda change: pb.setGravity(*change.new)],\r\n })\r\n\r\n def __del__(self):\r\n try:\r\n pb.disconnect()\r\n except Exception: # pylint: disable=broad-except\r\n pass # cleanup code. ignore errors\r\n\r\n @singledispatchmethod\r\n def add_asset(self, asset: core.Asset) -> Optional[int]:\r\n raise NotImplementedError(f\"Cannot add {asset!r}\")\r\n\r\n def remove_asset(self, asset: core.Asset) -> None:\r\n if self in asset.linked_objects:\r\n pb.removeBody(asset.linked_objects[self])\r\n # TODO(klausg): unobserve\r\n\r\n @add_asset.register(core.Camera)\r\n def _add_object(self, obj: core.Camera) -> None:\r\n logger.debug(\"Ignored camera %s\", obj)\r\n\r\n @add_asset.register(core.Material)\r\n def _add_object(self, obj: core.Material) -> None:\r\n logger.debug(\"Ignored material %s\", obj)\r\n\r\n @add_asset.register(core.Light)\r\n def _add_object(self, obj: core.Light) -> None:\r\n logger.debug(\"Ignored light %s\", obj)\r\n\r\n @add_asset.register(core.Cube)\r\n def _add_object(self, obj: core.Cube) -> Optional[int]:\r\n collision_idx = pb.createCollisionShape(pb.GEOM_BOX, halfExtents=obj.scale)\r\n visual_idx = -1\r\n mass = 0 if obj.static else obj.mass\r\n # useMaximalCoordinates and contactProcessingThreshold are required to\r\n # fix the sticky walls issue;\r\n # see https://github.com/bulletphysics/bullet3/issues/3094\r\n box_idx = pb.createMultiBody(mass, collision_idx, visual_idx, obj.position,\r\n wxyz2xyzw(obj.quaternion), useMaximalCoordinates=True)\r\n pb.changeDynamics(box_idx, -1, contactProcessingThreshold=0)\r\n register_physical_object_setters(obj, box_idx)\r\n\r\n return box_idx\r\n\r\n @add_asset.register(core.Sphere)\r\n def _add_object(self, obj: core.Sphere) -> Optional[int]:\r\n radius = obj.scale[0]\r\n assert radius == obj.scale[1] == obj.scale[2], obj.scale # only uniform scaling\r\n collision_idx = pb.createCollisionShape(pb.GEOM_SPHERE, radius=radius)\r\n visual_idx = -1\r\n mass = 0 if obj.static else obj.mass\r\n # useMaximalCoordinates and contactProcessingThreshold are required to\r\n # fix the sticky walls issue;\r\n # see https://github.com/bulletphysics/bullet3/issues/3094\r\n sphere_idx = pb.createMultiBody(mass, collision_idx, visual_idx, obj.position,\r\n wxyz2xyzw(obj.quaternion), useMaximalCoordinates=True)\r\n pb.changeDynamics(sphere_idx, -1, contactProcessingThreshold=0)\r\n register_physical_object_setters(obj, sphere_idx)\r\n\r\n return sphere_idx\r\n\r\n @add_asset.register(core.FileBasedObject)\r\n def _add_object(self, obj: core.FileBasedObject) -> Optional[int]:\r\n # TODO: support other file-formats\r\n if obj.simulation_filename is None:\r\n return None # if there is no simulation file, then ignore this object\r\n path = pathlib.Path(obj.simulation_filename).resolve()\r\n logger.debug(\"Loading '%s' in the simulator\", path)\r\n\r\n if not path.exists():\r\n raise IOError(f\"File '{path}' does not exist.\")\r\n\r\n scale = obj.scale[0]\r\n assert obj.scale[1] == obj.scale[2] == scale, \"Pybullet does not support non-uniform scaling\"\r\n\r\n # useMaximalCoordinates and contactProcessingThreshold are required to\r\n # fix the sticky walls issue;\r\n # see https://github.com/bulletphysics/bullet3/issues/3094\r\n if path.suffix == \".urdf\":\r\n obj_idx = pb.loadURDF(str(path), useFixedBase=obj.static,\r\n globalScaling=scale,\r\n useMaximalCoordinates=True)\r\n else:\r\n raise IOError(\r\n \"Unsupported format '{path.suffix}' of file '{path}'\")\r\n\r\n if obj_idx < 0:\r\n raise IOError(f\"Failed to load '{path}'\")\r\n\r\n pb.changeDynamics(obj_idx, -1, contactProcessingThreshold=0)\r\n\r\n register_physical_object_setters(obj, obj_idx)\r\n return obj_idx\r\n\r\n def check_overlap(self, obj: core.PhysicalObject) -> bool:\r\n obj_idx = obj.linked_objects[self]\r\n\r\n body_ids = [pb.getBodyUniqueId(i) for i in range(pb.getNumBodies())]\r\n for body_id in body_ids:\r\n if body_id == obj_idx:\r\n continue\r\n overlap_points = pb.getClosestPoints(obj_idx, body_id, distance=0)\r\n if overlap_points:\r\n return True\r\n return False\r\n\r\n def get_position_and_rotation(self, obj_idx: int):\r\n pos, quat = pb.getBasePositionAndOrientation(obj_idx)\r\n return pos, xyzw2wxyz(quat) # convert quaternion format\r\n\r\n def get_velocities(self, obj_idx: int):\r\n velocity, angular_velocity = pb.getBaseVelocity(obj_idx)\r\n return velocity, angular_velocity\r\n\r\n def save_state(self, path: Union[pathlib.Path, str] = \"scene.bullet\"):\r\n \"\"\"Receives a folder path as input.\"\"\"\r\n assert self.scratch_dir is not None\r\n # first store in a temporary file and then copy, to support remote paths\r\n pb.saveBullet(str(self.scratch_dir / \"scene.bullet\"))\r\n tf.io.gfile.copy(self.scratch_dir / \"scene.bullet\", path, overwrite=True)\r\n\r\n def run(\r\n self,\r\n frame_start: int = 0,\r\n frame_end: Optional[int] = None\r\n ) -> Tuple[Dict[core.PhysicalObject, Dict[str, list]], List[dict]]:\r\n \"\"\"\r\n Run the physics simulation.\r\n\r\n The resulting animation is saved directly as keyframes in the assets,\r\n and also returned (together with the collision events).\r\n\r\n Args:\r\n frame_start: The first frame from which to start the simulation (inclusive).\r\n Also the first frame for which keyframes are stored.\r\n frame_end: The last frame (inclusive) that is simulated (and for which animations\r\n are computed).\r\n\r\n Returns:\r\n A dict of all animations and a list of all collision events.\r\n \"\"\"\r\n\r\n frame_end = self.scene.frame_end if frame_end is None else frame_end\r\n steps_per_frame = self.scene.step_rate // self.scene.frame_rate\r\n max_step = (frame_end - frame_start + 1) * steps_per_frame\r\n\r\n obj_idxs = [pb.getBodyUniqueId(i) for i in range(pb.getNumBodies())]\r\n animation = {obj_id: {\"position\": [], \"quaternion\": [], \"velocity\": [], \"angular_velocity\": []}\r\n for obj_id in obj_idxs}\r\n\r\n collisions = []\r\n for current_step in range(max_step):\r\n\r\n contact_points = pb.getContactPoints()\r\n for collision in contact_points:\r\n (contact_flag,\r\n body_a, body_b,\r\n link_a, link_b,\r\n position_a, position_b, contact_normal_b,\r\n contact_distance, normal_force,\r\n lateral_friction1, lateral_friction_dir1,\r\n lateral_friction2, lateral_friction_dir2) = collision\r\n del link_a, link_b # < unused\r\n del contact_flag, contact_distance, position_a # < unused\r\n del lateral_friction1, lateral_friction2 # < unused\r\n del lateral_friction_dir1, lateral_friction_dir2 # < unused\r\n if normal_force > 1e-6:\r\n collisions.append({\r\n \"instances\": (self._obj_idx_to_asset(body_b), self._obj_idx_to_asset(body_a)),\r\n \"position\": position_b,\r\n \"contact_normal\": contact_normal_b,\r\n \"frame\": current_step / steps_per_frame,\r\n \"force\": normal_force,\r\n })\r\n\r\n if current_step % steps_per_frame == 0:\r\n for obj_idx in obj_idxs:\r\n position, quaternion = self.get_position_and_rotation(obj_idx)\r\n velocity, angular_velocity = self.get_velocities(obj_idx)\r\n\r\n animation[obj_idx][\"position\"].append(position)\r\n animation[obj_idx][\"quaternion\"].append(quaternion)\r\n animation[obj_idx][\"velocity\"].append(velocity)\r\n animation[obj_idx][\"angular_velocity\"].append(angular_velocity)\r\n\r\n pb.stepSimulation()\r\n\r\n animation = {asset: animation[asset.linked_objects[self]] for asset in self.scene.assets\r\n if asset.linked_objects.get(self) in obj_idxs}\r\n\r\n # --- Transfer simulation to renderer keyframes\r\n for obj in animation.keys():\r\n for frame_id in range(frame_end - frame_start + 1):\r\n obj.position = animation[obj][\"position\"][frame_id]\r\n obj.quaternion = animation[obj][\"quaternion\"][frame_id]\r\n obj.velocity = animation[obj][\"velocity\"][frame_id]\r\n obj.angular_velocity = animation[obj][\"angular_velocity\"][frame_id]\r\n obj.keyframe_insert(\"position\", frame_id + frame_start)\r\n obj.keyframe_insert(\"quaternion\", frame_id + frame_start)\r\n obj.keyframe_insert(\"velocity\", frame_id + frame_start)\r\n obj.keyframe_insert(\"angular_velocity\", frame_id + frame_start)\r\n\r\n return animation, collisions\r\n\r\n def _obj_idx_to_asset(self, idx):\r\n assets = [asset for asset in self.scene.assets if asset.linked_objects.get(self) == idx]\r\n if len(assets) == 1:\r\n return assets[0]\r\n elif len(assets) == 0:\r\n return None\r\n else:\r\n raise RuntimeError(\"Multiple assets linked to same pybullet object. That should never happen\")\r\n\r\n\r\ndef xyzw2wxyz(xyzw):\r\n \"\"\"Convert quaternions from XYZW format to WXYZ.\"\"\"\r\n x, y, z, w = xyzw\r\n return w, x, y, z\r\n\r\n\r\ndef wxyz2xyzw(wxyz):\r\n \"\"\"Convert quaternions from WXYZ format to XYZW.\"\"\"\r\n w, x, y, z = wxyz\r\n return x, y, z, w\r\n\r\n\r\ndef register_physical_object_setters(obj: core.PhysicalObject, obj_idx):\r\n assert isinstance(obj, core.PhysicalObject), f\"{obj!r} is not a PhysicalObject\"\r\n\r\n obj.observe(setter(obj_idx, set_position), \"position\")\r\n obj.observe(setter(obj_idx, set_quaternion), \"quaternion\")\r\n # TODO Pybullet does not support rescaling. So we should warn if scale is changed\r\n obj.observe(setter(obj_idx, set_velocity), \"velocity\")\r\n obj.observe(setter(obj_idx, set_angular_velocity), \"angular_velocity\")\r\n obj.observe(setter(obj_idx, set_friction), \"friction\")\r\n obj.observe(setter(obj_idx, set_restitution), \"restitution\")\r\n obj.observe(setter(obj_idx, set_mass), \"mass\")\r\n obj.observe(setter(obj_idx, set_static), \"static\")\r\n\r\n\r\ndef setter(object_idx, func):\r\n def _callable(change):\r\n return func(object_idx, change.new, change.owner)\r\n return _callable\r\n\r\n\r\ndef set_position(object_idx, position, asset): # pylint: disable=unused-argument\r\n # reuse existing quaternion\r\n _, quaternion = pb.getBasePositionAndOrientation(object_idx)\r\n # resetBasePositionAndOrientation zeroes out velocities, but we wish to conserve them\r\n velocity, angular_velocity = pb.getBaseVelocity(object_idx)\r\n pb.resetBasePositionAndOrientation(object_idx, position, quaternion)\r\n pb.resetBaseVelocity(object_idx, velocity, angular_velocity)\r\n\r\n\r\ndef set_quaternion(object_idx, quaternion, asset): # pylint: disable=unused-argument\r\n quaternion = wxyz2xyzw(quaternion) # convert quaternion format\r\n # reuse existing position\r\n position, _ = pb.getBasePositionAndOrientation(object_idx)\r\n # resetBasePositionAndOrientation zeroes out velocities, but we wish to conserve them\r\n velocity, angular_velocity = pb.getBaseVelocity(object_idx)\r\n pb.resetBasePositionAndOrientation(object_idx, position, quaternion)\r\n pb.resetBaseVelocity(object_idx, velocity, angular_velocity)\r\n\r\n\r\ndef set_velocity(object_idx, velocity, asset): # pylint: disable=unused-argument\r\n _, angular_velocity = pb.getBaseVelocity(object_idx) # reuse existing angular velocity\r\n pb.resetBaseVelocity(object_idx, velocity, angular_velocity)\r\n\r\n\r\ndef set_angular_velocity(object_idx, angular_velocity, asset): # pylint: disable=unused-argument\r\n velocity, _ = pb.getBaseVelocity(object_idx) # reuse existing velocity\r\n pb.resetBaseVelocity(object_idx, velocity, angular_velocity)\r\n\r\n\r\ndef set_mass(object_idx, mass: float, asset):\r\n if mass < 0:\r\n raise ValueError(f\"mass cannot be negative ({mass})\")\r\n if not asset.static:\r\n pb.changeDynamics(object_idx, -1, mass=mass)\r\n\r\n\r\ndef set_static(object_idx, is_static, asset):\r\n if is_static:\r\n pb.changeDynamics(object_idx, -1, mass=0.)\r\n else:\r\n pb.changeDynamics(object_idx, -1, mass=asset.mass)\r\n\r\n\r\ndef set_friction(object_idx, friction: float, asset): # pylint: disable=unused-argument\r\n if friction < 0:\r\n raise ValueError(\"friction cannot be negative ({friction})\")\r\n pb.changeDynamics(object_idx, -1, lateralFriction=friction)\r\n\r\n\r\ndef set_restitution(object_idx, restitution: float, asset): # pylint: disable=unused-argument\r\n if restitution < 0:\r\n raise ValueError(\"restitution cannot be negative ({restitution})\")\r\n if restitution > 1:\r\n raise ValueError(\"restitution should be below 1.0 ({restitution})\")\r\n pb.changeDynamics(object_idx, -1, restitution=restitution)\r\n" ]
[ [ "tensorflow.io.gfile.copy" ] ]
tuantran1810/advanced-nlp
[ "35b4f156f6e3c3efaaf0014b101aa33bdc519c6b" ]
[ "models/text_generator.py" ]
[ "import torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nclass TextGeneratorModel(nn.Module):\n def __init__(self, vocab_size, emb_size, hidden_lstm, string_length = 250, hidden_fc = 200, lstm_layers = 2, batch_size = 32):\n super(TextGeneratorModel, self).__init__()\n self.__emb = nn.Embedding(vocab_size, emb_size)\n self.__lstm = nn.LSTM(emb_size, hidden_lstm, lstm_layers, bidirectional = True, batch_first = True, dropout = 0.1)\n self.__w = nn.Parameter(torch.randn(1, lstm_layers*hidden_lstm))\n self.__fc1 = nn.Linear(lstm_layers*hidden_lstm, hidden_fc)\n self.__fc2 = nn.Linear(hidden_fc, vocab_size)\n\n self.__lstm_layers = lstm_layers\n self.__hidden_lstm = hidden_lstm\n\n def init_hidden(self, batch_size):\n return (\n torch.zeros(size = (self.__lstm_layers*2, batch_size, self.__hidden_lstm)),\n torch.zeros(size = (self.__lstm_layers*2, batch_size, self.__hidden_lstm))\n )\n\n def infer(self, inp, hidden):\n self.eval()\n return self.__forward(inp, hidden)\n\n def forward(self, x):\n x, _ = self.__forward(x, None)\n return x\n\n def __forward(self, x, hidden):\n x = self.__emb(x)\n if hidden is not None:\n x, hidden = self.__lstm(x, hidden)\n else:\n x, hidden = self.__lstm(x)\n x = x.permute(0, 2, 1)\n m = torch.tanh(x)\n alpha = torch.matmul(self.__w, m).squeeze(1)\n alpha = F.softmax(alpha, dim = 1).unsqueeze(2)\n x = torch.matmul(x, alpha).squeeze(2)\n x = F.relu(self.__fc1(x))\n x = F.relu(self.__fc2(x))\n return x, hidden\n" ]
[ [ "torch.nn.functional.softmax", "torch.nn.LSTM", "torch.zeros", "torch.randn", "torch.nn.Embedding", "torch.tanh", "torch.nn.Linear", "torch.matmul" ] ]
KDriesen/slippy
[ "816723fe6ab9f5ed26b14b4fe0f66423649b85e6" ]
[ "slippy/contact/quasi_static_step.py" ]
[ "import numpy as np\nfrom numbers import Number\nimport typing\nimport warnings\n\nfrom .steps import _ModelStep\nfrom ._model_utils import get_gap_from_model\nfrom ._step_utils import HeightOptimisationFunction, make_interpolation_func\n\n__all__ = ['QuasiStaticStep']\n\n\nclass QuasiStaticStep(_ModelStep):\n \"\"\"\n A model step for quasi static relative movement\n\n To be used for loading, unloading and sliding as well as quasi static impacts, can be used for rolling-sliding\n with appropriate sub models for tangential behaviour.\n\n Parameters\n ----------\n\n step_name: str\n An identifying name for the step used for errors and outputs\n number_of_steps: int\n The number of sub steps the problem will be split into, together with the time_period this controls the duration\n of the time steps used\n no_time: bool, optional (False)\n Set to true if there is no time dependence and the time steps can be solved in any order (no permanent changes\n between steps such as plastic deformation or heat generation), if True the model will be solved more efficiently\n time_period: float, optional (1.0)\n The total time period of this model step, used for solving sub-models and writing outputs\n off_set_x, off_set_y: float or Sequence of float, optional (0.0)\n The off set between the surfaces in the x and y directions, this can be a relative off set or an absolute off\n set, controlled by the relative_loading parameter:\n\n * A constant (float) value, indicating a constant offset between the surfaces (no relative movement of profiles)\n * A two element sequence of floats, indicating the the start and finish offsets, if this is used, the\n movement_interpolation_mode will be used to generate intermediate values\n * A 2 by n array of n absolute position values and n time values normalised to a 0-1 scale. array[0] should be\n position values and array[1] should be time values, time values must be between 0 and 1. The\n movement_interpolation_mode will be used to generate intermediate values\n interference, normal_load: float or Sequence of float, optional (None)\n The interference and normal load between the surfaces, only one of these can be set (the other will be solved\n for) setting neither keeps the interference as it is at the start of this model step. As above for the off sets,\n either of these parameters can be:\n\n * A constant (float) value, indicating a constant load/ interference between the surfaces.\n * A two element sequence of floats, indicating the the start and finish load. interference, if this is used, the\n movement_interpolation_mode will be used to generate intermediate values\n * A 2 by n array of n absolute position values and n time values normalised to a 0-1 scale. array[0] should be\n position values and array[1] should be time values, time values must be between 0 and 1. The\n movement_interpolation_mode will be used to generate intermediate values\n relative_loading: bool, optional (False)\n If True the load or displacement and off set will be applied relative to the value at the start of the step,\n otherwise the absolute value will be used. eg, if the previous step ended with a load of 10N and this step ramps\n from 0 to 10N setting relative_loading to True will ramp the total load form 10 to 20N over this step.\n adhesion: bool, optional (True)\n If True the adhesion model set for the contact model will be used, If set to false this step will ignore the\n adhesion model (typically used for loading steps)\n unloading: bool, optional (False)\n If True the contact nodes will be constrained to be a sub set of those found in the previous time step.\n fast_ld: bool, optional (False)\n If True the load and displacements can be swapped to give a faster simulation, eg: if 100 equally spaced load\n steps are specified by a start and finish load, the displacement at the maximum load will be found and instead\n 100 equally spaced displacement controlled steps will solved between just touching and the maximum deflection.\n This swapping makes the computation much faster as it removes an optimisation loop.\n impact_properties: list, optional (None)\n This is currently not supported, providing a value will cause an error\n movement_interpolation_mode: str or int, optional ('linear')\n Any valid input to scipy.interpolate.interp1d as the 'kind' parameter, using 'nearest', 'previous' or 'next'\n will cause a warning. This parameter controls how the offset and loading is interpolated over the step\n profile_interpolation_mode: {'nearest', 'linear'}, optional ('nearest')\n Used to generate the grid points for the second surface at the location of the grid points for the first\n surface, nearest ensures compatibility with sub models which change the profile, if the grid spacings of the\n surfaces match\n periodic_geometry: bool, optional (False)\n If True the surface profile will warp when applying the off set between the surfaces\n periodic_axes: tuple, optional ((False, False))\n For each True value the corresponding axis will be solved by circular convolution, meaning the result is\n periodic in that direction\n periodic_im_repeats: tuple, optional (1,1)\n The number of times the influence matrix should be wrapped along periodic dimensions, only used if at least one\n of periodic axes is True. This is necessary to ensure truly periodic behaviour, no physical limit exists\n method: {'auto', 'pk', 'double'}, optional ('auto')\n The method by which the normal contact is solved, only used for load controlled contact.\n 'pk' uses the Polonsky and Keer algorithm for elastic contact.\n 'double' uses a double iteration procedure, suitable for elastic contact with a maximum pressure.\n 'auto' automatically selects 'pk' if there is no maximum pressure and 'double' if there is.\n max_it_interference: int, optional (100)\n The maximum number of iterations used to find the interference between the surfaces, only used if\n a total normal load is specified (Not used if contact is displacement controlled)\n rtol_interference: float, optional (1e-3)\n The relative tolerance on the load used as the convergence criteria for the interference optimisation loop, only\n used if a total normal load is specified (Not used if contact is displacement controlled)\n max_it_displacement: int, optional (100)\n The maximum number of iterations used to find the surface pressures from the interference, used for all IM\n based materials\n rtol_displacement: float, optional (1e-4)\n The norm of the residual used to declare convergence of the bccg iterations\n no_update_warning: bool, optional (True)\n Change to False to suppress warning given when no movement or loading changes are specified\n upper: float, optional (4.0)\n For load controlled contact the upper bound for the interference between the bodies will be this factor\n multiplied by the largest just touching gap. 4 is suitable for flat on flat contacts but for ball on flat\n contacts a lower value will give faster converging solutions\n\n Examples\n --------\n In the following example we model the contact between a rough cylinder and a flat plane.\n Both surface are elastic. This code could be used to generate load displacement curves.\n\n >>> import slippy.surface as s\n >>> import slippy.contact as c\n >>> # define contact geometry\n >>> cylinder = s.RoundSurface((1 ,np.inf, 1), shape=(256, 256), grid_spacing=0.001)\n >>> roughness = s.HurstFractalSurface(1, 0.2, 1000, shape=(256, 256), grid_spacing=0.001,\n >>> generate = True)\n >>> combined = cylinder + roughness * 0.00001\n >>> flat = s.FlatSurface(shape=(256, 256), grid_spacing=0.001, generate = True)\n >>> # define material behaviour and assign to surfaces\n >>> material = c.Elastic('steel', properties = {'E':200e9, 'v':0.3})\n >>> combined.material = material\n >>> flat.material = material\n >>>\n >>> # make a contact model\n >>> my_model = c.ContactModel('qss_test', combined, flat)\n >>>\n >>> # make a modelling step to describe the problem\n >>> max_int = 0.002\n >>> n_time_steps = 20\n >>> my_step = c.QuasiStaticStep('loading', n_time_steps, no_time=True,\n >>> interference = [max_int*0.001, max_int],\n >>> periodic_geometry=True, periodic_axes = (False, True))\n >>> # add the steps to the model\n >>> my_model.add_step(my_step)\n >>> # add output requests\n >>> output_request = c.OutputRequest('Output-1',\n >>> ['interference', 'total_normal_load',\n >>> 'loads_z', 'total_displacement',\n >>> 'converged'])\n >>> my_step.add_output(output_request)\n >>> # solve the model\n >>> final_result = my_model.solve()\n \"\"\"\n _just_touching_gap = None\n _adhesion_model = None\n _initial_contact_nodes = None\n _upper = None\n\n def __init__(self, step_name: str, number_of_steps: int, no_time: bool = False,\n time_period: float = 1.0,\n off_set_x: typing.Union[float, typing.Sequence[float]] = 0.0,\n off_set_y: typing.Union[float, typing.Sequence[float]] = 0.0,\n interference: typing.Union[float, typing.Sequence[float]] = None,\n normal_load: typing.Union[float, typing.Sequence[float]] = None,\n relative_loading: bool = False,\n adhesion: bool = True,\n unloading: bool = False,\n fast_ld: bool = False,\n impact_properties: dict = None,\n movement_interpolation_mode: str = 'linear',\n profile_interpolation_mode: str = 'nearest',\n periodic_geometry: bool = False, periodic_axes: tuple = (False, False),\n periodic_im_repeats: tuple = (1, 1), method: str = 'auto',\n max_it_interference: int = 100, rtol_interference=1e-3,\n max_it_displacement: int = None, rtol_displacement=1e-5, no_update_warning: bool = True,\n upper: float = 4.0):\n\n # movement interpolation mode sort out movement interpolation mode make array of values\n if impact_properties is not None:\n raise NotImplementedError(\"Impacts are not yet implemented\")\n # work out the time step if needed:\n self._no_time = no_time\n self.total_time = time_period\n if not no_time and fast_ld:\n raise ValueError(\"Cannot have time dependence and fast_ld, either set no_time True or set fast_ld False\")\n self._periodic_im_repeats = periodic_im_repeats\n self._fast_ld = fast_ld\n self._relative_loading = relative_loading\n self.profile_interpolation_mode = profile_interpolation_mode\n self._periodic_profile = periodic_geometry\n self._periodic_axes = periodic_axes\n self._max_it_interference = max_it_interference\n self._rtol_interference = rtol_interference\n self._max_it_displacement = max_it_displacement\n self._rtol_displacement = rtol_displacement\n self.number_of_steps = number_of_steps\n\n if method not in {'auto', 'pk', 'double'}:\n raise ValueError(f\"Unrecognised method for step {step_name}: {method}\")\n\n self._method = method\n self._height_optimisation_func = None\n self._adhesion = adhesion\n self._unloading = unloading\n self._upper_factor = upper\n\n self.time_step = time_period / number_of_steps\n\n # check that something is actually changing\n self.update = set()\n\n if not isinstance(off_set_x, Number) or not isinstance(off_set_y, Number):\n if no_time:\n raise ValueError(\"Can not have no time dependence and sliding contact\")\n off_set_x = [off_set_x] * 2 if isinstance(off_set_x, Number) else off_set_x\n off_set_y = [off_set_y] * 2 if isinstance(off_set_y, Number) else off_set_y\n off_set_x_func = make_interpolation_func(off_set_x, movement_interpolation_mode, 'relative_off_set_x')\n off_set_y_func = make_interpolation_func(off_set_y, movement_interpolation_mode, 'relative_off_set_y')\n self._off_set_upd = lambda time: np.array([off_set_x_func(time), off_set_y_func(time)])\n self.update.add('off_set')\n self.off_set = None\n else:\n self.off_set = np.array([off_set_x, off_set_y])\n\n if normal_load is not None and interference is not None:\n raise ValueError(\"Both normal_load and interference are set, only one of these can be set\")\n if normal_load is None and interference is None:\n if relative_loading:\n interference = 0\n else:\n raise ValueError(\"Cannot have no set load or interference and not relative loading, set either the\"\n \"normal load, normal interference or change relative_loading to True\")\n\n if normal_load is not None:\n if isinstance(normal_load, Number):\n self.normal_load = normal_load\n else:\n self.normal_load = None\n self._normal_load_upd = make_interpolation_func(normal_load, movement_interpolation_mode,\n 'normal_load')\n self.update.add('normal_load')\n self.load_controlled = True\n else:\n self.normal_load = None\n\n if interference is not None:\n if isinstance(interference, Number):\n self.interference = interference\n else:\n self.interference = None\n self._interference_upd = make_interpolation_func(interference, movement_interpolation_mode,\n 'interference')\n self.update.add('interference')\n self.load_controlled = False\n\n if not self.update and no_update_warning:\n warnings.warn(\"Nothing set to update\")\n\n provides = {'off_set', 'loads_z', 'surface_1_displacement_z', 'surface_2_displacement_z',\n 'total_displacement_z', 'interference', 'just_touching_gap', 'surface_1_points', 'contact_nodes',\n 'surface_2_points', 'time', 'time_step', 'new_step', 'converged', 'gap', 'total_normal_load'}\n super().__init__(step_name, time_period, provides)\n\n def solve(self, previous_state, output_file):\n current_time = previous_state['time']\n if self._fast_ld:\n # solve the normal contact problem\n raise NotImplementedError(\"TODO\")\n # TODO\n # change to disp controlled, set the displacement variable\n\n for s in self.sub_models:\n s.no_time = self._no_time\n\n if self.load_controlled:\n update_func = self._solve_load_controlled\n else: # displacement controlled\n update_func = self._solve_displacement_controlled\n\n relative_time = np.linspace(0, 1, self.number_of_steps + 1)[1:]\n just_touching_gap = None\n\n original = dict()\n\n if self._relative_loading:\n original['normal_load'] = previous_state['total_normal_load'] if 'total_normal_load' in previous_state \\\n else 0\n original['interference'] = previous_state['interference'] if 'interference' in previous_state else 0\n original['off_set'] = np.array(previous_state['off_set']) if 'off_set' in previous_state else \\\n np.array([0, 0])\n\n self._adhesion_model = self.model.adhesion if self._adhesion else None\n\n current_state = dict()\n\n for i in range(self.number_of_steps):\n self.update_movement(relative_time[i], original)\n # find overlapping nodes\n if 'off_set' in self.update or just_touching_gap is None or not self._no_time:\n just_touching_gap, surface_1_points, surface_2_points \\\n = get_gap_from_model(self.model, interference=0, off_set=self.off_set,\n mode=self.profile_interpolation_mode, periodic=self._periodic_profile)\n self._just_touching_gap = just_touching_gap\n self._upper = None\n current_state = dict(just_touching_gap=just_touching_gap, surface_1_points=surface_1_points,\n surface_2_points=surface_2_points, off_set=self.off_set,\n time_step=self.time_step)\n if i == 0:\n current_state['new_step'] = True\n else:\n current_state['new_step'] = False\n # solve contact\n if self._unloading and 'contact_nodes' in previous_state:\n initial_contact_nodes = previous_state['contact_nodes']\n else:\n initial_contact_nodes = None\n\n self._initial_contact_nodes = initial_contact_nodes\n print('#####################################################\\nTime step:', i,\n '\\n#####################################################')\n print('Set load:', self.normal_load)\n\n results = update_func(current_state)\n current_state.update(results)\n current_state['gap'] = (just_touching_gap - current_state['interference'] +\n current_state['total_displacement_z'])\n current_time += self.time_step\n current_state['time'] = current_time\n # solve sub models\n self.solve_sub_models(current_state)\n self.save_outputs(current_state, output_file)\n\n return current_state\n\n @property\n def upper(self):\n if self._upper is None:\n self._upper = np.max(self._just_touching_gap) * self._upper_factor\n return self._upper\n\n def update_movement(self, relative_time, original):\n for name in self.update:\n if self._relative_loading:\n self.__setattr__(name, original[name] + self.__getattribute__(f'_{name}_upd')(relative_time))\n else:\n self.__setattr__(name, self.__getattribute__(f'_{name}_upd')(relative_time))\n\n def _solve_load_controlled(self, current_state) -> dict:\n # if there is time dependence or we don't already have one, make a new height optimiser\n if not self._no_time or self._height_optimisation_func is None:\n opt_func = HeightOptimisationFunction(just_touching_gap=self._just_touching_gap,\n model=self.model,\n adhesion_model=self._adhesion_model,\n initial_contact_nodes=self._initial_contact_nodes,\n max_it_inner=self._max_it_displacement,\n tol_inner=self._rtol_displacement,\n material_options=dict(),\n max_set_load=self.normal_load,\n tolerance=self._rtol_interference,\n periodic_axes=self._periodic_axes,\n periodic_im_repeats=self._periodic_im_repeats)\n self._height_optimisation_func = opt_func\n else:\n opt_func = self._height_optimisation_func\n\n if self._unloading and 'contact_nodes' in current_state:\n contact_nodes = current_state['contact_nodes']\n else:\n contact_nodes = None\n # contact_nodes = np.ones(self._just_touching_gap.shape, dtype=np.bool)\n if self._method == 'auto':\n if np.isinf(opt_func.max_pressure):\n self._method = 'pk'\n else:\n self._method = 'double'\n\n if self._method == 'pk':\n opt_func.contact_nodes = None\n opt_func.p_and_k(self.normal_load)\n else:\n opt_func.change_load(self.normal_load, contact_nodes)\n # need to set bounds and pick a sensible starting point\n upper = self.upper\n print(f'upper bound set at: {upper}')\n if self._no_time:\n brackets = opt_func.get_bounds_from_cache(0, upper)\n else:\n brackets = (0, upper)\n print(f'Bounds adjusted using cache to: {brackets}')\n print(f'Interference tolerance set to {self._rtol_interference} Relative')\n opt_func.brent(0, upper, r_tol=self._rtol_interference, max_iter=self._max_it_interference)\n\n # noinspection PyProtectedMember\n\n results = opt_func.results\n load_conv = (np.abs(results['total_normal_load'] - self.normal_load) / self.normal_load) < 0.05\n results['converged'] = bool(load_conv) and not opt_func.last_call_failed\n return results\n\n def _solve_displacement_controlled(self, current_state):\n if not self._no_time or self._height_optimisation_func is None:\n h_opt_func = HeightOptimisationFunction(just_touching_gap=self._just_touching_gap,\n model=self.model,\n adhesion_model=self._adhesion_model,\n initial_contact_nodes=self._initial_contact_nodes,\n max_it_inner=self._max_it_displacement,\n tol_inner=self._rtol_displacement,\n material_options=dict(),\n max_set_load=1,\n tolerance=self._rtol_interference,\n periodic_axes=self._periodic_axes,\n periodic_im_repeats=self._periodic_im_repeats)\n self._height_optimisation_func = h_opt_func\n else:\n h_opt_func = self._height_optimisation_func\n\n if self._unloading and 'contact_nodes' in current_state:\n contact_nodes = current_state['contact_nodes']\n else:\n contact_nodes = None\n # contact_nodes = np.ones(self._just_touching_gap.shape, dtype=np.bool)\n\n h_opt_func.change_load(1, contact_nodes)\n _ = h_opt_func(self.interference, current_state)\n results = h_opt_func.results\n results['interference'] = self.interference\n results['converged'] = not h_opt_func.last_call_failed\n return results\n\n def __repr__(self):\n return f'{self.name}: QuasiStaticStep'\n" ]
[ [ "numpy.abs", "numpy.linspace", "numpy.max", "numpy.array", "numpy.isinf" ] ]
WeidongLi-KG/KBGAN_Pytorch-v0.4.1
[ "26f545ecf305ee1fc428901313a45b9766280433" ]
[ "trans_d.py" ]
[ "import os\nimport logging\nimport numpy as np\nimport torch as t\nimport torch.nn as nn\nimport torch.nn.functional as f\nfrom config import config\nfrom torch.optim import Adam, SGD, Adagrad\nfrom torch.autograd import Variable\nfrom data_utils import batch_by_num\nfrom base_model import BaseModel, BaseModule\n\nclass TransDModule(BaseModule):\n def __init__(self, n_ent, n_rel, config):\n super(TransDModule, self).__init__()\n self.margin = config.margin\n self.p = config.p\n self.temp = config.get('temp', 1)\n self.rel_embed = nn.Embedding(n_rel, config.dim)\n self.ent_embed = nn.Embedding(n_ent, config.dim)\n self.proj_rel_embed = nn.Embedding(n_rel, config.dim)\n self.proj_ent_embed = nn.Embedding(n_ent, config.dim)\n self.init_weight()\n\n def init_weight(self):\n for param in self.parameters():\n param.data.normal_(1 / param.size(1) ** 0.5)\n param.data.renorm_(2, 0, 1)\n\n def forward(self, src, rel, dst):\n src_proj = self.ent_embed(src) +\\\n t.sum(self.proj_ent_embed(src) * self.ent_embed(src), dim=-1, keepdim=True) * self.proj_rel_embed(rel)\n dst_proj = self.ent_embed(dst) +\\\n t.sum(self.proj_ent_embed(dst) * self.ent_embed(dst), dim=-1, keepdim=True) * self.proj_rel_embed(rel)\n return t.norm(dst_proj - self.rel_embed(rel) - src_proj + 1e-30, p=self.p, dim=-1)\n\n def dist(self, src, rel, dst):\n return self.forward(src, rel, dst)\n\n def score(self, src, rel, dst):\n return self.forward(src, rel, dst)\n\n def prob_logit(self, src, rel, dst):\n return -self.forward(src, rel ,dst) / self.temp\n\n def constraint(self):\n for param in self.parameters():\n param.data.renorm_(2, 0, 1)\n\nclass TransD(BaseModel):\n def __init__(self, n_ent, n_rel, config):\n super(TransD, self).__init__()\n self.mdl = TransDModule(n_ent, n_rel, config)\n self.mdl.cuda()\n self.config = config\n\n def load_vec(self, path):\n ent_mat = np.loadtxt(os.path.join(path, 'entity2vec.vec'))\n self.mdl.ent_embed.weight.data.copy_(t.from_numpy(ent_mat))\n rel_mat = np.loadtxt(os.path.join(path, 'relation2vec.vec'))\n n_rel = rel_mat.shape[0]\n self.mdl.rel_embed.weight.data.copy_(t.from_numpy(rel_mat))\n a_mat = np.loadtxt(os.path.join(path, 'A.vec'))\n self.mdl.proj_rel_embed.weight.data.copy_(t.from_numpy(a_mat[:n_rel, :]))\n self.mdl.proj_ent_embed.weight.data.copy_(t.from_numpy(a_mat[n_rel:, :]))\n self.mdl.cuda()\n\n def pretrain(self, train_data, corrupter, tester):\n src, rel, dst = train_data\n n_train = len(src)\n optimizer = Adam(self.mdl.parameters())\n #optimizer = SGD(self.mdl.parameters(), lr=1e-4)\n n_epoch = self.config.n_epoch\n n_batch = self.config.n_batch\n best_perf = 0\n for epoch in range(n_epoch):\n epoch_loss = 0\n rand_idx = t.randperm(n_train)\n src = src[rand_idx]\n rel = rel[rand_idx]\n dst = dst[rand_idx]\n src_corrupted, dst_corrupted = corrupter.corrupt(src, rel, dst)\n src_cuda = src.cuda()\n rel_cuda = rel.cuda()\n dst_cuda = dst.cuda()\n src_corrupted = src_corrupted.cuda()\n dst_corrupted = dst_corrupted.cuda()\n for s0, r, t0, s1, t1 in batch_by_num(n_batch, src_cuda, rel_cuda, dst_cuda, src_corrupted, dst_corrupted,\n n_sample=n_train):\n self.mdl.zero_grad()\n loss = t.sum(self.mdl.pair_loss(Variable(s0), Variable(r), Variable(t0), Variable(s1), Variable(t1)))\n loss.backward()\n optimizer.step()\n self.mdl.constraint()\n epoch_loss += loss.data[0]\n logging.info('Epoch %d/%d, Loss=%f', epoch + 1, n_epoch, epoch_loss / n_train)\n if (epoch + 1) % self.config.epoch_per_test == 0:\n test_perf = tester()\n if test_perf > best_perf:\n self.save(os.path.join(config().task.dir, self.config.model_file))\n best_perf = test_perf\n return best_perf\n" ]
[ [ "torch.randperm", "torch.from_numpy", "torch.nn.Embedding", "torch.autograd.Variable" ] ]
DanielWinklehner/py_rfq_helper
[ "98a471f529c9418f822c7c711bcbd8dd50bbb0ff" ]
[ "py_rfq_helper/plotbunchdata.py" ]
[ "import matplotlib.pyplot as plt\nimport pickle\nimport numpy as np\n\nbunch = pickle.load(open(\"bunch_particles.2.dump\", \"rb\"))\n\nz = bunch[\"z\"]\nvz = bunch[\"vz\"]\ny = bunch[\"y\"]\nx = bunch[\"x\"]\nxp = bunch[\"xp\"]\nyp = bunch[\"yp\"]\nidx = np.where(vz > 2.5e6)\n#idx = np.where(vz > 0)\n\nplt.scatter(z[idx] - np.mean(z[idx]), vz[idx], 15, marker='.')\nplt.xlabel(\"Z\")\nplt.ylabel(\"Vz\")\nplt.title(\"Vz vs. Z\")\n# plt.gca().set_aspect(\"equal\")\n\n# plt.scatter(x[idx], xp[idx], 10, marker='.')\n# plt.scatter(y[idx], yp[idx], 10, marker='.', c=\"red\")\n\n# plt.hist(z, 25)\n\nplt.show()" ]
[ [ "matplotlib.pyplot.title", "numpy.mean", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "numpy.where", "matplotlib.pyplot.ylabel" ] ]
andreamust/TPSD
[ "aa2bd70fb0439c9bea6cac949bb2fc555b187245" ]
[ "src/tpsd.py" ]
[ "# pylint: disable=line-too-long\n\"\"\"\nThis script contains a Python 3 re-implementation of the Tonal Pith Space Distance (TPSD) algorithm as presented in:\n\nDe Haas, W.B., Veltkamp, R.C., Wiering, F.: Tonal pitch step distance: a similarity measure for chord progressions.\nIn: ISMIR. pp. 51–56 (2008)\n\nAuthor: Andrea Poltronieri (University of Bologna) and Jacopo de Berardinis (King's College of London)\nCopyright: 2022 Andrea Poltronieri and Jacopo de Berardinis\nLicense: MIT license\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom src.tps_comparison import TpsComparison\n\n\nclass Tpsd:\n \"\"\"\n Implements the TPSD as described in De Haas et al.\n \"\"\"\n\n # pylint: disable=line-too-long\n # pylint: disable=consider-using-enumerate\n def __init__(self, chord_sequence: list[str], key: str, timing_information: list[int]) -> None:\n \"\"\"\n Initialises the parameters needed for calculating the TPSD distance\n :param chord_sequence: a list of chords expressed using the Harte notation\n :param key: the key of the chord sequence to which calculate the sequence distance.\n \"\"\"\n self.key = key\n self.chord_sequence = chord_sequence\n self.timing_information = timing_information\n\n def sequence_area(self) -> list[float]:\n \"\"\"\n Calculates the TPS distance between all chords of a given sequence and the triad chord of a given key\n :return: a list of all the TPS distances calculated between all the chord in the input sequence and the triad\n of the global key.\n \"\"\"\n tpsd = []\n for idx, chord in enumerate(self.chord_sequence):\n chord_tpsd = TpsComparison(chord_a=chord, key_a=self.key, chord_b=self.key, key_b=self.key)\n for _ in range(self.timing_information[idx]):\n tpsd.append(chord_tpsd.distance())\n\n return tpsd\n\n def plot_area(self) -> None:\n \"\"\"\n Plots the area calculated applying the TPS algorithm on a chord sequence\n :return: None but plots the area defined by the TPSD.\n \"\"\"\n sequence = self.sequence_area()\n # sequence.insert(0, sequence[0])\n\n plt.step(range(len(sequence)), sequence, 'orange')\n plt.yticks(np.arange(0, 13 + 1))\n plt.xticks(np.linspace(0, len(sequence), 15, dtype=int))\n plt.ylabel('TPS score')\n plt.xlabel('Beat')\n\n plt.fill_between(range(len(sequence)), sequence, step='pre', color='orange', alpha=0.4)\n\n plt.show()\n" ]
[ [ "numpy.arange", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
louis-pre/NewsBlur
[ "b4e9a56041ff187ef77b38dfd0778daf41b53f4f" ]
[ "apps/rss_feeds/icon_importer.py" ]
[ "import urllib.request\nimport urllib.error\nimport urllib.parse\nimport lxml.html\nimport numpy\nimport scipy\nimport scipy.misc\nimport scipy.cluster\nimport struct\nimport operator\nimport gzip\nimport datetime\nimport requests\nimport base64\nimport http.client\nfrom PIL import BmpImagePlugin, PngImagePlugin, Image\nfrom socket import error as SocketError\nimport boto3\nfrom io import BytesIO\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.contrib.sites.models import Site\nfrom apps.rss_feeds.models import MFeedPage, MFeedIcon\nfrom utils.facebook_fetcher import FacebookFetcher\nfrom utils import log as logging\nfrom utils.feed_functions import timelimit, TimeoutError\nfrom OpenSSL.SSL import Error as OpenSSLError, SESS_CACHE_NO_INTERNAL_STORE\nfrom pyasn1.error import PyAsn1Error\nfrom requests.packages.urllib3.exceptions import LocationParseError\n\n\nclass IconImporter(object):\n\n def __init__(self, feed, page_data=None, force=False):\n self.feed = feed\n self.force = force\n self.page_data = page_data\n self.feed_icon = MFeedIcon.get_feed(feed_id=self.feed.pk)\n\n def save(self):\n if not self.force and self.feed.favicon_not_found:\n # print 'Not found, skipping...'\n return\n if (\n not self.force\n and not self.feed.favicon_not_found\n and self.feed_icon.icon_url\n and self.feed.s3_icon\n ):\n # print 'Found, but skipping...'\n return\n if 'facebook.com' in self.feed.feed_address:\n image, image_file, icon_url = self.fetch_facebook_image()\n else:\n image, image_file, icon_url = self.fetch_image_from_page_data()\n if not image:\n image, image_file, icon_url = self.fetch_image_from_path(force=self.force)\n \n if not image:\n self.feed_icon.not_found = True\n self.feed_icon.save()\n self.feed.favicon_not_found = True\n self.feed.save()\n return False\n \n image = self.normalize_image(image)\n try:\n color = self.determine_dominant_color_in_image(image)\n except (IndexError, ValueError, MemoryError):\n logging.debug(\" ---> [%-30s] ~SN~FRFailed to measure icon\" % self.feed.log_title[:30])\n return\n try:\n image_str = self.string_from_image(image)\n except TypeError:\n return\n\n if len(image_str) > 500000:\n image = None\n if (image and\n (self.force or\n self.feed_icon.data != image_str or\n self.feed_icon.icon_url != icon_url or\n self.feed_icon.not_found or\n (settings.BACKED_BY_AWS.get('icons_on_s3') and not self.feed.s3_icon))):\n logging.debug(\" ---> [%-30s] ~SN~FBIcon difference:~FY color:%s (%s/%s) data:%s url:%s notfound:%s no-s3:%s\" % (\n self.feed.log_title[:30],\n self.feed_icon.color != color, self.feed_icon.color, color,\n self.feed_icon.data != image_str,\n self.feed_icon.icon_url != icon_url,\n self.feed_icon.not_found,\n settings.BACKED_BY_AWS.get('icons_on_s3') and not self.feed.s3_icon))\n self.feed_icon.data = image_str\n self.feed_icon.icon_url = icon_url\n self.feed_icon.color = color\n self.feed_icon.not_found = False\n self.feed_icon.save()\n if settings.BACKED_BY_AWS.get('icons_on_s3'):\n self.save_to_s3(image_str)\n if self.feed.favicon_color != color:\n self.feed.favicon_color = color\n self.feed.favicon_not_found = False\n self.feed.save(update_fields=['favicon_color', 'favicon_not_found'])\n \n return not self.feed.favicon_not_found\n\n def save_to_s3(self, image_str):\n expires = datetime.datetime.now() + datetime.timedelta(days=60)\n expires = expires.strftime(\"%a, %d %b %Y %H:%M:%S GMT\")\n base64.b64decode(image_str)\n settings.S3_CONN.Object(settings.S3_ICONS_BUCKET_NAME, \n self.feed.s3_icons_key).put(Body=base64.b64decode(image_str), \n ContentType='image/png',\n Expires=expires,\n ACL='public-read'\n )\n\n self.feed.s3_icon = True\n self.feed.save()\n\n def load_icon(self, image_file, index=None):\n '''\n DEPRECATED\n\n Load Windows ICO image.\n\n See http://en.wikipedia.org/w/index.php?oldid=264332061 for file format\n description.\n\n Cribbed and modified from http://djangosnippets.org/snippets/1287/\n '''\n try:\n image_file.seek(0)\n header = struct.unpack('<3H', image_file.read(6))\n except Exception:\n return\n\n # Check magic\n if header[:2] != (0, 1):\n return\n\n # Collect icon directories\n directories = []\n for i in range(header[2]):\n directory = list(struct.unpack('<4B2H2I', image_file.read(16)))\n for j in range(3):\n if not directory[j]:\n directory[j] = 256\n\n directories.append(directory)\n\n if index is None:\n # Select best icon\n directory = max(directories, key=operator.itemgetter(slice(0, 3)))\n else:\n directory = directories[index]\n\n # Seek to the bitmap data\n image_file.seek(directory[7])\n\n prefix = image_file.read(16)\n image_file.seek(-16, 1)\n\n if PngImagePlugin._accept(prefix):\n # Windows Vista icon with PNG inside\n try:\n image = PngImagePlugin.PngImageFile(image_file)\n except IOError:\n return\n else:\n # Load XOR bitmap\n try:\n image = BmpImagePlugin.DibImageFile(image_file)\n except IOError:\n return\n if image.mode == 'RGBA':\n # Windows XP 32-bit color depth icon without AND bitmap\n pass\n else:\n # Patch up the bitmap height\n image.size = image.size[0], image.size[1] >> 1\n d, e, o, a = image.tile[0]\n image.tile[0] = d, (0, 0) + image.size, o, a\n\n # Calculate AND bitmap dimensions. See\n # http://en.wikipedia.org/w/index.php?oldid=264236948#Pixel_storage\n # for description\n offset = o + a[1] * image.size[1]\n stride = ((image.size[0] + 31) >> 5) << 2\n size = stride * image.size[1]\n\n # Load AND bitmap\n image_file.seek(offset)\n string = image_file.read(size)\n mask = Image.frombytes('1', image.size, string, 'raw',\n ('1;I', stride, -1))\n\n image = image.convert('RGBA')\n image.putalpha(mask)\n\n return image\n\n def fetch_image_from_page_data(self):\n image = None\n image_file = None\n content = None\n if self.page_data:\n content = self.page_data\n elif settings.BACKED_BY_AWS.get('pages_on_node'):\n domain = Site.objects.get_current().domain\n url = \"https://%s/original_page/%s\" % (\n domain,\n self.feed.pk,\n )\n try:\n page_response = requests.get(url)\n if page_response.status_code == 200:\n content = page_response.content\n except requests.ConnectionError:\n pass\n elif settings.BACKED_BY_AWS.get('pages_on_s3') and self.feed.s3_page:\n key = settings.S3_CONN.Bucket(settings.S3_PAGES_BUCKET_NAME).Object(key=self.feed.s3_pages_key)\n compressed_content = key.get()[\"Body\"].read()\n stream = BytesIO(compressed_content)\n gz = gzip.GzipFile(fileobj=stream)\n try:\n content = gz.read()\n except IOError:\n pass\n else:\n content = MFeedPage.get_data(feed_id=self.feed.pk)\n url = self._url_from_html(content)\n if not url:\n try:\n content = requests.get(self.cleaned_feed_link, timeout=10).content\n url = self._url_from_html(content)\n except (AttributeError, SocketError, requests.ConnectionError,\n requests.models.MissingSchema, requests.sessions.InvalidSchema,\n requests.sessions.TooManyRedirects,\n requests.models.InvalidURL,\n requests.models.ChunkedEncodingError,\n requests.models.ContentDecodingError,\n http.client.IncompleteRead,\n requests.adapters.ReadTimeout,\n LocationParseError, OpenSSLError, PyAsn1Error,\n ValueError) as e:\n logging.debug(\" ---> ~SN~FRFailed~FY to fetch ~FGfeed icon~FY: %s\" % e)\n if url:\n image, image_file = self.get_image_from_url(url)\n return image, image_file, url\n \n @property\n def cleaned_feed_link(self):\n if self.feed.feed_link.startswith('http'):\n return self.feed.feed_link\n return 'http://' + self.feed.feed_link\n \n def fetch_image_from_path(self, path='favicon.ico', force=False):\n image = None\n url = None\n\n if not force:\n url = self.feed_icon.icon_url\n if not url and self.feed.feed_link and len(self.feed.feed_link) > 6:\n try:\n url = urllib.parse.urljoin(self.feed.feed_link, 'favicon.ico')\n except ValueError:\n url = None\n if not url:\n return None, None, None\n\n image, image_file = self.get_image_from_url(url)\n if not image:\n url = urllib.parse.urljoin(self.feed.feed_link, '/favicon.ico')\n image, image_file = self.get_image_from_url(url)\n # print 'Found: %s - %s' % (url, image)\n return image, image_file, url\n \n def fetch_facebook_image(self):\n facebook_fetcher = FacebookFetcher(self.feed)\n url = facebook_fetcher.favicon_url()\n image, image_file = self.get_image_from_url(url)\n if not image:\n url = urllib.parse.urljoin(self.feed.feed_link, '/favicon.ico')\n image, image_file = self.get_image_from_url(url)\n # print 'Found: %s - %s' % (url, image)\n return image, image_file, url\n \n def get_image_from_url(self, url):\n # print 'Requesting: %s' % url\n if not url:\n return None, None\n\n @timelimit(30)\n def _1(url):\n headers = {\n 'User-Agent': 'NewsBlur Favicon Fetcher - %s subscriber%s - %s %s' %\n (\n self.feed.num_subscribers,\n 's' if self.feed.num_subscribers != 1 else '',\n self.feed.permalink,\n self.feed.fake_user_agent,\n ),\n 'Connection': 'close',\n 'Accept': 'image/png,image/x-icon,image/*;q=0.9,*/*;q=0.8'\n }\n try:\n request = urllib.request.Request(url, headers=headers)\n icon = urllib.request.urlopen(request).read()\n except Exception:\n return None\n return icon\n try:\n icon = _1(url)\n except TimeoutError:\n return None, None\n\n try:\n icon_file = BytesIO(icon)\n image = Image.open(icon_file)\n except (IOError, ValueError):\n return None, None\n\n return image, icon_file\n\n def _url_from_html(self, content):\n url = None\n if not content:\n return url\n try:\n if isinstance(content, str):\n content = content.encode('utf-8')\n icon_path = lxml.html.fromstring(content).xpath(\n '//link[@rel=\"icon\" or @rel=\"shortcut icon\"]/@href'\n )\n except (lxml.etree.ParserError, TypeError):\n return url\n\n if icon_path:\n if str(icon_path[0]).startswith('http'):\n url = icon_path[0]\n else:\n url = urllib.parse.urljoin(self.feed.feed_link, icon_path[0])\n return url\n\n def normalize_image(self, image):\n # if image.size != (16, 16):\n # image = image.resize((16, 16), Image.BICUBIC)\n if image.mode != 'RGBA':\n try:\n image = image.convert('RGBA')\n except IOError:\n pass\n\n return image\n\n def determine_dominant_color_in_image(self, image):\n NUM_CLUSTERS = 5\n\n # Convert image into array of values for each point.\n if image.mode == '1':\n image.convert('L')\n ar = numpy.array(image)\n # ar = scipy.misc.fromimage(image)\n shape = ar.shape\n\n # Reshape array of values to merge color bands. [[R], [G], [B], [A]] => [R, G, B, A]\n if len(shape) > 2:\n ar = ar.reshape(scipy.product(shape[:2]), shape[2])\n \n # Get NUM_CLUSTERS worth of centroids.\n ar = ar.astype(numpy.float)\n codes, _ = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)\n\n # Pare centroids, removing blacks and whites and shades of really dark and really light.\n original_codes = codes\n for low, hi in [(60, 200), (35, 230), (10, 250)]:\n codes = scipy.array([code for code in codes\n if not ((code[0] < low and code[1] < low and code[2] < low) or\n (code[0] > hi and code[1] > hi and code[2] > hi))])\n if not len(codes):\n codes = original_codes\n else:\n break\n\n # Assign codes (vector quantization). Each vector is compared to the centroids\n # and assigned the nearest one.\n vecs, _ = scipy.cluster.vq.vq(ar, codes)\n\n # Count occurences of each clustered vector.\n counts, bins = scipy.histogram(vecs, len(codes))\n\n # Show colors for each code in its hex value.\n # colors = [''.join(chr(c) for c in code).encode('hex') for code in codes]\n # total = scipy.sum(counts)\n # print dict(zip(colors, [count/float(total) for count in counts]))\n\n # Find the most frequent color, based on the counts.\n index_max = scipy.argmax(counts)\n peak = codes.astype(int)[index_max]\n color = \"{:02x}{:02x}{:02x}\".format(peak[0], peak[1], peak[2])\n color = self.feed.adjust_color(color[:6], 21)\n\n return color\n\n def string_from_image(self, image):\n output = BytesIO()\n image.save(output, 'png', quality=95)\n contents = output.getvalue()\n output.close()\n return base64.b64encode(contents).decode()\n" ]
[ [ "scipy.cluster.vq.kmeans", "scipy.argmax", "scipy.product", "scipy.array", "numpy.array", "scipy.cluster.vq.vq" ] ]
prog-autom/hidden-demo
[ "26912cc2abe9984f204b9d5e0b1defb49a59d326" ]
[ "src/experiment.py" ]
[ "from sklearn import datasets\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport seaborn as sb\n\nfrom sklearn.linear_model import RidgeCV\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\nfrom sklearn import model_selection\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\n\nimport random\n\ndef init_random_state(seed):\n np.random.seed(int(seed))\n random.seed = int(seed)\n\ndef gbr_model(**kwargs):\n \"\"\"\n Creates a boosted trees regressor trained with a gradient descent method.\n\n Uses `GradientBoostingRegressor` from `scikit-learn`\n\n :param kwargs: parameters for `GradientBoostingRegressor`\n :return: an instance of regressor\n \"\"\"\n return GradientBoostingRegressor(**kwargs)\n\n\ndef ridge_model(**kwargs):\n \"\"\"\n Creates a pipeline of a data scaler and a ridge regression.\n Scaler transforms data to zero mean and unit variance.\n Hyperparameters or the regression are tuned via cross-validation\n\n Uses `StandardScaler` and `RidgeCV` from `scikit-learn`\n :param kwargs: parameters for `RidgeCV`\n :return: an instance of `Pipeline`\n \"\"\"\n return Pipeline([['scaler', StandardScaler()], ['ridgecv', RidgeCV(**kwargs)]])\n\n\ndef get_boston_dataset():\n \"\"\"\n Return a Boston dataset from `scikit-learn`\n :return: X, y and description\n \"\"\"\n # get dataset\n desc = datasets.load_boston()\n X, y = desc['data'], desc['target']\n return X, y, desc\n\n\ndef single_model_experiment(X, y, model, model_name=\"model\", train_size=0.9):\n \"\"\"\n Trains a `model` on the given dataset `X` with the target `y`.\n\n Saves regression plot to `{model_name}-train-test.png`\n\n :param X: dataset to train and test on (uses split via `train_size`)\n :param y: target variable for regression\n :param model: a class/constructor of the model, should be `callable` which returns and instance of the model with a `fit` method\n :param model_name: a filename for the model, may include path\n :param seed:\n :param train_size:\n :return: None\n \"\"\"\n\n X_train, X_test, \\\n y_train, y_test = model_selection.train_test_split(X, y, train_size=train_size)\n\n # Fit regression model\n gbr = model()\n gbr.fit(X_train, np.log(y_train))\n gbr_test = np.exp(gbr.predict(X_test))\n gbr_train = np.exp(gbr.predict(X_train))\n\n print('train: ', np.float16(mean_squared_error(y_train, gbr_train)),\n np.float16(r2_score(y_train, gbr_train)))\n print('test: ', np.float16(mean_squared_error(y_test, gbr_test)),\n np.float16(r2_score(y_test, gbr_test)))\n\n plt.figure()\n plt.title = \"Regression plot\"\n sb.regplot(x=y_train, y=gbr_train, label=\"Train\")\n sb.regplot(x=y_test, y=gbr_test, label=\"Test\")\n plt.legend()\n plt.xlabel('y')\n plt.ylabel('prediction')\n plt.savefig(f\"{model_name}-train-test.png\")\n\n\ndef feature_importances(clf, data, path, model_name=\"model\"):\n feature_importance = clf.feature_importances_\n # make importances relative to max importance\n feature_importance = 100.0 * (feature_importance / feature_importance.max())\n sorted_idx = np.argsort(feature_importance)\n pos = np.arange(sorted_idx.shape[0]) + .5\n plt.barh(pos, feature_importance[sorted_idx], align='center')\n plt.yticks(pos, data['feature_names'][sorted_idx])\n plt.xlabel('Relative Importance')\n plt.title('Variable Importance')\n plt.savefig(f\"{path}/{model_name}-feature-importance.png\")\n\n\ndef plot_gbr_deviance(X_test, y_test, gbr, path, model_name=\"model\"):\n # #############################################################################\n # Plot training deviance\n\n # compute test set deviance\n test_score = np.zeros((gbr.n_estimators,), dtype=np.float64)\n\n for i, y_pred in enumerate(gbr.staged_predict(X_test)):\n test_score[i] = gbr.loss_(y_test, np.exp(y_pred))\n\n plt.figure(figsize=(12, 6))\n plt.title('Deviance')\n plt.plot(np.arange(gbr.n_estimators) + 1, gbr.train_score_, 'b-',\n label='Training Set Deviance')\n plt.plot(np.arange(gbr.n_estimators) + 1, test_score, 'r-',\n label='Test Set Deviance')\n plt.legend(loc='upper right')\n plt.xlabel('Boosting Iterations')\n plt.ylabel('Deviance')\n plt.ylim(-0.1, 1)\n plt.savefig(f\"{path}/{model_name}-deviance.png\")\n \n\nclass HiddenLoopExperiment:\n \"\"\"\n The main experiment for hidden loops paper\n See details in the paper.\n\n In short.\n\n Creates a feedback loop on a regression problem (e.g. Boston housing).\n Some of the model predictions are adhered to by users and fed back into the model as training data.\n Users add a normally distributed noise to the log of the target variable (price).\n Uses a sliding window to retrain the model on new data.\n\n \"\"\"\n\n\n # params = {'loss':'huber', 'n_estimators': 1000, 'max_depth': 5, 'max_features': 1.0,\n # 'learning_rate': 0.01, 'random_state':0, 'subsample':0.5}\n default_params = {'loss':'ls', 'n_estimators': 50, \n 'max_depth': 3, 'max_features': 1.0,\n 'learning_rate': 0.5, 'random_state':0,\n 'subsample':0.75}\n\n default_state = {\n 'r2': 'R^2, dynamic data',\n 'mae': 'MAE, dynamic_data',\n 'r2_orig': 'R^2, original data',\n 'mae_orig': 'MAE, original data'\n }\n\n def __init__(self, X, y, model, model_name=\"model\"):\n \"\"\"\n Creates an instance of the experiment\n\n :param X: a dataset for regression\n :param y: target variable\n :param model: a class/constructor of the model, should be `callable` which returns and instance of the model with a `fit` method\n :param model_name: a filename to use for figures\n \"\"\"\n self.X = X\n self.y = y\n self.gbr_tst = []\n self.gbr_base = None\n self.model = model\n self.model_name = model_name\n\n def prepare_data(self, train_size=0.3):\n \"\"\"\n Initializes the experiment\n\n :param train_size: size of the sliding window as a portion of the dataset\n :return: None\n \"\"\"\n self.train_size = float(train_size)\n\n self.X_orig, self.X_new, self.y_orig, self.y_new = \\\n model_selection.train_test_split(\n self.X,\n np.log(self.y),\n train_size=self.train_size)\n\n self.train_len = len(self.X_orig)\n\n self.X_new, self.X_orig_tst, self.y_new, self.y_orig_tst = \\\n model_selection.train_test_split(\n self.X_new,\n self.y_new,\n test_size=int(0.25*len(self.X_orig)))\n \n self.X_curr = self.X_orig\n self.y_curr = self.y_orig\n self.mae, self.r2 = [], []\n self.mae_orig, self.r2_orig = [], []\n self.mae_new, self.r2_new = [], []\n\n def _add_instances(self, X, y, usage=0.9, adherence=0.9):\n \"\"\"\n This is a generator function (co-routine) for the sliding window loop.\n Works as follows.\n\n Called once when the loop is initialized.\n Python creates a generator that returns any values provided from this method.\n The method returns the next value via `yield` and continues when `next()` is called on the generator.\n\n `X` and `y` are set on the first invocation.\n\n :param X:\n :param y:\n :param usage: how closely users adhere to predictions: `0` means exactly\n :param adherence: share of users to follow prediction\n :return: yields a new sample index from `X`, new price - from `y` or as model predicted\n \"\"\"\n\n for sample in np.random.permutation(len(X)):\n if np.random.random() <= float(usage):\n pred = self.gbr.predict([X[sample]])\n new_price = np.random.normal(pred, self.m*float(adherence))[0]\n else:\n new_price = y[sample]\n\n yield sample, new_price\n\n def eval_m(self, model, X, y, mae=None, r2=None):\n gbr_pred = model.predict(X)\n \n mae_v = mean_absolute_error(y, gbr_pred)\n r2_v = r2_score(y, gbr_pred)\n \n if mae is not None:\n mae.append(mae_v)\n if r2 is not None:\n r2.append(r2_v)\n \n return mae_v, r2_v\n\n def hidden_loop_experiment(self, adherence=0.2, usage=0.1, step=10):\n \"\"\"\n Main method of the experiment\n\n :param seed:\n :param adherence: how closely users follow model predictions\n :param usage: how often users follow predictions\n :param step: number of steps the model is retrained\n :return: None\n \"\"\"\n \n self.X_tr, self.X_tst, self.y_tr, self.y_tst = model_selection.train_test_split(self.X_curr, self.y_curr)\n\n self.gbr_base = self.model()\n self.gbr_base.fit(self.X_tr, self.y_tr)\n \n self.gbr = self.model()\n self.gbr.fit(self.X_tr, self.y_tr)\n \n self.m, self.r = self.eval_m(self.gbr, self.X_tst, self.y_tst, self.mae, self.r2)\n m_b, r_b = self.eval_m(self.gbr_base, self.X_tst, self.y_tst)\n\n self.eval_m(self.gbr, self.X_orig_tst, self.y_orig_tst, self.mae_orig, self.r2_orig)\n self.eval_m(self.gbr, self.X_new, self.y_new, self.mae_new, self.r2_new)\n\n i = 0\n\n for idx, pred in self._add_instances(self.X_new, self.y_new,\n adherence=float(adherence), usage=float(usage)):\n self.X_curr = np.concatenate((self.X_curr[1:], [self.X_new[idx]]))\n self.y_curr = np.concatenate((self.y_curr[1:], [pred]))\n\n i = i + 1\n if i % int(step) == 0:\n self.X_tr, self.X_tst, \\\n self.y_tr, self.y_tst = model_selection.train_test_split(self.X_curr, self.y_curr)\n\n self.gbr = self.model()\n self.gbr.fit(self.X_tr, self.y_tr)\n\n self.m, self.r = self.eval_m(self.gbr, self.X_tst, self.y_tst, self.mae, self.r2)\n m_b, r_b = self.eval_m(self.gbr_base, self.X_tst, self.y_tst)\n\n self.eval_m(self.gbr, self.X_orig_tst, self.y_orig_tst, self.mae_orig, self.r2_orig)\n self.eval_m(self.gbr, self.X_new, self.y_new, self.mae_new, self.r2_new)\n\n\nclass MultipleResults:\n import pandas as pd\n\n def __init__(self, model_name, **initial_state):\n self.model_name = model_name\n self.state_vars = initial_state\n for k, v in initial_state.items():\n vars(self)[k] = list()\n\n def add_results(self, **update_state):\n for k in self.state_vars.keys():\n vars(self)[k].extend([{'round':i, k:j} for i, j in enumerate(update_state[k])])\n\n def plot_multiple_results(self, path):\n for k in self.state_vars.keys():\n data = MultipleResults.pd.DataFrame(data=vars(self)[k])\n\n plt.figure()\n ax = sb.lineplot(data=data, x=\"round\", y=k)\n ax.set(xlabel='rounds', ylabel=k, title=self.state_vars[k])\n plt.savefig(f\"{path}/{self.model_name}-{k}.png\")\n data.to_csv(f\"{path}/{self.model_name}-{k}.csv\")\n" ]
[ [ "matplotlib.pyplot.legend", "sklearn.metrics.r2_score", "matplotlib.pyplot.barh", "sklearn.metrics.mean_absolute_error", "sklearn.metrics.mean_squared_error", "numpy.concatenate", "sklearn.datasets.load_boston", "numpy.exp", "numpy.arange", "sklearn.ensemble.GradientBoostingRegressor", "sklearn.linear_model.RidgeCV", "numpy.zeros", "matplotlib.pyplot.figure", "numpy.log", "matplotlib.pyplot.title", "matplotlib.pyplot.ylim", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.savefig", "sklearn.preprocessing.StandardScaler", "numpy.argsort", "matplotlib.pyplot.ylabel", "numpy.random.random", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.yticks" ] ]
ashrefm/dt-grade-prediction
[ "6600f5fed8ccb44ba5493694ba57185742e6c898" ]
[ "app.py" ]
[ "# MIT License\n#\n# Copyright (c) 2019 Mohamed-Achref MAIZA\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE\n\n\"\"\"Flask App to demonstrate the ML inference system.\"\"\"\n\nimport json\nimport os\n\nimport numpy as np\nfrom numpy.linalg import norm\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.externals import joblib\nfrom pyemd import emd\nfrom flask import Flask\nfrom flask import jsonify\nfrom flask import render_template\nfrom flask import request\nfrom flask import url_for\n\nfrom utils import get_hash, load_model\nfrom utils import Featurizer\n\n\napp = Flask(__name__)\n\n\ndef get_features(landmarks, pd_hash, qu_hash, answer):\n \"\"\"\"Create all features to represent an observation.\n \n Args:\n landmarks (dataframe): landmark instances from preprocessing\n pd_hash (string) : hashkey of problem description\n qu_hash (string) : hashkey of question\n answer (string) : student response to question\n \n Returns:\n features : a numpy vector with float numbers\n \"\"\"\n \n # Get observation values\n emb = featurizer.doc2vec(answer)\n \n # Landmark of different question will get zero similarity (default)\n qu_land = landmarks.copy()\n qu_land['similarity'] = 0 # Compute cosine similarity with landmark\n qu_land['asym_diff_left'] = 0 # asymmetric difference between answer and landmark\n qu_land['asym_diff_right'] = 0 # asymmetric diffence between landmark and answer\n qu_land['word_match'] = 0 # word match between landmark and answer\n #qu_land['wmdist'] = 0 # world mover's distance between landmark and answer\n\n # Get index of landmarks with same problem and question \n idx = qu_land[(qu_land['pd_hash']==pd_hash)\\\n & (qu_land['qu_hash']==qu_hash)].index\n question_found = 1 if len(idx)>0 else 0\n\n # Compute similarity when embedding is not zero and landmark from same question\n if norm(emb)!=0:\n # Compute the direct similarity with these landmarks\n qu_land.loc[idx, 'similarity'] = qu_land.loc[idx, 'embedding']\\\n .apply(lambda x : featurizer.cossim_from_emb(emb, np.array(x)))\n # Compute the asymmetric difference between answer and landmark\n qu_land.loc[idx, 'asym_diff_left'] = qu_land.loc[idx, 'answer']\\\n .apply(lambda x : featurizer.asym_diff(answer, x))\n # Compute the asymmetric difference between landmark and answer\n qu_land.loc[idx, 'asym_diff_right'] = qu_land.loc[idx, 'answer']\\\n .apply(lambda x : featurizer.asym_diff(x, answer))\n # Compute the word match ratio between answer and landmark\n qu_land.loc[idx, 'word_match'] = qu_land.loc[idx, 'answer']\\\n .apply(lambda x : featurizer.word_match(answer, x))\n # Compute the world mover's distance between answer and landmark\n #qu_land.loc[idx, 'wmdist'] = qu_land.loc[idx, 'answer']\\\n # .apply(lambda x : featurizer.wmdist(obs['answer'], x))\n\n # Features will be all similarity measures to landmarks \n features = np.concatenate((qu_land['similarity'],\n qu_land['asym_diff_left'],\n qu_land['asym_diff_right'],\n qu_land['word_match']))\n \n # Add feature to indicate wether or not observation embedding was zero\n void_answer = 0\n if norm(emb)==0:\n features = np.append(1, features)\n void_answer = 1\n else:\n features = np.append(0, features)\n \n return features, question_found, void_answer\n\n\ndef get_prediction(landmarks, instance):\n \"\"\"Compute the prediction from instance features\n \n Args:\n landmarks (dataframe): landmark instances from preprocessing\n instance (dict) : contains intance data (pb_hash, qu_hash, answer)\n\n Returns: \n prediction (string) : e.g correct, incorrect,..\n \"\"\"\n \n pd_hash = instance['pd_hash']\n qu_hash = instance['qu_hash']\n answer = instance['answer']\n features, question_found, void_answer = get_features(\n landmarks,\n pd_hash,\n qu_hash,\n answer)\n if not question_found: return \"Unknown\"\n if void_answer: return \"Incorrect\"\n features = np.reshape(features, (1, len(features)))\n class_id = model.predict(features)[0]\n class_dict = {\n 0:'Correct', \n 1:'Correct but incomplete',\n 2:'Contradictory',\n 3:'Incorrect'\n }\n prediction = class_dict[class_id]\n return prediction\n\n\[email protected]('/')\ndef index():\n return render_template('index.html')\n\n\[email protected]('/form')\ndef input_form():\n return render_template('form.html')\n\n\[email protected]('/api/predict', methods=['POST'])\ndef predict():\n data = json.loads(request.data.decode())\n mandatory_items = ['problem', 'question', 'answer']\n for item in mandatory_items:\n if item not in data.keys():\n return jsonify({'result': 'Fill in all text fields.'})\n if item == '':\n return jsonify({'result': 'Empty field: %s' %item})\n instance = {}\n instance['pd_hash'] = get_hash(data['problem'])\n instance['qu_hash'] = get_hash(data['question'])\n instance['answer'] = data['answer']\n prediction = get_prediction(landmarks, instance)\n return jsonify({'result': prediction})\n\n \nif __name__ == \"__main__\":\n\n print(\"INFO: Starting DT-Grade Prediction App...\")\n \n # Read landmarks\n landmarks = pd.read_csv(os.path.join('munge', 'landmarks.txt'), sep=\"\\t\")\n landmarks['embedding'] = landmarks['embedding']\\\n .apply(lambda x : list(map(float, x.split(','))))\n if len(landmarks) == 0:\n raise Exception(\"Landmarks file is empty.\")\n else:\n print(\"INFO: Found %d landmark instances.\" %len(landmarks))\n\n # Create a featurizer object that converts a phrase into embedding\n # vector using pre-trained word2vec\n emb_file = os.path.join('data', 'GoogleNews-vectors-negative300.bin')\n featurizer = Featurizer(emb_file)\n\n # Load model\n model = load_model(os.path.join('model', 'multinomial_lr.pkl'))\n app.run(debug=True)" ]
[ [ "numpy.concatenate", "numpy.append", "numpy.array", "numpy.linalg.norm" ] ]
shoefer/ball_catching
[ "46b2e95894659347b563123c1c23742437755993" ]
[ "ball_catching/dynamics/world.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 16 11:24:25 2016\n\n@author: shoefer\n\"\"\"\n\nimport numpy as np\nimport os\nimport pandas as pd\n\nfrom ball_catching.utils.cont2discrete import cont2discrete\n\n# -----\n# state dim\n# 0 -> xb\n# 1 -> xb'\n# 2 -> xb''\n# 3 -> yb\n# 4 -> yb'\n# 5 -> yb''\n# 6 -> zb\n# 7 -> zb'\n# 8 -> zb''\n#\n# 9 -> xa\n# 10 -> xa'\n# 11 -> xa''\n# 12 -> za\n# 13 -> za'\n# 14 -> za''\nSTATE_DIM = 15\n\n# -----\n# action dim\nACTION_DIM = 2\n\n# -----\n# system\n\nA = np.array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 0 -> xb\n [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 1 -> xb'\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 2 -> xb''\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 3 -> yb\n [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 4 -> yb'\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 5 -> yb''\n [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], # 6 -> zb\n [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], # 7 -> zb'\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 8 -> zb''\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], # 9 -> xa\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 10 -> xa'\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 11 -> xa''\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], # 12 -> za\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 13 -> za'\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 14 -> za''\n ])\n\n# A = np.array([[ 0,\t1,\t0, 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0,\t0, 0, 0\t],\t# 0 -> xb\n#\t\t\t [ 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0,\t0, 0, 0\t],\t# 1 -> xb'\n#\t\t\t [ 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0,\t0, 0, 0\t],\t# 2 -> xb''\n# \t\t\t [ 0,\t0,\t0, 0,\t1,\t0, 0,\t0,\t0, 0,\t0,\t0,\t0, 0, 0\t],\t# 3 -> yb\n# \t\t\t [ 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0,\t0, 0, 0\t], # 4 -> yb'\n#\t\t\t [ 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0,\t0, 0, 0\t],\t# 5 -> yb''\n# \t\t\t [ 0,\t0,\t0, 0,\t0,\t0, 0,\t1,\t0, 0,\t0,\t0,\t0, 0, 0\t],\t# 6 -> zb\n# \t\t\t [ 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0,\t0, 0, 0\t],\t# 7 -> zb'\n#\t\t\t [ 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0,\t0, 0, 0\t],\t# 8 -> zb''\n# \t\t\t [ 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0, 0,\t1,\t0,\t0, 0, 0\t],\t# 9 -> xa\n# \t\t\t [ 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0,\t0, 0, 0\t],\t# 10 -> xa'\n# \t\t\t [ 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0,\t0, 0, 0\t],\t# 11 -> xa''\n# \t\t\t [ 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0,\t0, 1, 0\t],\t# 12 -> za\n# \t\t\t [ 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0,\t0, 0, 0 ],\t# 13 -> za'\n# \t\t\t [ 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0, 0,\t0,\t0,\t0, 0, 0 ],\t# 14 -> za''\n# \t\t\t ])\n\n# acceleration-based control\nBacc = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, ],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, ]]).T\n\n# velocity-based control\nBvel = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, ],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, ]]).T\n\n# observability is useful for Kalman filtering -> C only observes positions & agent velocities\nC = np.array([\n [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # xb\n [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # yb\n [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], # zb\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], # xa\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], # xa'\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], # za\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], # za'\n])\n\nD = 0\n\n\n# ----------------------------------------------------------------------------------------\n\nclass DynamicsModelType(type):\n def __call__(cls, *args, **kwargs):\n try:\n if len(args) == 0 and len(kwargs) == 0:\n return cls.__instance\n else:\n raise AttributeError()\n except AttributeError:\n dm = super(DynamicsModelType, cls).__call__(*args, **kwargs)\n if \"copy\" in kwargs and kwargs[\"copy\"]:\n print (\"WARN: Generating copy of DynamicsModel, not resetting global one\")\n return dm\n\n try:\n if cls.__instance is not None:\n print (\"INFO: Resetting global dynamics model\")\n except:\n pass\n\n cls.__instance = dm\n return cls.__instance\n\n\nclass DynamicsModel:\n __metaclass__ = DynamicsModelType\n\n def __init__(self, dt=None, framerate=None, gravity=9.81,\n v_max=9., a_max=4.5,\n rho=1.293, c=0.5, r=0.0366, mass=0.15,\n sigma_ball=0., sigma_agent=0.,\n drag=False,\n dim=None,\n wind_gust_force=[0., 0., 0.],\n wind_gust_duration=0.,\n wind_gust_relative_start_time=0.,\n copy=False):\n \"\"\"\n Singleton dynamics model.\n\n If you want to create a new dynamics model w/o overwriting\n the current global instance, then set \"copy=True\".\n \"\"\"\n\n self.DT = dt\n self.FRAMERATE = framerate\n self.GRAVITY = gravity\n\n # agent properties\n self.AGENT_V_MAX = v_max\n self.AGENT_A_MAX = a_max\n\n # drag-relevant ball dynamics\n self.rho = rho\n self.c = c\n self.r = r\n self.mass = mass\n # necessary for drag\n self.A = np.pi * self.r * self.r\n self.sigma_ball = sigma_ball\n self.sigma_agent = sigma_agent\n\n self.wind_gust_force = wind_gust_force\n self.wind_gust_duration = wind_gust_duration\n self.wind_gust_relative_start_time = wind_gust_relative_start_time\n\n # dimensionality: 2d or 3d (for sampling noise)\n self.dim = dim\n assert (self.dim is not None)\n self.drag = drag\n\n # discretized system matrices\n self.Adt = None\n self.Baccdt = None\n self.Bacc = None\n self.B = None\n self.Bdt = None\n self.cdt = None\n\n self.Bvel = None\n self.Cdt = None\n self.Ddt = None\n\n self.compute_J_drag = None\n\n self.copy = copy\n self._generate_dynamics()\n\n def _generate_dynamics(self):\n if self.DT is not None:\n assert (self.FRAMERATE is None)\n self.FRAMERATE = 1. / self.DT\n else:\n assert (self.FRAMERATE is not None)\n self.DT = 1. / self.FRAMERATE\n\n # discretize system\n self.Adt, self.Baccdt, self.Cdt, self.Ddt, dt = cont2discrete((A, Bacc, C, D), self.DT)\n self.Adt, self.Bveldt, self.Cdt, self.Ddt, dt = cont2discrete((A, Bvel, C, D), self.DT)\n\n # default: acceleration driven dynamics\n self.B = Bacc\n self.Bdt = self.Baccdt\n\n # constant offset in ddy: gravity\n self._GRAVITY_VECTOR = np.array([0, -self.GRAVITY, 0])\n self.cdt = np.zeros(self.Adt.shape[0])\n self.cdt[5] = -self.GRAVITY\n # hacky: set ddx(t) = 0 (because it is covered by constant offset)\n self.Adt[2, 2] = self.Adt[5, 5] = self.Adt[8, 8] = 0\n\n if self.copy:\n print (\"---------\")\n print (\"Local Dynamics: \")\n else:\n print (\"=========\")\n print (\"GLOBAL Dynamics: \")\n\n print (\"Dimensionality: %d \" % self.dim)\n print (\" DT=%.5f, FRAMERATE=%.1f\" % (self.DT, self.FRAMERATE))\n print (\" drag=%s\" % (self.drag))\n print (\"Agent: \")\n print (\" AGENT_A_MAX = %.2f\" % self.AGENT_A_MAX)\n print (\" AGENT_V_MAX = %.2f\" % self.AGENT_V_MAX)\n print (\"Ball: \")\n print (\" radius = %.5f\" % self.r)\n print (\" mass = %.5f\" % self.mass)\n print (\" c = %.5f\" % self.c)\n if self.copy:\n print (\"---------\")\n else:\n print (\"=========\")\n\n def is_equivalent(self, dyn):\n return np.all([\n self.DT == dyn.DT,\n self.FRAMERATE == dyn.FRAMERATE,\n self.GRAVITY == dyn.GRAVITY,\n self.AGENT_V_MAX == dyn.AGENT_V_MAX,\n self.AGENT_A_MAX == dyn.AGENT_A_MAX,\n self.rho == dyn.rho,\n self.c == dyn.c,\n self.r == dyn.r,\n self.mass == dyn.mass,\n self.drag == dyn.drag,\n self.dim == dyn.dim,\n ])\n\n def set_presimulate(self):\n self._presimulate = True\n self._epsilons = []\n\n def set_run(self):\n self._presimulate = False\n # revert episilon for \"popping\"\n # print (\"len(self._epsilons)\", len(self._epsilons))\n self._epsilons = list(reversed(self._epsilons))\n\n def set_stop(self):\n if not self.is_nonlinear():\n return True\n\n sn = len(self._epsilons) == 0\n self._epsilons = []\n return sn\n\n def _sample_system_noise(self):\n if self.is_nonlinear() and not self._presimulate:\n return self._epsilons.pop()\n\n s_ball = np.random.randn(3) * self.sigma_ball\n s_agent = np.random.randn(2) * self.sigma_agent\n\n # we assume we are applying a random FORCE to the ball\n # but we add acceleration to the model, so we need to convert:\n # a = F/m\n s_ball /= self.mass\n\n s = np.zeros(STATE_DIM)\n # affects position\n # dims_ball = [0, 3, 6]\n # dims_agent = [9, 12]\n\n # affects acceleration\n dims_ball = [2, 5, 8]\n dims_agent = [11, 14]\n\n # assign\n s[dims_ball] = s_ball\n s[dims_agent] = s_agent\n # check dimensionality\n if self.dim == 2:\n s[dims_ball[-1]] = 0.\n s[dims_agent[-1]] = 0.\n\n if self.has_wind():\n s += self.noise_wind_current\n self.noise_wind_current[:] = 0. # delete\n\n if self.is_nonlinear():\n self._epsilons.append(s)\n\n return s\n\n def is_nonlinear(self):\n return self.sigma_ball > 0 or self.drag or self.has_wind\n\n def is_ball_on_ground(self, x_t):\n return x_t[3] < 0\n\n def step(self, x_t, u_t, noise=True):\n if self.drag:\n return self.step_drag(x_t, u_t, noise=noise)\n else:\n return self.step_linear(x_t, u_t, noise=noise)\n\n def step_linear(self, x_t, u_t, noise=True):\n \"\"\" Evaluate the system x and u at one time step \"\"\"\n # linear system\n # sys.stdout.write(\"[\"+str((sgm)) + \"] \\n\")\n # sys.stdout.flush()\n\n cdt = self.cdt\n if len(x_t.shape) == 2:\n cdt = cdt.reshape((-1, 1))\n else:\n cdt = cdt.reshape((-1,))\n\n x = np.dot(self.Adt, x_t) + np.dot(self.Bdt, u_t) + cdt\n\n if noise:\n # ball: set acceleration due to gravity (because might get overwritten)\n # due to our constant acceleration model\n # x[2], x[5], x[8] = self._GRAVITY_VECTOR # FIXME\n\n sgm = self._sample_system_noise()\n if np.any(sgm != 0.):\n # add noise\n x += sgm\n\n # sys.stdout.write(\"\"+str(x) + \" \\n\")\n # sys.stdout.write(\"\" + str(sgm) + \" \\n\")\n # sys.stdout.flush()\n\n return x\n\n def step_drag(self, x_t, u_t, noise=True):\n \"\"\"\n Compared to\n http://www.livephysics.com/simulations/mechanics-sim/projectile-motion-simulation/\n \"\"\"\n # x = self.step_linear(x_t, u_t)\n # x = np.dot(self.Adt, x_t) + np.dot(self.Bdt, u_t)\n\n x_t_ = np.asarray(x_t).reshape((-1,))\n u_t_ = np.asarray(u_t).reshape((-1,))\n\n x = np.dot(self.Adt, x_t_) + np.dot(self.Bdt, u_t_) + self.cdt.reshape((-1,))\n\n v = np.array([x[1], x[4], x[7]])\n # new acceleration\n # x[2], x[5], x[8] = self._GRAVITY_VECTOR - v*v * 0.5 * self.rho * self.c * self.A/self.mass\n ddx = - v * v * 0.5 * self.rho * self.c * self.A / self.mass\n for i, idx in enumerate([2, 5, 8]):\n x[idx] += ddx[i]\n\n if noise:\n sgm = self._sample_system_noise()\n # sys.stdout.write(\"[\"+str(max(sgm)) + \"] \")\n # sys.stdout.flush()\n x += sgm\n\n return x\n\n def has_wind(self):\n return np.any(np.abs(self.wind_gust_force)) > 0 and self.wind_gust_duration > 0.\n\n def precompute_trajectory(self, x0):\n # get linear duration\n t_n, N, x_n, z_n = self.get_time_to_impact(x0)\n fr = DynamicsModel().FRAMERATE\n\n if not self.is_nonlinear():\n # nothing to do\n return t_n, N, x_n, z_n\n\n self.set_presimulate()\n\n if self.has_wind():\n assert (self.wind_gust_relative_start_time >= 0. and self.wind_gust_relative_start_time < 1.)\n self.wind_gust_start_time = t_n * self.wind_gust_relative_start_time\n # self.wind_gust_end_time = t_n * (self.wind_gust_relative_start_time+self.wind_gust_duration)\n self.wind_gust_end_time = t_n * (self.wind_gust_relative_start_time) + self.wind_gust_duration\n print (\"Dynamics: wind_gust -> %.2f s to %.2f s -> %d to %d\" \\\n % (self.wind_gust_start_time, self.wind_gust_end_time, round(self.wind_gust_start_time / fr),\n round(self.wind_gust_end_time / fr)))\n self.noise_wind_current = np.zeros(STATE_DIM)\n\n dims_ball = [2, 5, 8] # FIXME copied\n\n # we need to pre-simulate\n x_ = x0.reshape((-1,))\n i = 0\n while i == 0 or x_[3] > 0.:\n tcur = i / fr\n\n # wind\n if self.has_wind():\n self.noise_wind_current[:] = 0.\n if tcur > self.wind_gust_start_time and tcur < self.wind_gust_end_time:\n self.noise_wind_current[dims_ball] = self.wind_gust_force\n self.noise_wind_current[dims_ball] /= self.mass # it's a force\n # print (\"WIND! %d, %f\" % (i, tcur, ))\n # print self.noise_wind_current[dims_ball]\n\n x_ = self.step(x_, [0., 0.]).reshape((-1,))\n i += 1\n\n # print \"last x \", x_[3]\n\n t_n = i / fr\n x_n = x_[0]\n z_n = x_[6]\n\n self.set_run()\n\n return t_n, i, x_n, z_n\n\n def get_time_to_impact(self, x0, ignore_drag=False):\n \"\"\"\n Returns time to impact related variables as tuple:\n - t seconds\n - N steps at current framerate\n - x position of ball\n - z position of ball\n\n \"\"\"\n\n drag = self.drag\n if ignore_drag:\n drag = False\n\n x0 = x0.flatten()\n\n if x0[3] < 0:\n return 0, 0, 0, 0\n\n if not drag:\n g = self.GRAVITY\n a, b, c = -g / 2, x0[4], x0[3]\n\n phalf = - b / (2.0 * a)\n pm_term = np.sqrt((b ** 2) / (4 * a ** 2) - c / a)\n t_n = phalf + pm_term\n x_n = x0[1] * t_n + x0[0]\n z_n = 0.\n\n else:\n # dynamics.set_presimulate()\n\n # we need to pre-simulate\n x_ = x0.reshape((-1,))\n i = 0\n while i == 0 or x_[3] > 0.:\n x_ = self.step_drag(x_, [0., 0.], noise=False).reshape((-1,))\n i += 1\n\n t_n = i / self.FRAMERATE\n x_n = x_[0]\n z_n = x_[6]\n\n assert (not np.isnan(t_n))\n\n # t_n seconds at current FRAMERATE\n N = int(np.ceil(t_n * self.FRAMERATE))\n\n return t_n, N, x_n, z_n\n\n def compute_J(self, x_t, u_t):\n if self.drag:\n if self.compute_J_drag is None:\n self._derive_drag_jacobian()\n return np.asarray(self.compute_J_drag(x_t, u_t))\n else:\n return self.Adt\n\n def _derive_drag_jacobian(self):\n # dt = self.DT\n g = self.GRAVITY\n rho, c, Ac, mass = self.rho, self.c, self.A, self.mass\n\n import sympy as sp\n from sympy.abc import x, y, z\n # from sympy import symbols, Matrix\n\n dx, dy, dz, ddx, ddy, ddz = sp.symbols(\"dx, dy, dz, ddx, ddy, ddz\")\n ax, az, dax, daz, ddax, ddaz = sp.symbols(\"ax, az, dax, daz, ddax, ddaz\")\n X = sp.Matrix([x, dx, ddx, y, dy, ddy, z, dz, ddz,\n ax, dax, ddax, az, daz, ddaz, ])\n\n ux, uz = sp.symbols(\"ux, uz\")\n U = sp.Matrix([ux, uz])\n\n A = sp.Matrix(self.Adt)\n B = sp.Matrix(self.Bdt)\n f_xu = sp.Matrix(A.dot(X)) + sp.Matrix(B.dot(U))\n # drag\n v = sp.Matrix([dx, dy, dz])\n\n # wrong: dd* does not evolve depending on the previous time step\n # f_xu[2], f_xu[5], f_xu[8] = sp.Matrix([ddx, ddy, ddz]) \\\n\n # Correct but -g is constant and will thus disappear from Jacobian\n # -> put it into starting state\n # f_xu[2], f_xu[5], f_xu[8] = sp.Matrix([0, -g, 0]) \\\n # - v.multiply_elementwise(v) * 0.5 * rho * c * Ac/mass\n\n # Correct: ddx and ddz solely depend on squared velocity\n f_xu[2], f_xu[5], f_xu[8] = \\\n - v.multiply_elementwise(v) * 0.5 * rho * c * Ac / mass\n\n self.FJ_drag = f_xu.jacobian(sp.Matrix([X]))\n self._compute_J_drag = sp.lambdify((dx, dy, dz), self.FJ_drag)\n self.compute_J_drag = lambda x, _: self._compute_J_drag(x[1], x[4], x[7])\n\n def observe_state(self, x_t):\n return self.C.dot(x_t)\n\n @property\n def state_dim(self):\n return self.Adt.shape[0]\n\n @property\n def action_dim(self):\n return self.Bdt.shape[1]\n\n @property\n def observation_dim(self):\n return self.Cdt.shape[0]\n\n\n# ----------------------------------------------------------------------------------------\n\nclass RecordedTrajectoryStepper:\n #required_cols = [\"x\", \"y\", \"z\", \"vx\", \"vy\", \"vz\", \"ax\", \"ay\", \"az\", ]\n required_cols = [\"x\", \"vx\", \"ax\", \"y\", \"vy\", \"ay\", \"z\", \"vz\", \"az\", ]\n\n def __init__(self, pd_pkl, dt=None):\n if dt is None:\n DT = dt = DynamicsModel().DT\n \n self.tj = pd.read_pickle(pd_pkl)\n assert (np.all([col in self.tj.columns for col in self.required_cols ]))\n \n if \"t\" in self.tj.columns:\n # downsample if necessary\n dt = round(self.tj.iloc[1].t - self.tj.iloc[0].t, 5)\n assert (round(DT, 5) == dt)\n \n # HACK: we need to append an additional column where the ball's height < 0\n if self.tj.iloc[-1].y > 0:\n xT = np.zeros((STATE_DIM,))\n xT = self._copy(self.tj.iloc[-1], xT)\n xTp1 = DynamicsModel().step(xT, np.zeros((ACTION_DIM,)))\n \n # copy back\n t_next = self.tj.iloc[-1].t+DT\n # create\n new_idx = len(self.tj)\n self.tj.loc[new_idx] = np.nan\n # set time\n self.tj.loc[new_idx,\"t\"] = t_next\n # set rest\n for c, v in zip(self.required_cols, xTp1[:9]):\n #self.tj.loc[t_next][c] = v\n self.tj.loc[new_idx,c] = v\n if self.tj.loc[new_idx,\"y\"] > 0:\n self.tj.loc[new_idx,\"y\"]*= -1\n\n path, basename = os.path.split(pd_pkl)\n fn_rsmpl = os.path.join(path, os.path.splitext(basename)[0] + (\"_dt%.4f_fixed\" % DT) + \".pkl\")\n self.tj.to_pickle(fn_rsmpl)\n \n self.idx = 0\n self.t = 0\n\n def initialize_for_trial(self):\n pass\n\n def _copy(self, tj_t, x):\n x[:3] = tj_t.x, tj_t.vx, tj_t.ax\n x[3:6] = tj_t.y, tj_t.vy, tj_t.ay\n x[6:9] = tj_t.z, tj_t.vz, tj_t.az\n\n # v and a are NaN in the beginning\n x = np.nan_to_num(x)\n\n return x \n \n def __call__(self, x_t, u_t):\n x = DynamicsModel().step(x_t, u_t)\n \n tj_t = self.tj.iloc[self.idx]\n x = self._copy(tj_t, x)\n\n assert (not np.any (np.isnan(x)))\n \n self.idx += 1\n \n return x\n\n#-----------------------------------------------------------------------------------------\n\n\ndef parabola_find_null_points(a,b,c):\n # FIXME delete\n phalf = - b/(2.0*a)\n pm_term = np.sqrt( (b**2) / (4*a**2) - c/a)\n if b > 0:\n return (phalf+pm_term, phalf-pm_term)\n else:\n return (np.abs(phalf-pm_term), phalf+pm_term)\n\n# ----------------------------------------------------------------------------------------\n\ndef observe_angle_and_distance(x_t): \n # ball height\n yb = x_t[3]\n \n if yb < 0:\n return 0.,0.\n \n d = np.sqrt ( (x_t[0] - x_t[9])**2 + (x_t[3])**2 + (x_t[6] - x_t[12])**2)\n \n if d <= 0.:\n return 0.,0.\n \n # compute angle alpha\n alpha = np.arcsin( yb/d )\n if x_t[0]>x_t[9]:\n #d=-d\n alpha=np.pi-alpha\n pass\n \n return alpha,d\n \ndef normalize_angle(angle):\n if np.abs(angle) > np.pi:\n if angle > 0:\n angle = - (2*np.pi - angle)\n else:\n angle = 2*np.pi + angle\n return angle \n\n\ndef compute_bearing_angle(xt):\n ba = np.array([xt[9]-xt[0], xt[12]-xt[6]])\n ba /= np.linalg.norm(ba)\n \n a2bt = np.arctan2(ba[0], ba[1])\n a2bt = normalize_angle(a2bt)\n \n return a2bt \n \n# ----------------------------------------------------------------------------------------\n\ndef observation_noise_ball(x, std=[0.01,0.01,0.01], noiseDistFactor=0.05, noise_dim=-1):\n std = np.array(std)\n if noiseDistFactor != 0.:\n # agent ball distance\n d = np.linalg.norm(x[[0,3,6]]-np.array([x[9],0.,x[12]]))\n std *= noiseDistFactor*d\n\n current_position_noise = np.zeros(std.shape)\n for i,s in enumerate(std):\n if s > 0:\n current_position_noise[i] = np.random.normal(0., s)\n \n xn = np.zeros(x.shape)\n xn[:] = x[:]\n \n for i,idx in enumerate([0,3,6]):\n if noise_dim == -1 or i != noise_dim:\n xn[ idx ] += current_position_noise[i]\n \n# print current_position_noise\n# print \"was, \", x\n# print \"NOISE, \", xn\n \n return xn\n\n# ----------------------------------------------------------------------------------------\n\n" ]
[ [ "numpy.dot", "pandas.read_pickle", "numpy.sqrt", "numpy.abs", "numpy.arcsin", "numpy.isnan", "numpy.asarray", "numpy.linalg.norm", "numpy.nan_to_num", "numpy.arctan2", "numpy.all", "numpy.ceil", "numpy.random.normal", "numpy.random.randn", "numpy.any", "numpy.array", "numpy.zeros" ] ]
Tastalian/avp-rrt-rss-2013
[ "d3d9b50bb582c23a4ee83408b26bcede4d84469e" ]
[ "rrtcmp/misc.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2013 Stephane Caron <[email protected]>\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# 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 pylab\nfrom numpy import fmod, pi, array\n\n\ndef center_angle(theta):\n theta = fmod(theta, 2 * pi)\n if theta > pi:\n return theta - 2 * pi\n if theta < -pi:\n return theta + 2 * pi\n return theta\n\n\ndef center_angle_vect(q):\n return array(map(center_angle, q))\n\n\ndef put_symbol(q, color, markersize=10):\n pylab.plot([q[0]], [q[1]], color, markersize=markersize)\n" ]
[ [ "numpy.fmod" ] ]
Project-Fare/quantum_computation
[ "fc182007d0cf7cca170efdbcb442576fde5927ff" ]
[ "TFQ/qosf/gates.py" ]
[ "import numpy as np\r\nimport math\r\n\r\nouter_00 = np.array([[1, 0], [0, 0]])\r\nouter_11 = np.array([[0, 0], [0, 1]])\r\n\r\nclass X(object):\r\n def __init__(self, qubit=None) -> None:\r\n super().__init__()\r\n self.op = np.array([\r\n [0, 1],\r\n [1, 0]\r\n ])\r\n self.on = qubit\r\n\r\nclass Y(object):\r\n def __init__(self, qubit=None) -> None:\r\n super().__init__()\r\n self.op = np.array([\r\n [0, -1j],\r\n [1j, 0]\r\n ])\r\n self.on = qubit\r\n\r\nclass Z(object):\r\n def __init__(self, qubit=None) -> None:\r\n super().__init__()\r\n self.op = np.array([\r\n [1, 0],\r\n [0, -1]\r\n ])\r\n self.on = qubit\r\n\r\nclass H(object):\r\n def __init__(self, qubit=None) -> None:\r\n super().__init__()\r\n self.op = 1/math.sqrt(2) * np.array([\r\n [1, 1],\r\n [1, -1]\r\n ])\r\n self.on = qubit\r\n\r\nclass I(object):\r\n def __init__(self, qubit=None) -> None:\r\n super().__init__()\r\n self.op = np.array([\r\n [1, 0],\r\n [0, 1]\r\n ])\r\n self.on = qubit\r\n\r\nclass S(object):\r\n def __init__(self, qubit=None) -> None:\r\n super().__init__()\r\n self.op = np.array([\r\n [1, 0],\r\n [0, 1j]\r\n ])\r\n self.on = qubit\r\n\r\nclass U(object):\r\n def __init__(self, theta, phi, lamb, qubit=None) -> None:\r\n super().__init__()\r\n self.op = np.array([\r\n [math.cos(theta/2), -np.exp(1j * lamb) * math.sin(theta/2)],\r\n [np.exp(1j * phi) * math.sin(theta/2), np.exp(1j * (lamb + phi)) * math.cos(theta/2)]\r\n ])\r\n self.on = qubit\r\n\r\nclass Controlled(object):\r\n def __init__(self, op, qubits=None) -> None:\r\n super().__init__()\r\n self.on = qubits\r\n self.op = op.op\r\n self.two_qubit = True\r\n\r\nclass Rx(object):\r\n def __init__(self, param=0, qubit=None) -> None:\r\n super().__init__()\r\n self.param = param \r\n self.op = np.array([\r\n [math.cos(self.param/2), -1j * math.sin(self.param/2)],\r\n [-1j * math.sin(param/2), math.cos(param/2)]\r\n ])\r\n self.on = qubit\r\n\r\nclass Ry(object):\r\n def __init__(self, param=0, qubit=None) -> None:\r\n super().__init__()\r\n self.param = param \r\n self.op = np.array([\r\n [math.cos(self.param/2), -1 * math.sin(self.param/2)],\r\n [math.sin(param/2), math.cos(param/2)]\r\n ])\r\n self.on = qubit\r\n\r\nclass Rz(object):\r\n def __init__(self, param=0, qubit=None) -> None:\r\n super().__init__()\r\n self.param = param \r\n self.op = np.array([\r\n [np.exp(-1j * self.param/2), 0], \r\n [0, np.exp(1j * self.param/2)]\r\n ])\r\n self.on = qubit" ]
[ [ "numpy.exp", "numpy.array" ] ]
ryankirkland/voice-of-the-customer
[ "0214af45cc6aa76bfce64065f07c3f4781ee045e" ]
[ "dashboard/app/reviewmodel.py" ]
[ "from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.decomposition import LatentDirichletAllocation\n\n\nclass ReviewLDA():\n\n def __init__(self, n_components=5, learning_decay=0.7):\n self.lda = LatentDirichletAllocation(n_components=n_components, learning_decay=learning_decay)\n\n def fit(self, X, validate=False, n_components=[3, 5, 10], learning_decay=[0.5, 0.7, 0.9]):\n \"\"\"\n Fit list of tokens to TF-IDF vectorizer model to then fit LDA\n model. If 'validate' is set to true, fits GridSearchCV to find\n optimal LDA model.\n\n INPUT: X: A list of preprocessed tokens derived form the corpus.\n\n OUTPUT: LDA model\n \"\"\"\n # Fit to TF-IDF\n self.tfidf = TfidfVectorizer()\n self.dtm = self.tfidf.fit_transform(X)\n\n # Begin validation\n if validate:\n search_params = {\n 'n_components': n_components,\n 'learning_decay': learning_decay\n }\n self.model = GridSearchCV(self.lda, search_params)\n self.model.fit(self.dtm)\n self.best_lda = self.model.best_estimator_\n self.cv_results = self.model.cv_results_\n self.best_params = self.model.best_params_\n self.best_score = self.model.best_score_\n\n # End validation\n else:\n self.best_lda = self.lda.fit(self.dtm)\n \n self.perplexity = self.best_lda.perplexity(self.dtm)\n self.log_likelihood = self.best_lda.score(self.dtm)\n self.components_ = self.best_lda.components_\n\n return self.best_lda\n\n def transform(self, review):\n \"\"\"\n Convert reviews to list where values correspond to the probability\n the review belongs to each of n topics.\n\n INPUT: review: A tfidf vectorized review.\n\n OUTPUT: Probability review belongs to each of n topics\n \"\"\"\n return self.best_lda.transform(review)" ]
[ [ "sklearn.decomposition.LatentDirichletAllocation", "sklearn.model_selection.GridSearchCV", "sklearn.feature_extraction.text.TfidfVectorizer" ] ]
hjwdzh/FrameNet
[ "fe5cc45148f210ad9a2520a576ad92f5f282ca71" ]
[ "src/demo/AttachTexture.py" ]
[ "import cv2\nimport skimage.io as sio\nimport sys\nimport numpy as np\nfrom visualizer import app\nfrom direction import *\nimport scipy.misc as misc\nimport argparse\n\nparser = argparse.ArgumentParser(description='Process saome integers.')\nparser.add_argument('--input', type=str, default='selected/0000')\nparser.add_argument('--resource', type=str, default='resources/im4.png')\nargs = parser.parse_args()\n# set up file names\nstart_name = args.input\ncolor_name = start_name + '-color.png'\norient_x_name = start_name + '-orient-X_pred.png'\norient_y_name = start_name + '-orient-Y_pred.png'\n\nintrinsics = np.array([577.591,318.905,578.73,242.684]).astype('float32')\n\nif args.resource[-3:] == 'obj':\n\tmesh_info = ProcessOBJ(args.resource,args.resource[:-3] + 'jpg')\nelse:\n\tmesh_info = ProcessOBJ('resources/objects/toymonkey/toymonkey.obj','resources/objects/toymonkey/toymonkey.jpg')\n\ncolor_image = cv2.imread(color_name)\ndirX_3d = Color2Vec(misc.imresize(sio.imread(orient_x_name), (480,640), 'nearest'))\ndirY_3d = Color2Vec(misc.imresize(sio.imread(orient_y_name), (480,640), 'nearest'))\n\nif args.resource[-3:] != 'obj':\n\tresource_image = cv2.imread(args.resource)\nelse:\n\tresource_image = cv2.imread('resources/im4.png')\n\nif (resource_image.shape[2] == 4):\n\tmask = resource_image[:,:,3] > 0\n\tresource_image[:,:,0] *= mask\n\tresource_image[:,:,1] *= mask\n\tresource_image[:,:,2] *= mask\n\tresource_image = resource_image[:,:,0:3]\nmin_v = np.min([resource_image.shape[0], resource_image.shape[1]])\nstart_x = (resource_image.shape[1] - min_v)//2\nstart_y = (resource_image.shape[0] - min_v)//2\nattached_patch = np.ascontiguousarray(resource_image[start_y:start_y+min_v, start_x:start_x+min_v,:])\nattached_patch = misc.imresize(attached_patch, (401,401),'nearest')\n\napp(color_image, dirX_3d, dirY_3d, attached_patch, intrinsics, mesh_info)" ]
[ [ "numpy.ascontiguousarray", "scipy.misc.imresize", "numpy.array", "numpy.min" ] ]
timothymillar/cyvcf2
[ "acde4eab6e441f01f25cca48afc921343a810fa3" ]
[ "cyvcf2/tests/test_reader.py" ]
[ "from __future__ import print_function\nfrom ..cyvcf2 import VCF, Variant, Writer\nimport numpy as np\nimport os.path\nfrom nose.tools import assert_raises\nimport tempfile\nimport sys\nimport os\nimport atexit\ntry:\n from pathlib import Path\nexcept ImportError:\n from pathlib2 import Path # python 2 backport\n\n\nHERE = os.path.dirname(__file__)\nVCF_PATH = os.path.join(HERE, \"test.vcf.gz\")\nVCF_PATH2 = os.path.join(HERE, \"test.snpeff.vcf\")\nVCF_PHASE_PATH = os.path.join(HERE, \"test.comp_het.3.vcf\")\nVCF_ALTFREQ_PATH = os.path.join(HERE, \"test_gt_alt_freqs.vcf\")\n\ntry:\n basestring\nexcept NameError:\n basestring = (str, bytes)\n\ndef test_init():\n # string\n v = VCF(VCF_PATH)\n assert v\n expected_count = sum(1 for _ in v)\n v.close()\n\n # Path\n v = VCF(Path(VCF_PATH))\n value = sum(1 for _ in v)\n assert value == expected_count\n\n # file descriptor\n with open(VCF_PATH) as fp:\n fd = fp.fileno()\n v = VCF(fd)\n assert sum(1 for _ in v) == expected_count\n v.close() # this should not close the file descriptor originally opened\n\n # file-like object\n with open(VCF_PATH) as fp:\n v = VCF(fp)\n assert sum(1 for _ in v) == expected_count\n v.close() # this should not close the file descriptor originally opened\n\ndef test_type():\n vcf = VCF(VCF_PATH)\n for v in vcf:\n if len(v.REF) == 1 and len(v.ALT[0]) == 1:\n assert v.var_type == 'snp'\n elif v.ALT[0][0] != \"<\":\n assert v.var_type == 'indel'\n else:\n print(v.var_type, v.REF, v.ALT)\n\ndef test_format_str():\n vcf = VCF(os.path.join(HERE, \"test-format-string.vcf\"))\n\n f = next(vcf).format(\"RULE\")\n assert list(f) == ['F', 'G']\n f = next(vcf).format(\"RULE\")\n assert list(f) == ['F2,F3,F4', 'G2,G3,G4']\n\ndef test_missing_samples():\n samples = ['101976-101976', 'sample_not_in_vcf']\n vcf = VCF(VCF_PATH, gts012=True, samples=samples)\n assert len(vcf.samples) == 1\n vcf.close()\n samples = '101976-101976,sample_not_in_vcf'\n vcf = VCF(VCF_PATH, gts012=True, samples=samples)\n assert len(vcf.samples) == 1\n\ndef test_ibd():\n samples = ['101976-101976', '100920-100920', '100231-100231']\n vcf = VCF(VCF_PATH, gts012=True, samples=samples)\n res = vcf.ibd()\n assert len(res) == 3, (len(res))\n arr = res[('101976-101976', '100920-100920')]\n assert len(arr) > 0\n\ndef test_relatedness():\n vcf = VCF(VCF_PATH, gts012=True)\n df = vcf.relatedness(gap=0, linkage_max=2)\n assert \"ibs0\" in df, df\n assert \"rel\" in df\n #vcf = VCF(VCF_PATH, gts012=True)\n #for r in viter:\n # print r['pair'], r['ibs0'], r['ibs2'], r['ibs2*']\n\ndef test_pls():\n vcf = VCF(VCF_PATH)\n v = next(vcf)\n\n assert v.gt_phred_ll_homref[0] == 0, v.gt_phred_ll_homref[0]\n assert v.gt_phred_ll_het[0] == 7, v.gt_phred_ll_het[0]\n assert v.gt_phred_ll_homalt[0] == 922, v.gt_phred_ll_homalt[0]\n\n import numpy as np\n imax = np.iinfo(np.int32(0)).max\n # missing\n assert v.gt_phred_ll_homref[1] == imax, v.gt_phred_ll_homref[1]\n assert v.gt_phred_ll_het[1] == imax, v.gt_phred_ll_het[1]\n assert v.gt_phred_ll_homalt[1] == imax, v.gt_phred_ll_homalt[1]\n\ndef test_gt_alt_freqs():\n vcf = VCF(VCF_ALTFREQ_PATH)\n\n v = next(vcf)\n assert v.gt_alt_freqs[0] == 0.2\n assert v.gt_alt_freqs[1] == 1.0\n\n v = next(vcf)\n assert v.gt_alt_freqs[0] == 0.5\n assert v.gt_alt_freqs[1] == 0.9\n\n v = next(vcf)\n assert v.gt_alt_freqs[0] == 0.0\n assert v.gt_alt_freqs[1] == 0.0\n\n v = next(vcf)\n assert v.gt_alt_freqs[0] == 0.0\n assert v.gt_alt_freqs[1] == 1.0\n\n v = next(vcf)\n assert v.gt_alt_freqs[0] == 0.0\n assert v.gt_alt_freqs[1] == 0.0\n\n v = next(vcf)\n assert v.gt_alt_freqs[0] == -1\n assert v.gt_alt_freqs[1] == -1\n\ndef test_str():\n vcf = VCF(VCF_PATH, lazy=True)\n v = next(vcf)\n s = str(v)\n\n assert \"10172\\t.\\tCCCTAA\\t\" in s\n assert \"fitcons_float=0.1266\" in s\n\n\ndef test_region():\n vcf = VCF(VCF_PATH)\n\n start = 12783\n end = 13783\n k = 0\n reg = '1:%d-%d' % (start, end)\n for var in vcf(reg):\n k += 1\n assert var.start <= end, var\n assert var.end >= start, var\n assert isinstance(var.REF, basestring)\n assert isinstance(var.ALT, list)\n assert k == 28, k\n\ndef test_empty_info():\n for v in VCF(VCF_PHASE_PATH):\n dict(v.INFO)\n\ndef test_phases():\n vcf = VCF(VCF_PHASE_PATH)\n\n v = next(vcf)\n assert all(v.gt_phases), v.gt_phases\n\n v = next(vcf)\n assert all(v.gt_phases)\n\n v = next(vcf)\n assert all(v.gt_phases[1::2])\n assert not any(v.gt_phases[0::2])\n\n v = next(vcf)\n assert not any(v.gt_phases[:-1])\n assert v.gt_phases[-1]\n\n v = next(vcf)\n assert not any(v.gt_phases)\n\ndef test_bad_init():\n assert_raises(Exception, VCF, \"XXXXX\")\n\ndef test_samples():\n v = VCF(VCF_PATH)\n assert len(v.samples) == 189\n\ndef test_next():\n v = VCF(VCF_PATH)\n variant = next(v)\n assert isinstance(variant, Variant)\n\ndef test_variant():\n assert_raises(TypeError, Variant)\n\ndef test_info_dict():\n v = VCF(VCF_PATH)\n variant = next(v)\n d = dict(variant.INFO)\n assert d != {}, d\n toks = _get_line_for(variant)\n\n info = toks[7].split(\";\")\n keys = [x.split('=')[0] for x in info]\n for k in keys:\n assert k in d, (k, info)\n\n\ndef test_attrs():\n # 1 10172 . CCCTAA C 92.0 PASS\n v = VCF(VCF_PATH)\n variant = next(v)\n assert variant.POS == 10172\n assert variant.CHROM == \"1\"\n assert variant.ID is None, variant.ID\n assert variant.start == 10171\n assert variant.end == 10177, variant.end\n assert variant.FILTER is None\n assert variant.QUAL == 92.0\n\n assert variant.REF == \"CCCTAA\"\n assert variant.ALT == [\"C\"]\n\ndef test_empty():\n p = os.path.join(HERE, \"empty.vcf\")\n assert os.path.exists(p)\n assert_raises(IOError, VCF, p)\n\ndef test_format_field():\n vcf = VCF(VCF_PATH)\n for v in vcf:\n assert isinstance(v.FORMAT, list)\n\ndef test_writer_from_string():\n\n header = \"\"\"##fileformat=VCFv4.1\n##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">\n##contig=<ID=chr2,length=249250621,assembly=hg19>\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsamplea\n\"\"\"\n\n w = Writer.from_string(\"out.vcf\", header)\n w.write_header()\n v = w.variant_from_string(\"chr1\\t234\\t.\\tA\\tC\\t40\\tPASS\\t.\\tGT\\t0/0\")\n w.write_record(v)\n w.close()\n\n\ndef run_writer(writer, filename, rec):\n rec.INFO[\"AC\"] = \"3\"\n rec.FILTER = [\"LowQual\"]\n writer.write_record(rec)\n\n rec.FILTER = [\"LowQual\", \"VQSRTrancheSNP99.90to100.00\"]\n writer.write_record(rec)\n\n rec.FILTER = \"PASS\"\n writer.write_record(rec)\n\n writer.close()\n\n expected = [\"LowQual\", \"LowQual;VQSRTrancheSNP99.90to100.00\", None]\n\n for i, variant in enumerate(VCF(filename)):\n assert variant.FILTER == expected[i], (variant.FILTER, expected[i])\n\ndef test_writer():\n v = VCF(VCF_PATH)\n f = tempfile.mktemp(suffix=\".vcf\")\n atexit.register(os.unlink, f)\n rec = next(v)\n\n # string\n run_writer(Writer(f, v), f, rec)\n\n # Path\n path = Path(f)\n run_writer(Writer(path, v), f, rec)\n\n # file descriptor\n with open(VCF_PATH) as fp:\n fd = fp.fileno()\n run_writer(Writer(fd, v), f, rec)\n\n # file-like object\n with open(VCF_PATH) as fp:\n run_writer(Writer(fp, v), f, rec)\n\ndef test_add_info_to_header():\n v = VCF(VCF_PATH)\n v.add_info_to_header({'ID': 'abcdefg', 'Description': 'abcdefg',\n 'Type':'Character', 'Number': '1'})\n # NOTE that we have to add the info to the header of the reader,\n # not the writer because the record will be associated with the reader\n f = tempfile.mktemp(suffix=\".vcf\")\n atexit.register(os.unlink, f)\n w = Writer(f, v)\n import sys\n rec = next(v)\n\n rec.INFO[\"abcdefg\"] = \"XXX\"\n w.write_record(rec)\n w.close()\n\n v = next(VCF(f))\n ret = v.INFO[\"abcdefg\"]\n if isinstance(ret, bytes):\n ret = ret.decode()\n assert ret == \"XXX\", (dict(v.INFO), v.INFO[\"abcdefg\"])\n\ndef test_read_flag():\n vcf = VCF(VCF_PATH)\n for v in vcf:\n assert (\"in_exac_flag\" in str(v)) == v.INFO.get('in_exac_flag', False)\n\ndef test_add_flag():\n vcf = VCF(VCF_PATH)\n vcf.add_info_to_header({'ID': 'myflag', 'Description': 'myflag',\n 'Type':'Flag', 'Number': '0'})\n # NOTE that we have to add the info to the header of the reader,\n # not the writer because the record will be associated with the reader\n f = tempfile.mktemp(suffix=\".vcf\")\n atexit.register(os.unlink, f)\n w = Writer(f, vcf)\n rec = next(vcf)\n\n rec.INFO[\"myflag\"] = True\n w.write_record(rec)\n w.close()\n\n v = next(VCF(f))\n assert v.INFO[\"myflag\"] is True, dict(v.INFO)\n\n f = tempfile.mktemp(suffix=\".vcf\")\n atexit.register(os.unlink, f)\n w = Writer(f, vcf)\n rec.INFO[\"myflag\"] = False\n w.write_record(rec)\n v = next(VCF(f))\n assert_raises(KeyError, v.INFO.__getitem__, \"myflag\")\n\n\ndef test_constants():\n v = VCF(VCF_PATH)\n assert v.HOM_REF == 0\n assert v.HET == 1\n assert v.UNKNOWN == 2\n assert v.HOM_ALT == 3\n\n v = VCF(VCF_PATH, gts012=True)\n assert v.HOM_REF == 0\n assert v.HET == 1\n assert v.HOM_ALT == 2\n assert v.UNKNOWN == 3\n\n\ndef test_add_filter_to_header():\n v = VCF(VCF_PATH)\n # NOTE that we have to add the filter to the header of the reader,\n # not the writer because the record will be associated with the reader\n v.add_filter_to_header({'ID': 'abcdefg', 'Description': 'abcdefg'})\n\n f = tempfile.mktemp(suffix=\".vcf\")\n atexit.register(os.unlink, f)\n w = Writer(f, v)\n rec = next(v)\n\n rec.FILTER = [\"abcdefg\"]\n w.write_record(rec)\n w.close()\n\n v = next(VCF(f))\n ret = v.FILTER\n if isinstance(ret, bytes):\n ret = ret.decode()\n\n assert ret == \"abcdefg\", v.FILTER\n\ndef test_seqnames():\n v = VCF(VCF_PATH)\n assert v.seqnames == [u'1', u'2', u'3', u'4', u'5', u'6', u'7', u'8', u'9', u'10', u'11', u'12', u'13', u'14', u'15', u'16', u'17', u'18', u'19', u'20', u'21', u'22', u'X', u'Y', u'MT', u'GL000207.1', u'GL000226.1', u'GL000229.1', u'GL000231.1', u'GL000210.1', u'GL000239.1', u'GL000235.1', u'GL000201.1', u'GL000247.1', u'GL000245.1', u'GL000197.1', u'GL000203.1', u'GL000246.1', u'GL000249.1', u'GL000196.1', u'GL000248.1', u'GL000244.1', u'GL000238.1', u'GL000202.1', u'GL000234.1', u'GL000232.1', u'GL000206.1', u'GL000240.1', u'GL000236.1', u'GL000241.1', u'GL000243.1', u'GL000242.1', u'GL000230.1', u'GL000237.1', u'GL000233.1', u'GL000204.1', u'GL000198.1', u'GL000208.1', u'GL000191.1', u'GL000227.1', u'GL000228.1', u'GL000214.1', u'GL000221.1', u'GL000209.1', u'GL000218.1', u'GL000220.1', u'GL000213.1', u'GL000211.1', u'GL000199.1', u'GL000217.1', u'GL000216.1', u'GL000215.1', u'GL000205.1', u'GL000219.1', u'GL000224.1', u'GL000223.1', u'GL000195.1', u'GL000212.1', u'GL000222.1', u'GL000200.1', u'GL000193.1', u'GL000194.1', u'GL000225.1', u'GL000192.1', u'NC_007605', u'hs37d5', u'phix'], v.seqnames\n\n b = VCF('{}/test.snpeff.bcf'.format(HERE), threads=3)\n assert b.seqnames[0] == 'chr1', b.seqnames\n assert b.seqnames[-1] == 'chrY', b.seqnames\n\ndef test_different_index():\n b = VCF('{}/test.snpeff.bcf'.format(HERE), threads=3)\n b.set_index(\"cyvcf2/tests/test-diff.csi\")\n s = 0\n for r in b(\"chr1:69427-69429\"):\n s += 1\n assert s == 1\n\ndef test_var_type():\n v = VCF(VCF_PATH)\n variant = next(v)\n assert variant.var_type == \"indel\", variant.var_type\n # 1 10172 . CCCTAA C 92.0 PASS\n for variant in v:\n if variant.POS == 10478: break\n else:\n raise Exception\n assert variant.var_type == \"snp\", variant.var_type\n\ndef _get_line_for(v):\n import gzip\n\n for i, line in enumerate(gzip.open(VCF_PATH), start=1):\n line = line.decode()\n if line[0] == \"#\": continue\n toks = line.strip().split(\"\\t\")\n if not (toks[0] == v.CHROM and int(toks[1]) == v.POS): continue\n if toks[3] != v.REF: continue\n if toks[4] not in v.ALT: continue\n return toks\n else:\n raise Exception(\"not found\")\n\n\ndef _get_samples(v):\n import numpy as np\n\n def _get_gt(s):\n if not \":\" in s:\n return 2\n s = s.split(\":\", 1)[0]\n if s in (\"0/0\", \"0|0\", \"0/.\", \"./0\", \"0|.\"):\n return 0\n if s in (\"0/1\", \"0|1\", \"1/.\", \"./1\", \"1/.\"):\n return 1\n if s in (\"1/1\", \"1|1\"):\n return 3\n return 2\n toks = _get_line_for(v)\n samples = toks[9:]\n return np.array([_get_gt(s) for s in samples], np.int)\n\ndef test_header_info():\n v = VCF(VCF_PATH)\n csq = v['CSQ']\n assert csq['ID'] == \"CSQ\"\n assert \"Description\" in csq\n\n\n assert_raises(KeyError, v.__getitem__, b'XXXXX')\n\ndef test_snpeff_header():\n v = VCF(VCF_PATH2)\n\n f = v['SnpEffVersion']\n assert f != {}, f\n assert 'SnpEffVersion' in f\n\n#def test_info_update():\n# vcf = VCF(VCF_PATH)\n# v = next(vcf)\n# ret = v.INFO.update({'k': 22})\n #print ret\n #assert v.INFO['k'] == 22\n #assert ret == 0, ret\n\ndef test_gt_types():\n v = VCF(VCF_PATH)\n for variant in v:\n\n gt_types = variant.gt_types\n o = _get_samples(variant)\n assert (gt_types == o).all(), (variant, variant.CHROM, variant.POS, zip(gt_types, o))\n\ndef test_raw_header():\n v = VCF(VCF_PATH)\n h = v.raw_header.strip().split(\"\\n\")\n s = h[0]\n assert s == \"##fileformat=VCFv4.1\", s\n assert len(h) == 185, len(h)\n\n\n\ndef test_iterate():\n\n for i, v in enumerate(VCF(VCF_PATH), start=1):\n pass\n assert i == 115, i\n\n\ndef test_empty_call():\n\n for i, v in enumerate(VCF(VCF_PATH)(), start=1):\n pass\n assert i == 115, i\n del i\n\n for i, v in enumerate(VCF(VCF_PATH)(''), start=1):\n pass\n assert i == 115, i\n\n\n\ndef test_haploid():\n\n for (gts012, (HOM_REF, HOM_ALT, UNKNOWN)) in ((False, [0, 3, 2]), (True, [0, 2, 3])):\n vcf = VCF(\"%s/test-haploidX.vcf\" % HERE, gts012=gts012)\n for i, v in enumerate(vcf):\n assert not any(\"/\" in b for b in v.gt_bases), (v.start + 1, v.gt_bases)\n if i == 0:\n assert (v.gt_types == [HOM_ALT, HOM_ALT, HOM_ALT]).all(), v.gt_types\n elif v.start == 2800676:\n assert (v.gt_types == [UNKNOWN, HOM_ALT, UNKNOWN]).all(), v.gt_types\n elif v.start == 2832771:\n assert (v.gt_types == [HOM_REF, HOM_ALT, HOM_ALT]).all(), v.gt_types\n break\n\n if v.start == 2700156:\n assert (v.gt_bases == ['A', 'A', 'A']).all(), v.gt_bases\n break\n\n\ndef test_diploid():\n vcf = VCF(\"%s/test.comp_het.3.vcf\" % HERE)\n for v in vcf:\n if v.start == 17362:\n assert (v.gt_bases == ['TTCT|TTCT', 'TTCT|TTCT', 'TTCT|TTCT',\n 'TTCT|TTCT', 'TTCT|TTCT', 'TTCT|TTCT', 'TTCT|T', 'TTCT|T',\n 'TTCT|TTCT', 'TTCT|T', 'TTCT|T',\n 'TTCT|TTCT']).all(), v.gt_bases\n\n\ndef test_format():\n\n vcf = VCF('{}/test.vcf.gz'.format(HERE))\n for v in vcf:\n a = v.format('PL', int)\n assert a.shape == (189, 3)\n\n a = v.format('SB', int)\n assert a is None\n\n a = v.format('DP', int)\n assert a.shape == (189, 1)\n\ndef test_header_stuff():\n vcf = VCF('{}/test.vcf.gz'.format(HERE))\n import sys\n seen_formats, seen_infos = 0, 0\n for h in vcf.header_iter():\n i = h.info(extra=True)\n assert isinstance(i, dict)\n seen_formats += i['HeaderType'] == 'FORMAT'\n seen_infos += i['HeaderType'] == 'INFO'\n assert seen_formats == 9, seen_formats\n assert seen_infos == 73, seen_infos\n\n\ndef test_bcf():\n vcf = VCF('{}/test.snpeff.bcf'.format(HERE))\n l = sum(1 for _ in vcf)\n assert l == 10, l\n\n # NOTE: this is 0 becuase we don't SEEK.\n l = sum(1 for _ in vcf())\n assert l == 0, l\n\n\n viter = vcf(\"1:69260-69438\")\n sys.stderr.write(\"\\nOK\\n\")\n sys.stderr.flush()\n l = list(viter)\n assert len(l) == 0, len(l)\n\n iter = vcf(\"chr1:69260-69438\")\n l = list(iter)\n assert len(l) == 2, len(l)\n\n\ndef test_issue12():\n fields = \"ADP_ALL ADPD ADPO ADP_PASS ADPR AFR AMBIG BMF_PASS BMF_QUANT AF_FAILED FA_FAILED FM_FAILED FP_FAILED FR_FAILED MD_FAILED IMPROPER MQ_FAILED OVERLAP PV_FAILED QSS\".split()\n\n vcf = VCF('{}/bug.vcf.gz'.format(HERE))\n for v in vcf:\n for f in fields:\n vals = v.format(f)\n if vals is not None:\n assert vals.dtype in (np.int32, np.float32), (f, vals.dtype)\n\n vals = v.format(\"RVF\")\n assert vals.dtype in (np.float32, np.float64)\n\n assert_raises(KeyError, v.format, \"RULE\")\n\ndef test_gt_bases_nondiploid():\n \"\"\"Ensure gt_bases works with more complex base representations.\n \"\"\"\n vcf = VCF('{}/test_gt_bases.vcf.gz'.format(HERE))\n expected = {0: ['C/C', 'C/C'], 1: ['C/T', 'C'], 2: ['C', 'C/T'], 3: ['C', 'C']}\n for i, v in enumerate(vcf):\n assert v.gt_bases.tolist() == expected[i], (v.gt_bases.tolist(), expected[i])\n\ndef fmap(fn, a):\n return list(map(fn, a))\n\ndef allclose(a, b):\n return np.allclose(np.array(a, dtype=float), np.array(b, dtype=float))\n\ndef test_set_format_float():\n vcf = VCF('{}/test-format-string.vcf'.format(HERE))\n assert vcf.add_format_to_header(dict(ID=\"PS\", Number=1, Type=\"Float\", Description=\"PS example\")) == 0\n v = next(vcf)\n v.set_format(\"PS\", np.array([0.555, 1.111], dtype=np.float32))\n assert allclose(fmap(float, get_gt_str(v, \"PS\")), np.array([0.555, 1.111]))\n\n v.set_format(\"PS\", np.array([8.555, 11.111], dtype=np.float64))\n assert allclose(fmap(float, get_gt_str(v, \"PS\")), [8.555, 11.111])\n\n v.set_format(\"PS\", np.array([9998.555, 99911.111], dtype=np.float32))\n obs = fmap(float, get_gt_str(v, \"PS\"))\n assert allclose(obs, [9998.555, 99911.111]), obs\n\ndef test_set_format_int_a():\n vcf = VCF('{}/test-format-string.vcf'.format(HERE))\n assert vcf.add_format_to_header(dict(ID=\"PI\", Number=1, Type=\"Integer\", Description=\"Int example\")) == 0\n v = next(vcf)\n v.set_format(\"PI\", np.array([5, 1], dtype=np.int))\n assert allclose(fmap(float, get_gt_str(v, \"PI\")), [5, 1])\n\ndef test_set_format_int_b():\n vcf = VCF('{}/test-format-string.vcf'.format(HERE))\n assert vcf.add_format_to_header(dict(ID=\"PI\", Number=1, Type=\"Integer\", Description=\"Int example\")) == 0\n v = next(vcf)\n\n v.set_format(\"PI\", np.array([855, 11], dtype=np.int64))\n assert allclose(fmap(float, get_gt_str(v, \"PI\")), [855, 11])\n\ndef test_set_format_int_c():\n vcf = VCF('{}/test-format-string.vcf'.format(HERE))\n assert vcf.add_format_to_header(dict(ID=\"PI\", Number=1, Type=\"Integer\", Description=\"Int example\")) == 0\n v = next(vcf)\n\n v.set_format(\"PI\", np.array([9998, 99911], dtype=np.int32))\n obs = fmap(float, get_gt_str(v, \"PI\"))\n assert allclose(obs, [9998, 99911]), obs\n\ndef test_set_format_int3():\n \"test that we can handle multiple (in this case 3) values per sample\"\n vcf = VCF('{}/test-format-string.vcf'.format(HERE))\n assert vcf.add_format_to_header(dict(ID=\"P3\", Number=3, Type=\"Integer\", Description=\"Int example\")) == 0\n v = next(vcf)\n exp = np.array([[1, 11, 111], [2, 22, 222]], dtype=np.int)\n v.set_format(\"P3\", exp)\n res = get_gt_str(v, \"P3\")\n assert res == [\"1,11,111\", \"2,22,222\"], (res, str(v))\n\n assert np.allclose(v.format(\"P3\"), exp)\n\ndef test_set_format_str_bytes_second_longer():\n vcf = VCF('{}/test-format-string.vcf'.format(HERE))\n assert vcf.add_format_to_header(dict(ID=\"STR\", Number=1, Type=\"String\", Description=\"String example\")) == 0\n v = next(vcf)\n\n v.set_format(\"STR\", np.array([b'foo', b'barbaz']))\n assert np.all(v.format('STR') == np.array(['foo', 'barbaz']))\n\ndef test_set_format_str_bytes_first_longer():\n vcf = VCF('{}/test-format-string.vcf'.format(HERE))\n assert vcf.add_format_to_header(dict(ID=\"STR\", Number=1, Type=\"String\", Description=\"String example\")) == 0\n v = next(vcf)\n\n v.set_format(\"STR\", np.array([b'foobar', b'baz']))\n assert np.all(v.format('STR') == np.array(['foobar', 'baz']))\n\ndef test_set_format_str_bytes_number3():\n # Confirm currently not supported\n vcf = VCF('{}/test-format-string.vcf'.format(HERE))\n assert vcf.add_format_to_header(dict(ID=\"STR\", Number=3, Type=\"String\", Description=\"String example\")) == 0\n v = next(vcf)\n\n contents = np.array([[b'foo', b'barbaz', b'biz'], [b'blub', b'bloop', b'blop']])\n assert_raises(Exception, v.set_format, \"STR\", contents)\n\ndef test_set_gts():\n vcf = VCF('{}/test-format-string.vcf'.format(HERE))\n v = next(vcf)\n\n v.genotypes = [[1, 1, True], [0, 0, False]]\n assert get_gt_str(v) == [\"1|1\", \"0/0\"]\n\n v.genotypes = [[-1, 1, False], [-1, 0, False]]\n assert get_gt_str(v) == [\"./1\", \"./0\"]\n\n v.genotypes = [[-1, -1, False], [0, 0, True]]\n assert get_gt_str(v) == [\"./.\", \"0|0\"]\n\n v.genotypes = [[2, 2, True], [0, 2, True]]\n assert get_gt_str(v) == [\"2|2\", \"0|2\"]\n\n v.genotypes = [[0, 1, 2, False], [1, 2, True]]\n s = get_gt_str(v)\n assert s == [\"0/1/2\", \"1|2\"]\n\n v.genotypes = [[1, 2, False], [0, 1, 2, True]]\n assert get_gt_str(v) == [\"1/2\", \"0|1|2\"]\n\n v.genotypes = [[0, 1, 2, False], [0, 1, 2, True]]\n assert get_gt_str(v) == [\"0/1/2\", \"0|1|2\"]\n\ndef test_info_del():\n vcf = VCF(os.path.join(HERE, \"test-hemi.vcf\"))\n v = next(vcf)\n d = str(v)\n assert \";DP=\" in d\n del v.INFO[\"DP\"]\n d = str(v)\n assert not \";DP=\" in d\n\ndef test_filter_id():\n vcf = VCF(os.path.join(HERE, \"test-hemi.vcf\"))\n v = next(vcf)\n assert v.ID == \"ID1\"\n assert v.FILTER == \"FAIL\"\n\n\ndef get_gt_str(variant, key=\"GT\"):\n idx = variant.FORMAT.index(key)\n return [x.split(\":\")[idx] for x in str(variant).strip().split(\"\\t\")[9:]]\n\ndef test_access_gts():\n vcf = VCF('{}/test-format-string.vcf'.format(HERE))\n \"\"\"\n7\t55086956\t.\tC\tG\t0\t.\t.\tGT:ADP_ALL:RULE\t0/0:6728,1:F\t1|1:22,1:G\n7\t55086957\t.\tT\tA,C,G\t0\t.\t.\tGT:ADP_ALL:RULE\t1/2:6768,2,2,1:F2,F3,F4\t2|3:1,2,3,4:G2,G3,G4\n7\t55086958\t.\tT\tG\t0\t.\t.\tGT:ADP_ALL:RULE\t0/1/.:6768,2,2,1:F2,F3,F4\t0:1,2,3,4:G2,G3,G4\n7\t55086959\t.\tT\tG,T\t0\t.\t.\tGT:ADP_ALL:RULE\t.\t0|2:1,2,3,4:G2,G3,G4\n \"\"\"\n\n v = next(vcf)\n gts = v.genotypes\n assert gts == [[0, 0, False], [1, 1, True]], gts\n\n v = next(vcf)\n assert v.genotypes == [[1, 2, False], [2, 3, True]], v.genotypes\n\n v = next(vcf)\n assert v.genotypes == [[0, 1, -1, False], [0, True]], v.genotypes\n\n v = next(vcf)\n assert v.genotypes == [[-1, True], [0, 2, True]], v.genotypes\n\ndef test_access_genotype():\n vcf = VCF('{}/test-format-string.vcf'.format(HERE))\n v = next(vcf)\n gts = v.genotype\n #print(str(v), file=sys.stderr)\n\n # indexing directly gives a list of Allele objects (for diploid, the list\n # has length 2)\n alleles = gts[0]\n assert alleles[0].value == 0\n assert alleles[1].value == 0\n assert alleles[0].phased == False\n\n alleles = gts[1]\n assert alleles[0].value == 1\n assert alleles[1].value == 1\n assert alleles[1].phased == True\n\n assert np.all(gts.array()[:, :2] == np.array([[0, 0], [1, 1]]))\n assert np.all(gts.array()[:, 2] == np.array([False, True]))\n\n assert alleles[1].phased == True\n alleles[1].phased = False\n assert alleles[1].phased == False\n alleles = gts[1]\n assert alleles[1].phased == False\n\n assert np.all(gts.array()[:, 2] == np.array([False, False]))\n\n # can also just get the phased stats of the nth sample:\n assert gts.phased(0) == False\n # note this got updated above\n assert gts.phased(1) == False\n\n # and the alleles of the nth sample.\n assert gts.alleles(0) == [0, 0]\n #print(gts.alleles(1), file=sys.stderr)\n assert gts.alleles(1) == [1, 1]\n\n\n alleles = gts[0]\n assert alleles[0].value == 0\n alleles[0].value = 1\n assert alleles[0].value == 1\n alleles = gts[0]\n assert alleles[0].value == 1\n assert alleles[0].phased == False\n\n assert np.all(gts.array()[:, :2] == np.array([[1, 0], [1, 1]]))\n\n gts[1][0].value = 0\n\n assert np.all(gts.array()[:, :2] == np.array([[1, 0], [0, 1]]))\n\n # update the varint\n v.genotype = gts\n assert \"1/0:6728,1:F\t0/1:22,1:G\" in str(v)\n\n\ndef test_alt_homozygous_gt():\n vcf = VCF(os.path.join(HERE, \"test-multiallelic-homozygous-alt.vcf.gz\"))\n assert vcf is not None\n v = next(vcf)\n assert v\n assert v.gt_bases[0] == '<*:DEL>/<*:DEL>'\n\n vcf = VCF(os.path.join(HERE, \"test-multiallelic-homozygous-alt.vcf.gz\"), gts012=True)\n assert vcf is not None\n v = next(vcf)\n assert v\n assert v.gt_bases[0] == '<*:DEL>/<*:DEL>'\n\ndef test_write_missing_contig():\n input_vcf = VCF('{}/seg.vcf.gz'.format(HERE))\n output_vcf = Writer('/dev/null', input_vcf)\n for v in input_vcf:\n v.genotypes = [[1,1,False]]\n output_vcf.write_record(v)\n output_vcf.close()\n\ndef test_set_samples():\n vcf = VCF(VCF_PATH)\n assert len(vcf.samples) == 189, len(vcf.samples)\n vcf.set_samples([vcf.samples[2]])\n assert len(vcf.samples) == 1\n v = next(vcf)\n assert len(v.gt_types) == 1\n\ndef test_hrec():\n\n vcf = VCF(VCF_PATH)\n for item in vcf.header_iter():\n info = item.info()\n if info['HeaderType'] != 'GENERIC':\n assert 'ID' in info\n\ndef test_issue44():\n vcf = VCF('{}/issue_44.vcf'.format(HERE))\n w = Writer('__o.vcf', vcf)\n for v in vcf:\n tmp = v.genotypes\n #print(tmp, file=sys.stderr)\n v.genotypes = tmp\n w.write_record(v)\n w.close()\n # \"./.\" \".\" \".|.\" \"0|0\"\n expected = [[-1, -1, False], [-1, False], [-1, -1, True], [0, 0, True]]\n #print(\"\", file=sys.stderr)\n for i, v in enumerate(VCF('__o.vcf')):\n #print(v.genotypes, file=sys.stderr)\n assert v.genotypes == [expected[i]], (i, v.genotypes, expected[i])\n os.unlink(\"__o.vcf\")\n\ndef test_id_field_updates():\n # 1 10172 . CCCTAA C 92.0 PASS\n v = VCF(VCF_PATH)\n variant = next(v)\n assert variant.ID is None, variant.ID\n\n variant.ID = 'foo'\n assert variant.ID == 'foo', variant.ID\n\n variant.ID = 100\n assert variant.ID == '100', variant.ID\n\n variant.ID = 100.1\n assert variant.ID == '100.1', variant.ID\n\n variant.ID = '.'\n assert variant.ID is None, variant.ID\n\n variant.ID = None\n assert variant.ID is None, variant.ID\n\ndef test_set_pos():\n test_vcf = '{}/test-strict-gt-option-flag.vcf.gz'.format(HERE)\n vcf = VCF(test_vcf, gts012=False)\n v = next(vcf)\n\n orig_pos, orig_start = v.POS, v.start\n v.set_pos(22)\n assert v.start == 22\n assert v.POS == 23\n\ndef test_set_chrom_when_contig_not_in_header():\n test_vcf = '{}/test-strict-gt-option-flag.vcf.gz'.format(HERE)\n new_chrom = \"NEW\"\n vcf = VCF(test_vcf, gts012=False)\n original_seqnames = vcf.seqnames\n assert new_chrom not in original_seqnames\n v = next(vcf)\n\n v.CHROM = new_chrom\n assert v.CHROM == new_chrom\n expected_seqnames = sorted(original_seqnames + [new_chrom])\n assert vcf.seqnames == expected_seqnames\n\ndef test_set_chrom_after_contig_is_added_to_header():\n test_vcf = '{}/test-strict-gt-option-flag.vcf.gz'.format(HERE)\n new_chrom = \"NEW\"\n vcf = VCF(test_vcf, gts012=False)\n original_seqnames = vcf.seqnames\n vcf.add_to_header(\"##contig=<ID={},length=15>\".format(new_chrom))\n expected_seqnames = sorted(original_seqnames + [new_chrom])\n assert vcf.seqnames == expected_seqnames\n v = next(vcf)\n\n v.CHROM = new_chrom\n assert v.CHROM == new_chrom\n\ndef test_set_qual():\n v = VCF(VCF_PATH)\n variant = next(v)\n assert variant.QUAL == 92.0\n\n variant.QUAL = 30.0\n assert variant.QUAL == 30.0\n\n with assert_raises(TypeError):\n variant.QUAL = \"30.0\"\n\n variant.QUAL = None\n assert variant.QUAL is None, 'variant.QUAL is {}'.format(variant.QUAL)\n\ndef test_strict_gt_option_flag():\n test_vcf = '{}/test-strict-gt-option-flag.vcf.gz'.format(HERE)\n\n truth_gt_bases = ('T/T', 'C/C', 'T/C', 'C/T', 'C/.', './C', 'T/.', './T', './.')\n truth_genotypes = (\n [0, 0, False],\n [1, 1, False],\n [0, 1, False],\n [1, 0, False],\n [1, -1, False],\n [-1, 1, False],\n [0, -1, False],\n [-1, 0, False],\n [-1, -1, False],\n )\n\n vcf = VCF(test_vcf, gts012=False)\n variant = next(vcf)\n\n msg = \"VCF(gts012=False, strict_gt=False) not working\"\n truth_gt_types = (0, 3, 1, 1, 1, 1, 0, 0, 2)\n assert bool(tuple(variant.gt_bases.tolist()) == truth_gt_bases), '{} [gt_bases]'.format(msg)\n assert bool(tuple(variant.gt_types.tolist()) == truth_gt_types), '{} [gt_types]'.format(msg)\n assert bool(tuple(variant.genotypes) == truth_genotypes), '{} (genotypes)'.format(msg)\n\n vcf = VCF(test_vcf, gts012=False, strict_gt=True)\n variant = next(vcf)\n\n msg = \"VCF(gts012=False, strict_gt=True) not working\"\n truth_gt_types = (0, 3, 1, 1, 2, 2, 2, 2, 2)\n assert bool(tuple(variant.gt_bases.tolist()) == truth_gt_bases), '{} [gt_bases]'.format(msg)\n assert bool(tuple(variant.gt_types.tolist()) == truth_gt_types), '{} [gt_types]'.format(msg)\n assert bool(tuple(variant.genotypes) == truth_genotypes), '{} (genotypes)'.format(msg)\n\n\n vcf = VCF(test_vcf, gts012=True)\n variant = next(vcf)\n\n msg = \"VCF(gts012=True, strict_gt=False) not working\"\n truth_gt_types = (0, 2, 1, 1, 1, 1, 0, 0, 3)\n assert tuple(variant.gt_bases.tolist()) == truth_gt_bases, '{} [gt_bases]'.format(msg)\n #sys.stderr.write(\"\\nobs:%s\\n\" % variant.gt_types.tolist())\n #sys.stderr.write(\"exp:%s\\n\" % list(truth_gt_types))\n assert tuple(variant.gt_types.tolist()) == truth_gt_types, '{} [gt_types]'.format(msg)\n assert tuple(variant.genotypes) == truth_genotypes, '{} (genotypes)'.format(msg)\n\n vcf = VCF(test_vcf, gts012=True, strict_gt=True)\n variant = next(vcf)\n\n msg = \"VCF(gts012=True, strict_gt=True) not working\"\n truth_gt_types = (0, 2, 1, 1, 3, 3, 3, 3, 3)\n assert tuple(variant.gt_bases.tolist()) == truth_gt_bases, '{} [gt_bases]'.format(msg)\n assert tuple(variant.gt_types.tolist()) == truth_gt_types, '{} [gt_types]'.format(msg)\n assert tuple(variant.genotypes) == truth_genotypes, '{} (genotypes)'.format(msg)\n\ndef test_alt_repr():\n v = os.path.join(HERE, \"test-alt-repr.vcf\")\n vcf = VCF(v, gts012=True, strict_gt=False)\n v = next(vcf)\n assert np.all(v.gt_types == np.array([0, 1, 2, 0, 1, 3]))\n\n v = os.path.join(HERE, \"test-alt-repr.vcf\")\n vcf = VCF(v, gts012=False, strict_gt=False)\n v = next(vcf)\n assert np.all(v.gt_types == np.array([0, 1, 3, 0, 1, 2]))\n\n\n\"\"\"\ndef test_seqlens():\n v = VCF(VCF_PATH)\n assert v.seqlens == [249250621, 243199373, 198022430, 191154276,\n 180915260, 171115067, 159138663, 146364022, 141213431, 135534747,\n 135006516, 133851895, 115169878, 107349540, 102531392, 90354753,\n 81195210, 78077248, 59128983, 63025520, 48129895, 51304566, 155270560,\n 59373566, 16569, 4262, 15008, 19913, 27386, 27682, 33824, 34474, 36148,\n 36422, 36651, 37175, 37498, 38154, 38502, 38914, 39786, 39929, 39939,\n 40103, 40531, 40652, 41001, 41933, 41934, 42152, 43341, 43523, 43691,\n 45867, 45941, 81310, 90085, 92689, 106433, 128374, 129120, 137718,\n 155397, 159169, 161147, 161802, 164239, 166566, 169874, 172149, 172294,\n 172545, 174588, 179198, 179693, 180455, 182896, 186858, 186861, 187035,\n 189789, 191469, 211173, 547496, 171823, 35477943, 5386], v.seqlens\n \"\"\"\n\ndef test_closed_iter():\n path = os.path.join(HERE, \"test-alt-repr.vcf\")\n vcf = VCF(path, gts012=True, strict_gt=False)\n vcf.close()\n\n assert_raises(Exception, next, vcf)\n\ndef test_issue72():\n path = os.path.join(HERE, \"test-alt-repr.vcf\")\n vcf = VCF(path, gts012=True, strict_gt=False)\n\n v = next(vcf)\n assert v.INFO['DQ'] == 1\n\n assert v.format('DQ') is not None\n\ndef test_is_transition():\n vcf = VCF(VCF_ALTFREQ_PATH)\n\n for r in vcf:\n assert r.is_transition\n\ndef test_decomposed():\n vcf = VCF(os.path.join(HERE, \"decomposed.vcf\"))\n v = next(vcf)\n #0/.\t./0\t1/.\t./1\t./.\n assert np.all(v.gt_types == np.array([vcf.HOM_REF, vcf.HOM_REF, vcf.HET, vcf.HET, vcf.UNKNOWN]))\n\n\ndef test_fd():\n\n fh = open(os.path.join(HERE, \"decomposed.vcf\"))\n fn = fh.fileno()\n\n vcf = VCF(fn)\n v = next(vcf)\n assert np.all(v.gt_types == np.array([vcf.HOM_REF, vcf.HOM_REF, vcf.HET, vcf.HET, vcf.UNKNOWN]))\n fh.close()\n vcf.close()\n\n\ndef test_set_reference():\n fh = open(os.path.join(HERE, \"decomposed.vcf\"))\n fn = fh.fileno()\n\n vcf = VCF(fn)\n for v in vcf:\n v.REF = \"CCCCA\"\n assert \"CCCCA\" in str(v)\n\ndef test_set_alternates():\n fh = open(os.path.join(HERE, \"decomposed.vcf\"))\n fn = fh.fileno()\n\n vcf = VCF(fn)\n for v in vcf:\n v.ALT = \"TTT,GGG\"\n assert \"TTT,GGG\" in str(v)\n\n v.ALT = [\"AAAC\", \"CCCA\"]\n assert \"AAAC,CCCA\" in str(v)\n\ndef test_no_seqlen():\n\n vcf_path = os.path.join(HERE, \"no-seq-len.vcf\")\n vcf = VCF(vcf_path)\n assert vcf.seqnames == [\"3\"]\n with assert_raises(AttributeError) as ae:\n vcf.seqlens\n assert isinstance(ae.exception, AttributeError)\n" ]
[ [ "numpy.array", "numpy.int32" ] ]
jay-z007/neumann-optimizer
[ "c931631346a1097d198983684d7c68d91ae82d39" ]
[ "NeumannOptimizerNumpy.py" ]
[ "import numpy as np\nimport time\nfrom math import exp\nimport matplotlib.pyplot as plt\n\ndef gradient_descent( func, initial_x, eps=1e-5, maximum_iterations=65536, learning_rate=1e-2 ):\n \"\"\"\n Gradient Descent\n func: the function to optimize It is called as \"value, gradient = func( x, 1 )\n initial_x: the starting point, should be a float\n eps: the maximum allowed error in the resulting stepsize t\n maximum_iterations: the maximum allowed number of iterations\n linesearch: the linesearch routine\n *linesearch_args: the extra arguments of linesearch routine\n \"\"\"\n\n if eps <= 0:\n raise ValueError(\"Epsilon must be positive\")\n x = np.matrix(initial_x)\n\n # initialization\n values = []\n runtimes = []\n xs = []\n start_time = time.time()\n iterations = 0\n\n # gradient updates\n while True:\n\n value, gradient = func( x , 1 )\n value = np.double( value )\n gradient = np.matrix( gradient )\n\n # updating the logs\n values.append( value )\n runtimes.append( time.time() - start_time )\n xs.append( x.copy() )\n\n direction = -gradient\n\n if np.linalg.norm(direction)<eps:\n break\n\n t = learning_rate\n\n x = x + t * direction\n\n iterations += 1\n if iterations >= maximum_iterations:\n break\n return (x, values, runtimes, xs)\n\ndef linear_regression(x, y, w, b, order=0):\n output = w*x.T + b\n error = np.mean((y-output)**2)\n if order == 1:\n grad_w = -2*x.T*(y-(w*x.T + b))\n grad_b = -2*(y-(w*x.T + b))\n grad_w = np.mean(grad_w)\n grad_b = np.mean(grad_b)\n return output, grad_w, grad_b\n return output\n\ndef boyd_example_func(x, order=0):\n a=np.matrix('1 3')\n b=np.matrix('1 -3')\n c=np.matrix('-1 0')\n x=np.asmatrix(x)\n\n value = exp(a*x-0.1)+exp(b*x-0.1)+exp(c*x-0.1)\n if order==0:\n return value\n elif order==1:\n gradient = a.T*exp(a*x-0.1)+b.T*exp(b*x-0.1)+c.T*exp(c*x-0.1)\n return (value, gradient)\n elif order==2:\n gradient = a.T*exp(a*x-0.1)+b.T*exp(b*x-0.1)+c.T*exp(c*x-0.1)\n hessian = a.T*a*exp(a*x-0.1)+b.T*b*exp(b*x-0.1)+c.T*c*exp(c*x-0.1)\n return (value, gradient, hessian)\n else:\n raise ValueError(\"The argument \\\"order\\\" should be 0, 1 or 2\")\n\ndef neumann( func, initial_x, learning_rate=1e-2, eps=1e-5, maximum_iterations=65536):\n x = np.matrix(initial_x)\n # moving_average = x\n neumann_iterate = 0\n iterate = 0\n k_value = 10\n values = []\n runtimes = []\n xs = []\n grad_norm = []\n start_time = time.time()\n while True:\n print(x)\n if iterate < 5:\n value, grad = func(x, 1)\n x = x - learning_rate*grad\n iterate += 1\n continue\n\n values.append( value )\n runtimes.append( time.time() - start_time )\n xs.append( x.copy() )\n\n eta = 0.5/iterate\n mu = iterate/(iterate + 1)\n mu = min(max(mu, 0.5),0.9)\n\n value, grad = func(x, 1)\n\n grad_norm.append(np.linalg.norm(grad)**2)\n\n if np.linalg.norm(grad)**2 < eps:\n break\n\n if iterate % k_value == 0:\n neumann_iterate = -eta*grad\n k_value *= 2\n\n #Removing crazy function as we're only trying on convex function\n\n neumann_iterate = mu*neumann_iterate - eta*grad\n\n x = x + mu*neumann_iterate - eta*grad\n # moving_average =\n iterate += 1\n if iterate >= maximum_iterations:\n break\n return x,values,runtimes,xs,grad_norm\n\n\ndef draw_contour( func, neumann_xs, fig, levels=np.arange(5, 1000, 10), x=np.arange(-5, 5.1, 0.05), y=np.arange(-5, 5.1, 0.05)):\n \"\"\"\n Draws a contour plot of given iterations for a function\n func: the contour levels will be drawn based on the values of func\n gd_xs: gradient descent iterates\n newton_xs: Newton iterates\n fig: figure index\n levels: levels of the contour plot\n x: x coordinates to evaluate func and draw the plot\n y: y coordinates to evaluate func and draw the plot\n \"\"\"\n Z = np.zeros((len(x), len(y)))\n for i in range(len(x)):\n for j in range(len(y)):\n Z[i, j] = func( np.matrix([x[i],y[j]]).T , 0 )\n\n plt.figure(fig)\n plt.contour( x, y, Z.T, levels, colors='0.75')\n plt.ion()\n plt.show()\n\n # line_gd, = plt.plot( gd_xs[0][0,0], gd_xs[0][1,0], linewidth=2, color='r', marker='o', label='GD' )\n line_newton, = plt.plot( neumann_xs[0][0,0], neumann_xs[0][1,0], linewidth=2, color='m', marker='o',label='Neumann' )\n\n L = plt.legend(handles=[line_newton])\n plt.draw()\n time.sleep(1)\n\n for i in range( 1, len(neumann_xs)):\n\n # line_gd.set_xdata( np.append( line_gd.get_xdata(), gd_xs[ min(i,len(gd_xs)-1) ][0,0] ) )\n # line_gd.set_ydata( np.append( line_gd.get_ydata(), gd_xs[ min(i,len(gd_xs)-1) ][1,0] ) )\n\n line_newton.set_xdata( np.append( line_newton.get_xdata(), neumann_xs[ min(i,len(neumann_xs)-1) ][0,0] ) )\n line_newton.set_ydata( np.append( line_newton.get_ydata(), neumann_xs[ min(i,len(neumann_xs)-1) ][1,0] ) )\n\n\n # L.get_texts()[0].set_text( \" GD, %d iterations\" % min(i,len(gd_xs)-1) )\n L.get_texts()[0].set_text( \" Neumann, %d iterations\" % min(i,len(neumann_xs)-1) )\n\n plt.draw()\n input(\"Press Enter to continue...\")\n\n\ninitial_x = np.matrix('-1.0; -1.0')\n\nx, values, runtimes, neumann_xs, grad_norm = neumann(boyd_example_func, initial_x)\nx_gd, gd_values, runtimes_gd, gradient_xs = gradient_descent(boyd_example_func, initial_x)\nplt.figure(1)\nline_gd, = plt.semilogy([x for x in values], linewidth=2, color='r', marker='o', label='Neumann')\nline_neumann, = plt.semilogy([x for x in gd_values], linewidth=2, color='b', marker='o', label='Neumann')\nplt.figure(2)\nplt.semilogy([x for x in grad_norm], linewidth=2, color='b', marker='o', label='Neumann')\ndraw_contour( boyd_example_func, neumann_xs, 3, levels=np.arange(0, 15, 1), x=np.arange(-2, 2, 0.1), y=np.arange(-2, 2, 0.1))\n" ]
[ [ "numpy.matrix", "matplotlib.pyplot.semilogy", "matplotlib.pyplot.legend", "numpy.arange", "numpy.linalg.norm", "matplotlib.pyplot.draw", "numpy.asmatrix", "matplotlib.pyplot.plot", "numpy.mean", "matplotlib.pyplot.contour", "matplotlib.pyplot.ion", "numpy.double", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
nrjl/GPN
[ "c7bd98d69e075ef05bcb2a443c02a71a916a71f4" ]
[ "GPy_regression_demo.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Polygon\n#from matplotlib.collections import PatchCollection\nimport nice_plot_colors as npc\nimport GPy\nplt.rc('font',**{'family':'serif','sans-serif':['Computer Modern Roman']})\nplt.rc('text', usetex=True)\n\n\nnp.random.seed(1)\nnoise = 0.2\nn_training = 8\nopt_hyper = False\n\ngp_l = 0.02\ngp_var = 1.0**2\ngp_noisevar = 0.1**2\n\n# Define polynomial function to be modelled\ndef true_function(x):\n #c = np.array([3,5,-9,-3,2],float)\n #y = np.polyval(c,x)\n y = np.sin(x*np.pi*1.5)\n return y\n\n# Define noisy observation function\ndef obs_function(x, sigma):\n y = true_function(x) + np.random.normal(0,sigma,(len(x),1))\n return y\n \ndef make_poly_array(x,y,sigma):\n nx = len(x)\n sig = np.array(sigma)\n xy = np.zeros((2*nx, 2))\n xy[:,0] = np.append(x, x[::-1])\n if sig.size > 1:\n rsig = sig[::-1]\n else:\n rsig = sig\n xy[:,1] = np.append(y-sig, y[::-1]+rsig)\n return xy\n\n \n# Main program\n# Plot true function\nnxp = 100\nx_plot = np.atleast_2d(np.linspace(-2.0,2.0,nxp,dtype='float')).T\nfx_plot = true_function(x_plot)\n\n# Training data\nx_train = np.random.random((n_training,1))*1.5-0.75\ny_train = obs_function(x_train, noise)\n\n# GP \nkernel = GPy.kern.RBF(input_dim=1, variance=gp_var, lengthscale=gp_l)\ngp = GPy.models.GPRegression(x_train,y_train,kernel)\ngp.Gaussian_noise.variance = gp_noisevar\nif opt_hyper:\n gp.optimize()\n\n# Predict\nfhat_test,var_test = gp.predict(x_plot)\n\n# Plot\nh_fig,h_ax = plt.subplots()\nh_fx, = h_ax.plot(x_plot,fx_plot,lw=1.5,c=npc.lines[0])\n\npatch_fx = Polygon(make_poly_array(x_plot,fx_plot,noise), ec=npc.lines[0], fc=npc.lighten(npc.lines[0], 3),alpha=0.5)\nh_ax.add_patch(patch_fx)\nh_y, = h_ax.plot(x_train,y_train,'rx',mew=1.0,ms=8)\n\npatch_fhat = Polygon(make_poly_array(x_plot,fhat_test,np.sqrt(var_test)), ec=npc.lines[1], fc=npc.lighten(npc.lines[1], 3),alpha=0.5)\nh_ax.add_patch(patch_fhat)\nh_fhat, = h_ax.plot(x_plot, fhat_test,lw=1.5,ls='--',c=npc.lines[1])\n\nh_ax.set_ylim([-3,3])\ngp_str = '$\\hat{{f}}(x) \\sim \\mathcal{{GP}}(l={0:0.2f}, \\sigma_f={1:0.2f}, \\sigma_n={2:0.2f})$'\ngp_str = gp_str.format(kernel.lengthscale.values[0], np.sqrt(kernel.variance.values[0]), np.sqrt(gp.Gaussian_noise.variance.values[0]))\nh_ax.legend((h_fx, h_y, h_fhat),('$f(x)$', '$y \\sim \\mathcal{N}(f(x), \\sigma^2)$', gp_str), loc='best')\nh_ax.set_xlabel('$x$')\n#h_fig.savefig('fig/regression_example.pdf', bbox_inches='tight', transparent='true')\nplt.show()" ]
[ [ "numpy.random.random", "numpy.sqrt", "numpy.random.seed", "numpy.linspace", "matplotlib.pyplot.rc", "matplotlib.pyplot.subplots", "numpy.sin", "numpy.append", "numpy.array", "matplotlib.pyplot.show", "numpy.zeros" ] ]
cylance/rogers
[ "a2300ed518fa01e0f2fcb77f1c10f7124ea7f49a" ]
[ "src/rogers/__main__.py" ]
[ "\"\"\" Entry points for Rogers malware similarity tool\n\"\"\"\nfrom . import config\nfrom . import store\nfrom .index import Index\nfrom .generated import Feature\nfrom .sample import pe\nfrom . import logger as l\nfrom . import api\n\nimport argparse\nimport pandas as pd\n\n\nlog = l.get_logger('rogers')\n\n\nINDEX_OPTIONS = Index.list_available_index()\n\n\ndef _samples_from_args(args):\n \"\"\" Get sample or samples from args\n :param args:\n :return: list of Samples\n \"\"\"\n db = store.Database()\n if args.input:\n hashvals = set(pd.read_csv(args.input)['sha256'].tolist())\n log.info(\"Loading samples for %s input hashes for index command\", len(hashvals))\n return [s for s in map(lambda x: db.load_sample(x), hashvals) if s is not None]\n elif hasattr(args, 'hashval') and args.hashval:\n log.info(\"Loading %s hashvals\" % len(args.hashval))\n return [s for s in map(lambda x: db.load_sample(x), args.hashval) if s is not None]\n else:\n log.info(\"Loading %s samples from db\", db.n)\n return [s for s in db.get_samples()]\n\n\ndef features_get(args):\n api.features_get(args.hashval, console_print=args.print, export=args.export)\n\n\ndef feature_add(args):\n api.feature_add(args.input, args.type, args.modaility)\n\n\ndef db_initialize(args):\n api.db_initialize()\n\n\ndef db_info(args):\n api.db_info()\n\n\ndef db_reset(args):\n api.db_reset()\n\n\ndef extract(args):\n if args.input:\n filter_hashvals = set(pd.read_csv(args.input)['sha256'].tolist())\n log.info(\"Filtering out %s samples by hashval for extraction\", len(filter_hashvals))\n else:\n filter_hashvals = None\n api.extract(args.dir, filter_hashvals=filter_hashvals, force=args.f)\n\n\ndef transform(args):\n samples = _samples_from_args(args)\n api.transform(args.index, samples)\n\n\ndef fit(args):\n samples = _samples_from_args(args)\n api.fit(args.index, samples)\n\n\ndef query(args):\n samples = _samples_from_args(args)\n api.query(args.index, samples, k=args.k, export=args.export, console_print=args.print)\n\n\ndef main():\n parser = argparse.ArgumentParser(prog='rogers', description='Malware similarity tool')\n subparsers = parser.add_subparsers(help='commands')\n parser.set_defaults(func=None)\n parser.add_argument('-v', action='store_true', help='Set debug logging')\n parser.add_argument('--print', action='store_true', help='Print results instead of table output')\n parser.add_argument('--conf', default=None, help='Path to rogers configuration file')\n\n # features command\n features_parser = subparsers.add_parser('feature')\n features_subparsers = features_parser.add_subparsers(help='Feature commands')\n\n # features get\n features_get_parser = features_subparsers.add_parser('get')\n features_get_parser.add_argument('hashval', type=str, help='sha256 hashval')\n features_get_parser.add_argument('--export', default=config.CWD, type=str, help='Dir to export sample feature as JSON')\n features_get_parser.set_defaults(func=features_get)\n\n # features add\n feature_add_parser = features_subparsers.add_parser('add')\n feature_add_parser.set_defaults(func=feature_add)\n feature_add_parser.add_argument('input', default=None, type=str, help='Path to CSV containing hashval column and feature columns')\n feature_add_parser.add_argument('--type', default='CATEGORICAL', choices=Feature.Variable.Type.keys(), type=str, help='Type of feature variable')\n feature_add_parser.add_argument('--modality', default='CONTEXTUAL', choices=Feature.Modality.Type.keys(), type=str, help='Type of feature modality')\n\n # db command\n db_parser = subparsers.add_parser('db')\n db_subparsers = db_parser.add_subparsers(help='Sample database admin commands')\n\n # db init\n init_parser = db_subparsers.add_parser('init')\n init_parser.set_defaults(func=db_initialize)\n\n # db list\n db_info_parser = db_subparsers.add_parser('info')\n db_info_parser.set_defaults(func=db_info)\n\n # db reset\n reset_parser = db_subparsers.add_parser('reset')\n reset_parser.set_defaults(func=db_reset)\n\n # index commands\n index_parser = subparsers.add_parser('index')\n index_parser.add_argument('--dir', default=None, type=str, help='Optional directory of samples, defaults to sample dir')\n index_parser.add_argument('--input', default=None, type=str, help='Optional path to CSV containing hashval column for index command')\n index_subparsers = index_parser.add_subparsers(help='index commands')\n\n # extract\n extract_parser = index_subparsers.add_parser('extract')\n extract_parser.add_argument('-f', action='store_true', help='Force extraction')\n extract_parser.set_defaults(func=extract)\n\n # transform\n transform_parser = index_subparsers.add_parser('transform')\n transform_parser.add_argument('index', choices=INDEX_OPTIONS, type=str, help='Name of index type')\n transform_parser.set_defaults(func=transform)\n\n # fit\n fit_parser = index_subparsers.add_parser('fit')\n fit_parser.add_argument('index', choices=INDEX_OPTIONS, type=str, help='Name of index type')\n fit_parser.set_defaults(func=fit)\n\n # partial_fit\n # TODO\n # partial_fit_parser = index_subparsers.add_parser('partial-fit')\n # partial_fit_parser.set_defaults(func=cli.partial_fit)\n\n # query\n query_parser = index_subparsers.add_parser('query')\n query_parser.add_argument('index', choices=INDEX_OPTIONS, type=str, help='Name of index type')\n query_parser.add_argument('hashval', default=None, nargs='*', type=str, help='sha256 hashval or path to CSV')\n query_parser.add_argument('--k', default=5, type=int, help='Number of nearest neighbors to return in query')\n query_parser.add_argument('--export', default=\"query_results.csv\", type=str, help='Path to export query results as csv')\n query_parser.set_defaults(func=query)\n\n args = parser.parse_args()\n\n if args.v:\n log_level = l.logging.DEBUG\n else:\n log_level = l.logging.INFO\n\n l.init_logging(level=log_level)\n\n if args.conf is not None:\n config.configure(args.conf)\n\n if args.func is None:\n parser.print_help()\n else:\n args.func(args)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "pandas.read_csv" ] ]
paocarvajal1912/VIXM-Algorithmic-Strategy
[ "acc8fa7cc735638f1605cd7a8785e01b499f5d58" ]
[ "vixcoin_functions/feature_functions.py" ]
[ "# Vixm Feature Functions\n\nimport pandas as pd\nfrom arch import arch_model\nimport yfinance as yf\nfrom datetime import datetime\nimport numpy as np\n\n\ndef garch_fit_and_predict(series, ticker, horizon=1, p=1, q=1, o=1, print_series_name=False):\n #p=1,q=1, o=1 \n #series=returns_df['spy']\n #horizon=1\n \"\"\"\n This function takes a series of returns, and get back the GJR-GARCH time series fit for the conditional volatility, \n using one shock, and a t-student distribution of errors that accepts a skew.\n \n Args:\n series: a pandas Series containing the time series of returns for which to predict its unconditional volatility\n ticker: a string with the security name or the time series name for the output of the model\n horizon=1: integer. The number of future out of sample predictions of the model. It is set up to one per default.\n p,q,1: integer parameters of the GJR-GARCH model desired. All of them are defaulted to 1.\n For details on this parameters see:\n https://arch.readthedocs.io/en/latest/univariate/generated/arch.univariate.base.ARCHModel.html\n print_series_name: indicator for output messages every time a series fit is completed. It is set to False per default.\n When it's set to True will print the output, when set to False, it will not.\n For details in the model see:\n https://arch.readthedocs.io/en/latest/univariate/univariate_volatility_modeling.html\n \n \n Return:\n A pandas Series which contains the GJR-GARCH time series fit for the conditional volatility, where the predicted value for the next day is\n set to t, where t is the last date of the time series provided. The idea is to include the out-of-sample prediction (horizon) as a feature\n in time t to predict t+1, where t is the present moment. The returned series have already made the shift.\n \"\"\"\n\n series=series.dropna()\n shock_skew_gm_model=arch_model(\n series, \n p=p, q=q, o=o,\n mean='constant',\n vol='GARCH',\n dist='skewt',\n rescale=True\n \n )\n if print_series_name==True:\n print(f\"Processing series: {ticker}.....\" )\n \n \n #Fit GARCH model and predict\n\n results_shock_skew_gm=shock_skew_gm_model.fit(update_freq=0, disp=\"off\")\n \n conditional_volatility=results_shock_skew_gm.conditional_volatility\n #summary =results_shock_skew_gm.summary()\n forecast =results_shock_skew_gm.forecast(horizon=1, reindex=False)\n\n # Prepare return of the series ready to include to X before shift\n serie_garch_before_shift=conditional_volatility.shift(-1)\n serie_garch_before_shift.iloc[-1,:]=forecast.variance.iloc[-1]\n\n return serie_garch_before_shift\n\n\n\ndef correlation_filter(series, min_corr=0.20, key_column='VIXM', eliminate_first_column=False):\n \n \"\"\"\n This function filters series that do not exceed the minimum correlation with the series defined in the key_column.\n Series that have only missing values are also eliminated.\n \n Args:\n \n series : a dataframe with time series to be filtered\n min_corr : a float number between -1 and 1 that indicated which is the minimum correlation to be included in the results\n key_column : the name of the columns with which the level of correlation is measured\n eliminate_first_column : option to exclude the first column from the results\n \"\"\"\n\n key_correlations = series.corr()[key_column]\n to_keep_columns = key_correlations[abs(key_correlations)>=min_corr].index\n filtered_series=series[to_keep_columns]\n \n if eliminate_first_column==True:\n filtered_series=filtered_series.iloc[:,1:]\n \n\n return filtered_series\n\n\n\n# Univariate retrievals (one ticker)\n\ndef retrieve_yahoo_close(ticker = 'spy', start_date = '2011-02-01', end_date = '2021-11-29'):\n \n \"\"\"\n This function retrieves from Yahoo Finance an individual time series of close prices from a given ticker\n If the close price for the ticker is not available, it provides an exception.\n \n Args:\n ticker: an string with the ticker to retrieve. Per default will retrieve the 'spy'\n start_date: the start date of the time series to retrieve in the format 'YYYY-MM-DD'. Per default will use '2007-07-02'\n end_date: the start date of the time series to retrieve in the format 'YYYY-MM-DD'. Per default will use '2021-10-01'\n \n Return:\n the time series of close price for the ticker as a Pandas Series with the Date and the close price time series\n \"\"\"\n\n try:\n # get data based on ticker\n yahoo_data = yf.Ticker(ticker)\n print(f\"Processing Close {ticker}\")\n # select close price data using start date and end data\n price_df = yahoo_data.history(start=start_date, end=end_date).Close\n price_df.name = ticker\n # if no data retrieved raise exception\n if price_df.shape[0] == 0:\n raise Exception(\"No Prices.\")\n return price_df\n # handle exception\n except Exception as ex:\n print(f\"Sorry, Data not available for '{ticker}': Exception is {ex}\")\n\n \n# Define function to retrieve one daily volume data from yahoo using ticker, start date and end date\ndef retrieve_yahoo_volume(ticker = 'spy', start_date = '2007-07-02', end_date = '2021-10-01'):\n\n \"\"\"\n This function retrieves from Yahoo Finance a time series of traded volume from a given ticker\n If the volume for the ticker is not available, it provides an exception.\n \n Args:\n ticker: an string with the ticker to retrieve. Per default will retrieve the 'spy'\n start_date: the start date of the time series to retrieve in the format 'YYYY-MM-DD'. Per default will use '2007-07-02'\n end_date: the start date of the time series to retrieve in the format 'YYYY-MM-DD'. Per default will use '2021-10-01'\n \n Return:\n The time series of traded volume for the ticker as a Pandas Series including the Date\n \"\"\"\n try:\n # get data based on ticker\n yahoo_data = yf.Ticker(ticker)\n print(f\"Processing Volume {ticker}\")\n # select data using start date and end data and calculate the daily return\n price_df = yahoo_data.history(start=start_date, end=end_date).Volume\n price_df.name = ticker\n # if no data retrieved raise exception\n if price_df.shape[0] == 0:\n raise Exception(\"No Prices.\")\n return price_df\n # handle exception\n except Exception as ex:\n print(f\"Sorry, Data not available for '{ticker}': Exception is {ex}\")\n\n# Define function to retrieve put daily volume data from yahoo using ticker, start date and end date\ndef retrieve_yahoo_put_options_volume(ticker = 'spy', date = '2007-07-02'):\n \"\"\"\n This functions retrieves a time series of intraday volume for a given day.\n If the volume for the ticker is not available, it provides an exception.\n \n Args:\n ticker: an string with the ticker to retrieve. Per default will retrieve the options of the SPY with 'spy'\n date: the date for which the intraday series of options volume is retrieved, using the format 'YYYY-MM-DD'. Per default it will use '2007-07-02'\n \n Return:\n The intraday volume data as a Panda Series\n \"\"\"\n\n try:\n # get data based on ticker\n yahoo_data = yf.Ticker(ticker)\n print(f\"Processing put volume from {ticker}\")\n # select data using start date and end data and calculate the daily return\n opts = yahoo_data.option_chain()\n price_df = opts.puts\n price_df.name = ticker\n price_df = price_df.volume\n # if no data retrieved raise exception\n if price_df.shape[0] == 0:\n raise Exception(\"No Prices.\")\n return price_df\n # handle exception\n except Exception as ex:\n print(f\"Sorry, Data not available for '{ticker}': Exception is {ex}\")\n\n \n# Multi-tickers in a list retrieval\n \ndef retrieve_close_multiple_tickers(ticker_list, start_date, end_date):\n \"\"\"\n This function retrieves close prices from Yahoo Finance for a ticker list\n \n Arg:\n ticker_list: a list of tickers of the yahoo close prices to be retrieve\n start_date: the start date of the time series to retrieve in the format 'YYYY-MM-DD'. \n end_date: the start date of the time series to retrieve in the format 'YYYY-MM-DD'. \n \n Return:\n A dictionary with close prices\n \"\"\"\n close_prices_dict = {}\n \n for ticker in ticker_list:\n close_price = retrieve_yahoo_close(ticker, start_date=start_date, end_date=end_date)\n close_prices_dict[ticker] = close_price\n close_prices_df=pd.DataFrame(close_prices_dict)\n return close_prices_df\n" ]
[ [ "pandas.DataFrame" ] ]
doudoupo/ray
[ "9aa0b4e89e240efe2d5c7ec17b6f2cd48ea2e021" ]
[ "python/ray/tests/test_object_spilling_3.py" ]
[ "import json\nimport re\nimport platform\nimport sys\nimport zlib\nimport shutil\nimport time\nfrom collections import defaultdict\nimport random\n\nimport numpy as np\nimport pytest\nimport ray\nfrom ray._private.test_utils import wait_for_condition\nfrom ray.tests.test_object_spilling import is_dir_empty, assert_no_thrashing\nfrom ray.cluster_utils import Cluster, cluster_not_supported\n\n\[email protected](platform.system() in [\"Windows\"], reason=\"Failing on \" \"Windows.\")\ndef test_multiple_directories(tmp_path, shutdown_only):\n num_dirs = 3\n temp_dirs = []\n for i in range(num_dirs):\n temp_folder = tmp_path / f\"spill_{i}\"\n temp_folder.mkdir()\n temp_dirs.append(temp_folder)\n\n # Limit our object store to 75 MiB of memory.\n min_spilling_size = 0\n object_spilling_config = json.dumps(\n {\n \"type\": \"filesystem\",\n \"params\": {\"directory_path\": [str(directory) for directory in temp_dirs]},\n }\n )\n address = ray.init(\n object_store_memory=75 * 1024 * 1024,\n _system_config={\n \"max_io_workers\": 5,\n \"object_store_full_delay_ms\": 100,\n \"object_spilling_config\": object_spilling_config,\n \"min_spilling_size\": min_spilling_size,\n },\n )\n\n arr = np.ones(74 * 1024 * 1024, dtype=np.uint8) # 74MB.\n object_refs = []\n # Now the storage is full.\n object_refs.append(ray.put(arr))\n\n num_object_spilled = 20\n for _ in range(num_object_spilled):\n object_refs.append(ray.put(arr))\n\n num_files = defaultdict(int)\n for temp_dir in temp_dirs:\n temp_folder = temp_dir / ray.ray_constants.DEFAULT_OBJECT_PREFIX\n for path in temp_folder.iterdir():\n num_files[str(temp_folder)] += 1\n\n for ref in object_refs:\n assert np.array_equal(ray.get(ref), arr)\n\n print(\"Check distribution...\")\n min_count = 5\n is_distributed = [n_files >= min_count for n_files in num_files.values()]\n assert all(is_distributed)\n\n print(\"Check deletion...\")\n # Empty object refs.\n object_refs = []\n # Add a new object so that the last entry is evicted.\n ref = ray.put(arr)\n for temp_dir in temp_dirs:\n temp_folder = temp_dir\n wait_for_condition(lambda: is_dir_empty(temp_folder))\n assert_no_thrashing(address[\"address\"])\n\n # Now kill ray and see all directories are deleted.\n print(\"Check directories are deleted...\")\n ray.shutdown()\n for temp_dir in temp_dirs:\n wait_for_condition(lambda: is_dir_empty(temp_dir, append_path=\"\"))\n\n\ndef _check_spilled(num_objects_spilled=0):\n def ok():\n s = ray.internal.internal_api.memory_summary(stats_only=True)\n if num_objects_spilled == 0:\n return \"Spilled \" not in s\n\n m = re.search(r\"Spilled (\\d+) MiB, (\\d+) objects\", s)\n if m is not None:\n actual_num_objects = int(m.group(2))\n return actual_num_objects >= num_objects_spilled\n\n return False\n\n wait_for_condition(ok, timeout=90, retry_interval_ms=5000)\n\n\ndef _test_object_spilling_threshold(thres, num_objects, num_objects_spilled):\n try:\n ray.init(\n object_store_memory=2_200_000_000,\n _system_config={\"object_spilling_threshold\": thres} if thres else {},\n )\n objs = []\n for _ in range(num_objects):\n objs.append(ray.put(np.empty(200_000_000, dtype=np.uint8)))\n time.sleep(10) # Wait for spilling to happen\n _check_spilled(num_objects_spilled)\n finally:\n ray.shutdown()\n\n\[email protected](platform.system() != \"Linux\", reason=\"Failing on Windows/macOS.\")\ndef test_object_spilling_threshold_default():\n _test_object_spilling_threshold(None, 10, 5)\n\n\[email protected](platform.system() != \"Linux\", reason=\"Failing on Windows/macOS.\")\ndef test_object_spilling_threshold_1_0():\n _test_object_spilling_threshold(1.0, 10, 0)\n\n\[email protected](platform.system() != \"Linux\", reason=\"Failing on Windows/macOS.\")\ndef test_object_spilling_threshold_0_1():\n _test_object_spilling_threshold(0.1, 10, 5)\n\n\ndef test_partial_retval_allocation(ray_start_cluster_enabled):\n cluster = ray_start_cluster_enabled\n cluster.add_node(object_store_memory=100 * 1024 * 1024)\n ray.init(cluster.address)\n\n @ray.remote(num_returns=4)\n def f():\n return [np.zeros(50 * 1024 * 1024, dtype=np.uint8) for _ in range(4)]\n\n ret = f.remote()\n for obj in ret:\n obj = ray.get(obj)\n print(obj.size)\n\n\ndef test_pull_spilled_object(\n ray_start_cluster_enabled, multi_node_object_spilling_config, shutdown_only\n):\n cluster = ray_start_cluster_enabled\n object_spilling_config, _ = multi_node_object_spilling_config\n\n # Head node.\n cluster.add_node(\n num_cpus=1,\n resources={\"custom\": 0},\n object_store_memory=75 * 1024 * 1024,\n _system_config={\n \"max_io_workers\": 2,\n \"min_spilling_size\": 1 * 1024 * 1024,\n \"automatic_object_spilling_enabled\": True,\n \"object_store_full_delay_ms\": 100,\n \"object_spilling_config\": object_spilling_config,\n },\n )\n ray.init(cluster.address)\n\n # add 1 worker node\n cluster.add_node(\n num_cpus=1, resources={\"custom\": 1}, object_store_memory=75 * 1024 * 1024\n )\n cluster.wait_for_nodes()\n\n @ray.remote(num_cpus=1, resources={\"custom\": 1})\n def create_objects():\n results = []\n for size in range(5):\n arr = np.random.rand(size * 1024 * 1024)\n hash_value = zlib.crc32(arr.tobytes())\n results.append([ray.put(arr), hash_value])\n # ensure the objects are spilled\n arr = np.random.rand(5 * 1024 * 1024)\n ray.get(ray.put(arr))\n ray.get(ray.put(arr))\n return results\n\n @ray.remote(num_cpus=1, resources={\"custom\": 0})\n def get_object(arr):\n return zlib.crc32(arr.tobytes())\n\n results = ray.get(create_objects.remote())\n for value_ref, hash_value in results:\n hash_value1 = ray.get(get_object.remote(value_ref))\n assert hash_value == hash_value1\n\n\n# TODO(chenshen): fix error handling when spilled file\n# missing/corrupted\[email protected](True, reason=\"Currently hangs.\")\ndef test_pull_spilled_object_failure(object_spilling_config, ray_start_cluster):\n object_spilling_config, temp_folder = object_spilling_config\n cluster = ray_start_cluster\n\n # Head node.\n cluster.add_node(\n num_cpus=1,\n resources={\"custom\": 0},\n object_store_memory=75 * 1024 * 1024,\n _system_config={\n \"max_io_workers\": 2,\n \"min_spilling_size\": 1 * 1024 * 1024,\n \"automatic_object_spilling_enabled\": True,\n \"object_store_full_delay_ms\": 100,\n \"object_spilling_config\": object_spilling_config,\n },\n )\n ray.init(cluster.address)\n\n # add 1 worker node\n cluster.add_node(\n num_cpus=1, resources={\"custom\": 1}, object_store_memory=75 * 1024 * 1024\n )\n cluster.wait_for_nodes()\n\n @ray.remote(num_cpus=1, resources={\"custom\": 1})\n def create_objects():\n arr = np.random.rand(5 * 1024 * 1024)\n hash_value = zlib.crc32(arr.tobytes())\n results = [ray.put(arr), hash_value]\n # ensure the objects are spilled\n arr = np.random.rand(5 * 1024 * 1024)\n ray.get(ray.put(arr))\n ray.get(ray.put(arr))\n return results\n\n @ray.remote(num_cpus=1, resources={\"custom\": 0})\n def get_object(arr):\n return zlib.crc32(arr.tobytes())\n\n [ref, hash_value] = ray.get(create_objects.remote())\n\n # remove spilled file\n shutil.rmtree(temp_folder)\n\n hash_value1 = ray.get(get_object.remote(ref))\n assert hash_value == hash_value1\n\n\[email protected](cluster_not_supported, reason=\"cluster not supported\")\ndef test_spill_dir_cleanup_on_raylet_start(object_spilling_config):\n object_spilling_config, temp_folder = object_spilling_config\n cluster = Cluster()\n cluster.add_node(\n num_cpus=0,\n object_store_memory=75 * 1024 * 1024,\n _system_config={\"object_spilling_config\": object_spilling_config},\n )\n ray.init(address=cluster.address)\n node2 = cluster.add_node(num_cpus=1, object_store_memory=75 * 1024 * 1024)\n\n # This task will run on node 2 because node 1 has no CPU resource\n @ray.remote(num_cpus=1)\n def run_workload():\n ids = []\n for _ in range(2):\n arr = np.random.rand(5 * 1024 * 1024) # 40 MB\n ids.append(ray.put(arr))\n return ids\n\n ids = ray.get(run_workload.remote())\n assert not is_dir_empty(temp_folder)\n\n # Kill node 2\n cluster.remove_node(node2)\n\n # Verify that the spill folder is not empty\n assert not is_dir_empty(temp_folder)\n\n # Start a new node\n cluster.add_node(num_cpus=1, object_store_memory=75 * 1024 * 1024)\n\n # Verify that the spill folder is now cleaned up\n assert is_dir_empty(temp_folder)\n\n # We hold the object refs to prevent them from being deleted\n del ids\n ray.shutdown()\n cluster.shutdown()\n\n\ndef test_spill_deadlock(object_spilling_config, shutdown_only):\n object_spilling_config, _ = object_spilling_config\n # Limit our object store to 75 MiB of memory.\n address = ray.init(\n object_store_memory=75 * 1024 * 1024,\n _system_config={\n \"max_io_workers\": 1,\n \"automatic_object_spilling_enabled\": True,\n \"object_store_full_delay_ms\": 100,\n \"object_spilling_config\": object_spilling_config,\n \"min_spilling_size\": 0,\n },\n )\n arr = np.random.rand(1024 * 1024) # 8 MB data\n replay_buffer = []\n\n # Create objects of more than 400 MiB.\n for _ in range(50):\n ref = None\n while ref is None:\n ref = ray.put(arr)\n replay_buffer.append(ref)\n # This is doing random sampling with 50% prob.\n if random.randint(0, 9) < 5:\n for _ in range(5):\n ref = random.choice(replay_buffer)\n sample = ray.get(ref, timeout=0)\n assert np.array_equal(sample, arr)\n assert_no_thrashing(address[\"address\"])\n\n\nif __name__ == \"__main__\":\n sys.exit(pytest.main([\"-sv\", __file__]))\n" ]
[ [ "numpy.array_equal", "numpy.ones", "numpy.random.rand", "numpy.zeros", "numpy.empty" ] ]
andreroche/Project2018
[ "d110e1c0c06368644b7212b6872d61551011dbfc" ]
[ "Project_Rev9.py" ]
[ "# André Roche 27-Apr-2018 Project Final - Programming and Scripting, Fisher's IRIS Data Set.\r\n# The program / script was developed in blocks or segments as learning and investigation continued. \r\n# This includes learning of python as a tool in addition to the investigation of the dataset.\r\n# For ease of review, each block will be named and will correspond with description of data in the final report.\r\n\r\n\r\n# Block 1 - basic attempt to get some inforamtion from the dataset\r\n\r\nimport numpy # import the numpy library\r\n\r\n# Please ensure that the iris dataset is loaded in working directory as presented in next line.\r\ndata = numpy.genfromtxt('data/iris_Dataset.csv', delimiter =',') # import dataset, genfromtxt function used to creat arrays from tabular data\r\nfrom scipy import stats # import the scipy library , from that import the statistics module\r\nfrom scipy.stats import skew, kurtosis, normaltest # from the statistics module, import skew, kurtosis and normaltest\r\n\r\n# Define each column. Assign data to these.The first column is the data in the first column and so on.\r\nfirstcol = data[:,0] \r\nsecondcol = data[:,1] \r\nthirdcol = data[:,2]\r\nfourthcol = data[:,3]\r\n\r\n# Using numpy.mean to calculate the mean value of each column.\r\nmeanfirstcol = numpy.mean(data[:,0])\r\nmeansecondcol = numpy.mean(data[:,1])\r\nmeanthirdcol = numpy.mean(data[:,2])\r\nmeanfourthcol = numpy.mean(data[:,3])\r\n\r\n# Using numpy.min to calculate the minimum value of each column.\r\nminfirstcol = numpy.min(data[:,0])\r\nminsecondcol = numpy.min(data[:,1])\r\nminthirdcol = numpy.min(data[:,2])\r\nminfourthcol = numpy.min(data[:,3])\r\n\r\n# Using numpy.max to calculate the max value of each column. \r\nmaxfirstcol = numpy.max(data[:,0])\r\nmaxsecondcol = numpy.max(data[:,1])\r\nmaxthirdcol = numpy.max(data[:,2])\r\nmaxfourthcol = numpy.max(data[:,3])\r\n\r\n# Using numpy.std to calculate the standard deviation or spread value of each column.\r\nstdfirstcol = numpy.std(data[:,0])\r\nstdsecondcol = numpy.std(data[:,1])\r\nstdthirdcol = numpy.std(data[:,2])\r\nstdfourthcol = numpy.std(data[:,3])\r\n\r\n# Using numpy.median to calculate the median value of each column.\r\nmedianfirstcol = numpy.median(data[:,0])\r\nmediansecondcol = numpy.median(data[:,1])\r\nmedianthirdcol = numpy.median(data[:,2])\r\nmedianfourthcol = numpy.median(data[:,3])\r\n\r\n# From the scipy library, using the stats module to calculate the skew of each column.\r\nskewfirstcol = skew(data[:,0])\r\nskewsecondcol = skew(data[:,1])\r\nskewthirdcol = skew(data[:,2])\r\nskewfourthcol = skew(data[:,3])\r\n\r\n# From the scipy library, using the stats module to calculate the kurtosis of each column.\r\nkurtfirstcol = kurtosis(data[:,0])\r\nkurtsecondcol = kurtosis(data[:,1])\r\nkurtthirdcol = kurtosis(data[:,2])\r\nkurtfourthcol = kurtosis(data[:,3])\r\n\r\n# From the scipy library, using the stats module to check 'normality' of the distribution of each column.\r\nnormfirstcol = normaltest(data[:,0])\r\nnormsecondcol = normaltest(data[:,1])\r\nnormthirdcol = normaltest(data[:,2])\r\nnormfourthcol = normaltest(data[:,3])\r\n\r\n\r\n# Printing quality solution indicators/summary of data to screen.\r\nprint ('The Summary for Sepal Length is as follows:')\r\nprint ('Max =', maxfirstcol)\r\nprint ('Min =', minfirstcol)\r\nprint ('Mean =', meanfirstcol)\r\nprint ('Standard Deviation =', stdfirstcol)\r\nprint ('Median =', medianfirstcol)\r\nprint ('Skew =', skewfirstcol)\r\nprint ('Kurtosis = ', kurtfirstcol)\r\nprint ('Normality = ', normfirstcol)\r\n\r\nprint('') # just print a line space on screen\r\n\r\nprint ('The Summary for Sepal Width is as follows:')\r\nprint ('Max =', maxsecondcol)\r\nprint ('Min =', minsecondcol)\r\nprint ('Mean =', meansecondcol)\r\nprint ('Standard Deviation =', stdsecondcol)\r\nprint ('Median =', mediansecondcol)\r\nprint ('Skew =', skewsecondcol)\r\nprint ('Kurtosis = ', kurtsecondcol)\r\nprint ('Normality = ', normsecondcol)\r\n\r\nprint('') # just print a line space on screen\r\n\r\nprint ('The Summary for Petal Length is as follows:')\r\nprint ('Max =', maxthirdcol)\r\nprint ('Min =', minthirdcol)\r\nprint ('Mean =', meanthirdcol)\r\nprint ('Standard Deviation =', stdthirdcol)\r\nprint ('Median =', medianthirdcol)\r\nprint ('Skew =', skewthirdcol)\r\nprint ('Kurtosis = ', kurtthirdcol)\r\nprint ('Normality = ', normthirdcol)\r\n\r\nprint('') # just print a line space on screen\r\n\r\nprint ('The Summary for Petal Width is as follows:')\r\nprint ('Max =', maxfourthcol)\r\nprint ('Min =', minfourthcol)\r\nprint ('Mean =', meanfourthcol)\r\nprint ('Standard Deviation =', stdfourthcol)\r\nprint ('Median =', medianfourthcol)\r\nprint ('Skew =', skewfourthcol)\r\nprint ('Kurtosis = ', kurtfourthcol)\r\nprint ('Normality = ', normfourthcol)\r\n\r\nprint('') # just print a line space on screen\r\n\r\n# Anova test of multiple means (means of all four columns / all four feature characteristics)\r\nstats.f_oneway(data[:,0],data[:,1], data[:,2],data[:,3]) # Anova (analysis of variance) test for more than two samples i.e. all features.\r\nprint('') # just print a line space on screen\r\nprint( 'Anova Results Are As Follows:') \r\nprint(stats.f_oneway(data[:,0],data[:,1], data[:,2],data[:,3]))\r\nprint('')\r\n\r\n\r\nimport matplotlib.pyplot as pl # import of matplotlib.pyplot library as pl alias. This is required for graphs.\r\n\r\npl.hist(firstcol) # plot a histogram of the first column.\r\npl.show() # show the histogram\r\n\r\npl.hist(secondcol) # plot a histogram of the second column.\r\npl.show() # show the histogram\r\n\r\npl.hist(thirdcol) # plot a histogram of the third column.\r\npl.show() # show the histogram\r\n\r\npl.hist(fourthcol) # plot a histogram of the fourth column.\r\npl.show() # show the histogram\r\n\r\n\r\n# Block 2 - use of librarys and associated modules for efficiency and more powerful tools.\r\n\r\n# Using pandas to import and print the Iris Dataset on-screen.\r\nimport pandas as pd # import pandas library with pd alias\r\nfrom pandas import scatter_matrix # import the scatter matrix tool\r\nimport seaborn as sns # import seaborn as sns alias\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import stats\r\nfrom scipy.stats import skew, kurtosis, kurtosistest, normaltest\r\n\r\n\r\n\r\ndf = sns.load_dataset('iris') # dataframe using seaborn to import the iris dataset. grouping the data by species column. \r\ndf.groupby('species').mean() \r\ndf.groupby('species').std()\r\ndf.groupby('species').median()\r\ndf.groupby('species').max()\r\ndf.groupby('species').min()\r\n\r\ndf.describe() #to give a statistical summary about the dataset\r\ndf.skew()\r\ndf.kurtosis()\r\nprint('')\r\nprint('Summary for the Dataset is as follows:')\r\nprint(df.describe())\r\n#print(df.skew())\r\n#print(df.kurtosis())\r\nprint('')\r\n# Printing the quality solution indicators for each feature but grouped by species.\r\nprint('The Mean of each feature across species is as follows:')\r\nprint(df.groupby('species').mean()) \r\nprint('')\r\nprint('The Standard Deviation of each feature across species is as follows:')\r\nprint(df.groupby('species').std())\r\nprint('')\r\nprint('The Median of each feature across species is as follows:')\r\nprint(df.groupby('species').median())\r\nprint('')\r\nprint('The Max of each feature across species is as follows:')\r\nprint(df.groupby('species').max())\r\nprint('')\r\nprint('The Min of each feature across species is as follows:')\r\nprint(df.groupby('species').min())\r\n\r\nprint('')\r\nprint('The correlation of features across species is as follows:')\r\nprint(df.corr()) # printing a correlation between featues across the dataset\r\n\r\n\r\ndf.groupby('species').boxplot()\r\nplt.show()\r\n\r\n\r\ndf.groupby('species').hist()\r\nplt.show()\r\n\r\ndf.groupby('species').sepal_length.hist()\r\nplt.show()\r\n\r\ndf.groupby('species').sepal_width.hist()\r\nplt.show()\r\n\r\ndf.groupby('species').petal_length.hist()\r\nplt.show()\r\n\r\ndf.groupby('species').petal_width.hist()\r\nplt.show()\r\n\r\npd.plotting.scatter_matrix(df)\r\nplt.show()\r\n\r\n# Block 3 - using Seaborn for more powerful and descriptive pairplots to better visualise dataset\r\n\r\nimport pandas as pd\r\nfrom pandas import scatter_matrix\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import stats\r\nfrom scipy.stats import skew, kurtosis, normaltest\r\n\r\n\r\ndf=pd.read_csv('data/iris_dataset.csv', header = None,\r\nnames = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'])\r\n\r\nimport seaborn as sns\r\nsns.set(style = \"ticks\", color_codes = True)\r\niris = sns.load_dataset(\"iris\")\r\np = sns.pairplot(iris)\r\nplt.show()\r\n\r\nimport seaborn as sns\r\nsns.set(style = \"ticks\", color_codes = True)\r\niris = sns.load_dataset(\"iris\")\r\nd = sns.pairplot(iris, hue = \"species\")\r\nplt.show()\r\n\r\nimport seaborn as sns\r\nsns.set(style = \"ticks\", color_codes = True)\r\niris = sns.load_dataset(\"iris\")\r\nf = sns.pairplot(iris, hue = \"species\", kind = \"reg\")\r\nplt.show()\r\n\r\n# Block 4 - Classification methods\r\n\r\nfrom sklearn.datasets import load_iris\r\n\r\niris = load_iris()\r\n\r\ntype (iris)\r\n\r\nprint ('The features values are:') # print to screen the text in inverted commas\r\nprint (iris.data) # print the iris data set\r\nprint('')\r\nprint ('The feature names and units of measurement are:')\r\nprint (iris.feature_names) # print the feature names\r\nprint('')\r\nprint ('The species target identity values are:') \r\nprint (iris.target) # print the target values - either a 0,1 or 2 (the species)\r\nprint('')\r\nprint ('The species names are as follows:')\r\nprint (iris.target_names) # print the names of the species\r\n\r\nprint('')\r\nprint (type(iris.data)) # what type is the data (it should be an numpy array)\r\nprint (type(iris.target)) # print what type is the target (it should be a numpy array)\r\n\r\nprint (iris.data.shape) # print the shape of the data (it should be 150 by 4)\r\nprint (iris.target.shape) # print he shape of the target (it should be 150)\r\n\r\nX = (iris.data) # assign X to the data (the feature data)\r\ny = (iris.target) # assign y to the target (the species)\r\n\r\n\r\n\r\nprint (X.shape) # print the shape of X\r\nprint (y.shape) # print the shape of y\r\nprint('')\r\n\r\n# using stats for classification. first method is K nearest neighbors.\r\nfrom sklearn.neighbors import KNeighborsClassifier # from library sklearn, import the function KNN or K nearest Neighbours \r\nknn= KNeighborsClassifier(n_neighbors=1) # define and use K = 1\r\n\r\nprint (knn) # print \r\n\r\nknn.fit(X,y) # fit\r\nX_old = ([[1,2,3,4]])\r\n\r\nprint('The results of the prediction are as follows:')\r\n\r\nknn.predict(X) # predict from this array\r\nprint (knn.predict(X_old)) # print the prediction to screen\r\n\r\nX_new = ([[3,5,4,2], [5,4,3,2]])\r\nknn.predict (X_new)\r\nprint (knn.predict(X_new)) # print the prediction to screen\r\n\r\nknn = KNeighborsClassifier(n_neighbors = 3) # change k to K= 3\r\nknn.fit(X,y)\r\nknn.predict(X_new)\r\nprint (knn.predict(X_new)) # the results from the new prediction where this time K=3\r\n\r\n\r\n# Different method for classification. Logistic Regression is not similiar to Linear Regression. \r\n\r\nfrom sklearn.linear_model import LogisticRegression # import\r\nlogreg = LogisticRegression() # define\r\nlogreg.fit(X,y) # perform the fit \r\nlogreg.predict(X_new) # make the prediction for X_new with this method \r\n\r\nprint(logreg.predict(X_new)) # print the prediction to screen\r\n\r\nprint ('Where: 0 = Setosa, 1 = Versicular, 2 = Virginica ') " ]
[ [ "scipy.stats.f_oneway", "pandas.read_csv", "sklearn.linear_model.LogisticRegression", "scipy.stats.normaltest", "numpy.min", "numpy.median", "sklearn.datasets.load_iris", "numpy.genfromtxt", "sklearn.neighbors.KNeighborsClassifier", "numpy.max", "numpy.std", "pandas.plotting.scatter_matrix", "numpy.mean", "scipy.stats.kurtosis", "matplotlib.pyplot.show", "scipy.stats.skew", "matplotlib.pyplot.hist" ] ]
ancientmooner/mmsegmentation
[ "1af2ad6a9f0a69e848c3cf8c307f75120c7f99b6" ]
[ "mmseg/models/decode_heads/decode_head.py" ]
[ "from abc import ABCMeta, abstractmethod\n\nimport torch\nimport torch.nn as nn\nfrom mmcv.cnn import normal_init\n\nfrom mmseg.core import build_pixel_sampler\nfrom mmseg.ops import resize\nfrom ..builder import build_loss\nfrom ..losses import accuracy\n\n\nclass BaseDecodeHead(nn.Module, metaclass=ABCMeta):\n \"\"\"Base class for BaseDecodeHead.\n\n Args:\n in_channels (int|Sequence[int]): Input channels.\n channels (int): Channels after modules, before conv_seg.\n num_classes (int): Number of classes.\n dropout_ratio (float): Ratio of dropout layer. Default: 0.1.\n conv_cfg (dict|None): Config of conv layers. Default: None.\n norm_cfg (dict|None): Config of norm layers. Default: None.\n act_cfg (dict): Config of activation layers.\n Default: dict(type='ReLU')\n in_index (int|Sequence[int]): Input feature index. Default: -1\n input_transform (str|None): Transformation type of input features.\n Options: 'resize_concat', 'multiple_select', None.\n 'resize_concat': Multiple feature maps will be resize to the\n same size as first one and than concat together.\n Usually used in FCN head of HRNet.\n 'multiple_select': Multiple feature maps will be bundle into\n a list and passed into decode head.\n None: Only one select feature map is allowed.\n Default: None.\n loss_decode (dict): Config of decode loss.\n Default: dict(type='CrossEntropyLoss').\n ignore_index (int): The label index to be ignored. Default: 255\n sampler (dict|None): The config of segmentation map sampler.\n Default: None.\n align_corners (bool): align_corners argument of F.interpolate.\n Default: False.\n \"\"\"\n\n def __init__(self,\n in_channels,\n channels,\n *,\n num_classes,\n dropout_ratio=0.1,\n conv_cfg=None,\n norm_cfg=None,\n act_cfg=dict(type='ReLU'),\n in_index=-1,\n input_transform=None,\n loss_decode=dict(\n type='CrossEntropyLoss',\n use_sigmoid=False,\n loss_weight=1.0),\n ignore_index=255,\n sampler=None,\n align_corners=False):\n super(BaseDecodeHead, self).__init__()\n self._init_inputs(in_channels, in_index, input_transform)\n self.channels = channels\n self.num_classes = num_classes\n self.dropout_ratio = dropout_ratio\n self.conv_cfg = conv_cfg\n self.norm_cfg = norm_cfg\n self.act_cfg = act_cfg\n self.in_index = in_index\n self.loss_decode = build_loss(loss_decode)\n self.ignore_index = ignore_index\n self.align_corners = align_corners\n if sampler is not None:\n self.sampler = build_pixel_sampler(sampler)\n else:\n self.sampler = None\n\n self.conv_seg = nn.Conv2d(channels, num_classes, kernel_size=1)\n if dropout_ratio > 0:\n self.dropout = nn.Dropout2d(dropout_ratio)\n else:\n self.dropout = None\n\n def extra_repr(self):\n \"\"\"Extra repr.\"\"\"\n s = f'input_transform={self.input_transform}, ' \\\n f'ignore_index={self.ignore_index}, ' \\\n f'align_corners={self.align_corners}'\n return s\n\n def _init_inputs(self, in_channels, in_index, input_transform):\n \"\"\"Check and initialize input transforms.\n\n The in_channels, in_index and input_transform must match.\n Specifically, when input_transform is None, only single feature map\n will be selected. So in_channels and in_index must be of type int.\n When input_transform\n\n Args:\n in_channels (int|Sequence[int]): Input channels.\n in_index (int|Sequence[int]): Input feature index.\n input_transform (str|None): Transformation type of input features.\n Options: 'resize_concat', 'multiple_select', None.\n 'resize_concat': Multiple feature maps will be resize to the\n same size as first one and than concat together.\n Usually used in FCN head of HRNet.\n 'multiple_select': Multiple feature maps will be bundle into\n a list and passed into decode head.\n None: Only one select feature map is allowed.\n \"\"\"\n\n if input_transform is not None:\n assert input_transform in ['resize_concat', 'multiple_select']\n self.input_transform = input_transform\n self.in_index = in_index\n if input_transform is not None:\n assert isinstance(in_channels, (list, tuple))\n assert isinstance(in_index, (list, tuple))\n assert len(in_channels) == len(in_index)\n if input_transform == 'resize_concat':\n self.in_channels = sum(in_channels)\n else:\n self.in_channels = in_channels\n else:\n assert isinstance(in_channels, int)\n assert isinstance(in_index, int)\n self.in_channels = in_channels\n\n def init_weights(self):\n \"\"\"Initialize weights of classification layer.\"\"\"\n normal_init(self.conv_seg, mean=0, std=0.01)\n\n def _transform_inputs(self, inputs):\n \"\"\"Transform inputs for decoder.\n\n Args:\n inputs (list[Tensor]): List of multi-level img features.\n\n Returns:\n Tensor: The transformed inputs\n \"\"\"\n\n if self.input_transform == 'resize_concat':\n inputs = [inputs[i] for i in self.in_index]\n upsampled_inputs = [\n resize(\n input=x,\n size=inputs[0].shape[2:],\n mode='bilinear',\n align_corners=self.align_corners) for x in inputs\n ]\n inputs = torch.cat(upsampled_inputs, dim=1)\n elif self.input_transform == 'multiple_select':\n inputs = [inputs[i] for i in self.in_index]\n else:\n inputs = inputs[self.in_index]\n\n return inputs\n\n @abstractmethod\n def forward(self, inputs):\n \"\"\"Placeholder of forward function.\"\"\"\n pass\n\n def forward_train(self, inputs, img_metas, gt_semantic_seg, train_cfg):\n \"\"\"Forward function for training.\n Args:\n inputs (list[Tensor]): List of multi-level img features.\n img_metas (list[dict]): List of image info dict where each dict\n has: 'img_shape', 'scale_factor', 'flip', and may also contain\n 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\n For details on the values of these keys see\n `mmseg/datasets/pipelines/formatting.py:Collect`.\n gt_semantic_seg (Tensor): Semantic segmentation masks\n used if the architecture supports semantic segmentation task.\n train_cfg (dict): The training config.\n\n Returns:\n dict[str, Tensor]: a dictionary of loss components\n \"\"\"\n seg_logits = self.forward(inputs)\n losses = self.losses(seg_logits, gt_semantic_seg)\n return losses\n\n def forward_test(self, inputs, img_metas, test_cfg):\n \"\"\"Forward function for testing.\n\n Args:\n inputs (list[Tensor]): List of multi-level img features.\n img_metas (list[dict]): List of image info dict where each dict\n has: 'img_shape', 'scale_factor', 'flip', and may also contain\n 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\n For details on the values of these keys see\n `mmseg/datasets/pipelines/formatting.py:Collect`.\n test_cfg (dict): The testing config.\n\n Returns:\n Tensor: Output segmentation map.\n \"\"\"\n return self.forward(inputs)\n\n def cls_seg(self, feat):\n \"\"\"Classify each pixel.\"\"\"\n if self.dropout is not None:\n feat = self.dropout(feat)\n output = self.conv_seg(feat)\n return output\n\n def losses(self, seg_logit, seg_label):\n \"\"\"Compute segmentation loss.\"\"\"\n loss = dict()\n seg_logit = resize(\n input=seg_logit,\n size=seg_label.shape[2:],\n mode='bilinear',\n align_corners=self.align_corners)\n if self.sampler is not None:\n seg_weight = self.sampler.sample(seg_logit, seg_label)\n else:\n seg_weight = None\n seg_label = seg_label.squeeze(1)\n loss['loss_seg'] = self.loss_decode(\n seg_logit,\n seg_label,\n weight=seg_weight,\n ignore_index=self.ignore_index)\n loss['acc_seg'] = accuracy(seg_logit, seg_label)\n return loss\n" ]
[ [ "torch.nn.Conv2d", "torch.nn.Dropout2d", "torch.cat" ] ]
danlamanna/ShapeWorks
[ "58ffac86cbea1e7f0b4ede9ff6ded167bd5dfc14" ]
[ "Python/DataAugmentationUtilsPackage/DataAugmentationUtils/Visualize.py" ]
[ "import csv\nimport re\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport pandas as pd \nfrom bokeh.document import Document\nfrom bokeh.embed import file_html\nfrom bokeh.layouts import gridplot\nfrom bokeh.models import (BasicTicker, Circle, ColumnDataSource, DataRange1d,\n Grid, LinearAxis, PanTool, Plot, WheelZoomTool,)\nfrom bokeh.resources import INLINE\nfrom bokeh.util.browser import view\n\ndef splom(data_csv):\n # read csv\n colors = []\n scores = []\n with open(data_csv, newline='') as csvfile:\n datareader = csv.reader(csvfile)\n index = 0\n for row in datareader:\n if \"Generated\" in row[0]:\n colors.append('red')\n else:\n colors.append('blue')\n scores.append(row[2:])\n scores = np.array(scores)\n\n # make splom\n plots = []\n for y in range(len(scores[0])):\n row = []\n for x in range(len(scores[0])):\n xax = (y == len(scores[0])-1)\n yax = (x == 0)\n xscores = [float(item) for item in list(scores[:,x])]\n yscores = [float(item) for item in list(scores[:,y])]\n source = ColumnDataSource(dict(x=xscores, y=yscores, colors=colors))\n plot = make_plot(source, x, y, xax, yax)\n row.append(plot)\n plots.append(row)\n\n grid = gridplot(plots)\n\n doc = Document()\n doc.add_root(grid)\n\n doc.validate()\n filename = \"augmentation_splom.html\"\n with open(filename, \"w\") as f:\n f.write(file_html(doc, INLINE, \"Data SPLOM\"))\n print(\"Wrote %s\" % filename)\n view(filename)\n\n\ndef make_plot(source, xindex, yindex, xax=False, yax=False):\n xdr = DataRange1d(bounds=None)\n ydr = DataRange1d(bounds=None)\n mbl = 40 if yax else 0\n mbb = 40 if xax else 0\n plot = Plot(\n x_range=xdr, y_range=ydr, background_fill_color=\"#efe8e2\",\n border_fill_color='white', plot_width=200 + mbl, plot_height=200 + mbb,\n min_border_left=2+mbl, min_border_right=2, min_border_top=2, min_border_bottom=2+mbb)\n\n circle = Circle(x='x', y='y', fill_color=\"colors\", fill_alpha=0.2, size=4, line_color=\"colors\")\n r = plot.add_glyph(source, circle)\n\n xdr.renderers.append(r)\n ydr.renderers.append(r)\n\n xticker = BasicTicker()\n if xax:\n xaxis = LinearAxis()\n xaxis.axis_label = str(xindex)\n plot.add_layout(xaxis, 'below')\n xticker = xaxis.ticker\n plot.add_layout(Grid(dimension=0, ticker=xticker))\n\n yticker = BasicTicker()\n if yax:\n yaxis = LinearAxis()\n yaxis.axis_label = str(yindex)\n yaxis.major_label_orientation = 'vertical'\n plot.add_layout(yaxis, 'left')\n yticker = yaxis.ticker\n plot.add_layout(Grid(dimension=1, ticker=yticker))\n\n plot.add_tools(PanTool(), WheelZoomTool())\n return plot\n\ndef violin(data_csv):\n # Get data frame\n types = []\n dims = []\n scores = []\n with open(data_csv, newline='') as csvfile:\n datareader = csv.reader(csvfile)\n index = 0\n for row in datareader:\n current_type = \"Original\"\n if \"Generated\" in row[0]:\n current_type = \"Generated\"\n for index in range(2, len(row)):\n types.append(current_type)\n dims.append(str(index-1))\n scores.append(float(row[index]))\n data = {'Data_Type':types, 'PCA_Mode':dims, \"PCA_Score\":scores}\n df = pd.DataFrame(data) \n # Plot\n sns.set_style(\"whitegrid\")\n ax = sns.violinplot(x=df.PCA_Mode, y=df.PCA_Score, hue=df.Data_Type,\n data=df, palette=\"Set2\", split=True, scale=\"count\")\n # Save and show\n plt.savefig(\"violin.png\") \n # img = Image.open('violin.png')\n # img.show() " ]
[ [ "numpy.array", "matplotlib.pyplot.savefig", "pandas.DataFrame" ] ]
qw85639229/Car_License_SVM
[ "c5b0062e84e5000c7940b1d90cc7c63e52afed21" ]
[ "recog_car_license_reshapevideo.py" ]
[ "#coding=UTF-8\nimport argparse\nimport logging\nimport os\n\nimport cv2\nimport numpy as np\nimport torch\nfrom PIL import Image, ImageDraw, ImageFont\nfrom torchvision import transforms\n\nfrom OCR_For_Car_License.cnn import ConvNet_Car_License\nfrom detect_car_license import detect_car_license\n# import caffe\n# from numpy.linalg import norm\n# import sys\n# import json\nfrom predict_version_1_onlyforBLUE import CardPredictor\n\n# SZ = 20 #训练图片长宽\n# MAX_WIDTH = 1000 #原始图片最大宽度\n# Min_Area = 2000 #车牌区域允许最大面积\n# PROVINCE_START = 1000\n\nlogging.basicConfig(format='%(asctime)s %(levelname)s:%(lineno)s] %(message)s',\n datefmt='%H:%M:%S', level=logging.INFO)\n\n\ndef diff(name, t_tensor, c_tensor):\n if t_tensor.shape != c_tensor.shape:\n logging.warning('t_tensor: {:}, c_tensor: {:}'.format(t_tensor.shape, c_tensor.shape))\n t_tensor = t_tensor.reshape(c_tensor.data.shape)\n # logging.info('{:s} sum diff: {:}'.format(name, np.abs(t_tensor.data.cpu().numpy() - c_tensor.data).sum()))\n logging.info('{:s} var diff: {:.8f}'.format(name, (t_tensor.data.cpu().numpy() - c_tensor.data).var()))\n\n\n\ndef parse_auguments():\n parser = argparse.ArgumentParser(description='RetinaPL')\n # 23 good\n parser.add_argument('--img_path', type=str, default='Pytorch_Retina_License_Plate/test_images')\n parser.add_argument('--height', default=60, type=int, help='image height after resizing')\n parser.add_argument('--num_blocks', default=7, type=int, help='block number for otsu')\n parser.add_argument('--weights', type=str, default='./OCR_For_Car_License/saved_ckpts/ConvNet_model_best.pth.tar')\n args = parser.parse_args()\n return args\n\n\ndef char_sep(img, args):\n # cv2.imshow('img', img)\n # cv2.waitKey(0)\n # cv2.destroyWindow('img')\n resize_img = cv2.resize(img, (int(img.shape[1] * 60 / img.shape[0] / args.num_blocks) * args.num_blocks, 60))\n grey_img = cv2.cvtColor(resize_img, cv2.COLOR_BGR2GRAY)\n # cv2.imshow('img', grey_img)\n # cv2.waitKey(0)\n # cv2.destroyWindow('img')\n grey_splited_imgs = np.hsplit(grey_img, args.num_blocks)\n otsu_img = []\n for splited_img in grey_splited_imgs:\n tmp_otsu_thres, tmp_otsu_img = cv2.threshold(splited_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n otsu_img.append(tmp_otsu_img)\n\n otsu_img = np.hstack(otsu_img)\n\n black = np.sum(np.where(otsu_img == 0))\n white = np.sum(np.where(otsu_img == 255))\n if black < white:\n otsu_img = 255 - otsu_img\n\n # cv2.imshow('otsu_img', otsu_img)\n # cv2.waitKey(0)\n # cv2.destroyWindow('otsu_img')\n\n otsu_img_array = np.array(otsu_img)\n\n right_h_histogram = np.sum(otsu_img_array[:, :int(otsu_img_array.shape[1] / 4)], axis=1)\n right_his_h_thres = np.max(right_h_histogram) / 5\n # h_histogram = np.where(h_histogram > his_h_thres, 1, 0)\n # print(h_histogram)\n right_v_start, right_v_end = None, None\n for i in range(0, len(right_h_histogram)):\n if right_h_histogram[i] >= right_his_h_thres and right_v_start is None:\n right_v_start = i\n if right_h_histogram[i] < right_his_h_thres and right_v_start is not None:\n if i - right_v_start > len(right_h_histogram) / 2.5:\n right_v_end = i\n break\n else:\n right_v_start = None\n\n if i == len(right_h_histogram) - 1 and right_h_histogram[i] >= right_his_h_thres and right_v_start is not None:\n right_v_end = i\n\n left_h_histogram = np.sum(otsu_img_array[:, -int(otsu_img_array.shape[1] / 4):], axis=1)\n left_his_h_thres = np.max(right_h_histogram) / 5\n # h_histogram = np.where(h_histogram > his_h_thres, 1, 0)\n # print(h_histogram)\n left_v_start, left_v_end = None, None\n for i in range(0, len(left_h_histogram)):\n if left_h_histogram[i] >= left_his_h_thres and left_v_start is None:\n left_v_start = i\n if left_h_histogram[i] < left_his_h_thres and left_v_start is not None:\n if i - left_v_start > len(left_h_histogram) / 2.5:\n left_v_end = i\n break\n else:\n left_v_start = None\n\n if i == len(left_h_histogram) - 1 and left_h_histogram[i] >= left_his_h_thres and left_v_start is not None:\n left_v_end = i\n\n if left_v_start is None or right_v_start is None:\n return []\n\n v_start = int((left_v_start + right_v_start) / 2)\n v_end = int((left_v_end + right_v_end) / 2)\n cropped_otsu_img = otsu_img[v_start:v_end, :]\n\n v_start = max(v_start - int(cropped_otsu_img.shape[0] / 8), 0)\n v_end = min(v_end + int(cropped_otsu_img.shape[0] / 8), otsu_img_array.shape[1] - 1)\n cropped_ori_img = resize_img[v_start:v_end, :]\n\n # avoid character concatenation\n\n if np.sum(cropped_otsu_img) / 255 / (cropped_otsu_img.shape[0] * cropped_otsu_img.shape[1]) > 0.54:\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))\n cropped_otsu_img = cv2.erode(cropped_otsu_img, kernel)\n\n # cv2.imshow('cropped_img', cropped_otsu_img)\n # cv2.waitKey(0)\n # cv2.destroyWindow('cropped_img')\n\n v_histogram = np.sum(cropped_otsu_img, axis=0)\n his_v_thres = np.max(v_histogram) / 15\n chars = list()\n bin_v_histogram = [1 if val > his_v_thres else 0 for val in v_histogram]\n start_exists = False\n tmp = 0\n i = 0\n while i < len(bin_v_histogram) - 1:\n if bin_v_histogram[i + 1] > bin_v_histogram[i]:\n tmp = i\n start_exists = True\n\n if bin_v_histogram[i + 1] < bin_v_histogram[i] and (i - tmp) > (len(bin_v_histogram) / 50) and \\\n np.sum(cropped_otsu_img[:, tmp:i]) > 100 * 255:\n if i - tmp < len(bin_v_histogram) / 10:\n c_start = int(max(tmp - (len(bin_v_histogram) / 9 - i + tmp) / 2, 0))\n c_end = int(min(i + (len(bin_v_histogram) / 9 - i + tmp) / 2, len(bin_v_histogram) - 1))\n chars.append((c_start, c_end))\n else:\n chars.append((tmp, i))\n\n start_exists = False\n\n if i == len(bin_v_histogram) - 2 and bin_v_histogram[i] == 1 and start_exists is True and \\\n (i - tmp) > (len(bin_v_histogram) / 50) and \\\n np.sum(cropped_otsu_img[:, tmp:i]) > 100 * 255:\n chars.append((tmp, i))\n start_exists = False\n\n i += 1\n\n char_imgs = []\n for c in chars:\n char_imgs.append(cropped_ori_img[:, c[0]:c[1]])\n\n # for i, c in enumerate(char_imgs):\n # cv2.imshow('char%d'% i, c)\n # cv2.waitKey(0)\n\n return char_imgs\n\n#图片缩小及填充\ndef reshape_pic(img,times):\n h, w = img.shape[:2]\n origin_size = (w, h)\n target_size = (int(w // times), int(h // times))\n #缩小固定倍率\n test_img = cv2.resize(img, target_size, interpolation=cv2.INTER_AREA)\n #\n border__half_h = int((h - h // times) // 2)\n border_half_w = int((w - w // times) // 2)\n # 添加边界,边界值为[128,128,128]\n test_img = cv2.copyMakeBorder(test_img, border__half_h, border__half_h, border_half_w, border_half_w,\n cv2.BORDER_CONSTANT, value=[128, 128, 128])\n # 为避免个别像素未对齐,重新再resize回去\n output_img = cv2.resize(test_img, origin_size, interpolation=cv2.INTER_LINEAR)\n return output_img\n\n#统计出现最多的字\ndef max_count(lt):\n # 定义一个字典,用于存放元素及出现的次数\n d = {}\n # 记录最大的次数的元素\n max_key = None\n # 遍历列表,统计每个元素出现的次数,然后保存到字典中\n for i in lt:\n if i not in d:\n # 计算元素出现的次数\n count = lt.count(i)\n # 保存到字典中\n d[i] = count\n # 记录次数最大的元素\n if count > d.get(max_key, 0):\n max_key = i\n return max_key\n\nif __name__ == '__main__':\n\n args = parse_auguments()\n c = CardPredictor()\n c.train_svm()\n\n\n save_dir = ''\n\n font = ImageFont.truetype('simhei.ttf', 24)\n #add the videoCapture\n\n video_path = 'testvideo'\n\n file = 'IMG_0278.MOV'\n plate_path = file[0:-4]\n plate_number = 0\n file = os.path.join(video_path, file)\n\n cap = cv2.VideoCapture(file)\n fps = int(cap.get(cv2.CAP_PROP_FPS))\n size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),\n int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n outputfile_dir = os.path.join(save_dir, os.path.basename(file))\n outputfile_dir = outputfile_dir[:-3]\n outputfile_dir = outputfile_dir+\"avi\"\n videoWriter = cv2.VideoWriter(outputfile_dir, cv2.VideoWriter_fourcc('D', 'I', 'V', 'X'), fps, size)\n ret, frame = cap.read()\n\n # 添加字典功能\n record_count = 0\n noresult_count = 0\n record = []\n record_re = []\n final_result = []\n text = ' counting'\n for i in range(7):\n record_re.append([])\n\n while (ret):\n plate_number += 1\n # 展示一帧\n #cv2.imshow(\"capture\", frame)\n\n #添加原图缩小及填充操作以定位离摄像头太近的车牌视频(实际使用应该无需此步骤)\n times = 2.4 #测试缩小固定倍数以识\n\n frame = reshape_pic(frame,times)\n car_licenses, license_boxes = detect_car_license(frame)\n\n #判断是否能检测到车牌,当检测不到车牌累计一定次数之后刷新字典\n if len(license_boxes) == 0:\n noresult_count += 1\n if noresult_count >= 40:\n text = ' no result'\n # 刷新字典及计数\n record_count = 0\n record = []\n record_re = []\n final_result = []\n for i in range(7):\n record_re.append([])\n\n raw_img = frame\n for img, b in zip(car_licenses, license_boxes):\n r, roi, color = c.predict(img)\n if len(r) >= 7:\n save_plate_path = os.path.join(plate_path, str(plate_number))\n save_plate_path = save_plate_path + '.jpg'\n #cv2.imwrite(save_plate_path,img)\n #计数操作及将检测到的车牌结果计入字典\n record_count += 1\n noresult_count = 0\n record.append(r)\n if record_count >= 25: #字典累计次数\n # 重排序字典\n for i in range(7):\n for j in range(len(record)):\n record_re[i].append(record[j][i])\n #找到车牌每个位置出现最多的情况\n for i in range(7):\n single_result = max_count(record_re[i])\n final_result.append(single_result)\n #print(\"final_result: \", final_result)\n text1 = ''.join(final_result)\n text = text1\n #刷新字典及计数\n record_count = 0\n record = []\n record_re = []\n final_result = []\n for i in range(7):\n record_re.append([])\n # else:\n # if 'test1' in dir():\n # text = test1\n # else:\n # text = ' counting'\n else:\n #判断累计测不到结果后清空字典\n noresult_count += 1\n if noresult_count >=40:\n text = ' no result'\n # 刷新字典及计数\n record_count = 0\n record = []\n record_re = []\n final_result = []\n for i in range(7):\n record_re.append([])\n\n\n raw_img = cv2.rectangle(raw_img, (b[0], b[1]), (b[2], b[3]), color=(0, 0, 255), thickness=3,\n lineType=cv2.LINE_AA)\n cx = b[0]\n cy = b[1] - 24\n\n img_pil = Image.fromarray(raw_img)\n draw = ImageDraw.Draw(img_pil)\n draw.text((cx, cy), text, font=font, fill=(0, 0, 255, 0))\n raw_img = np.array(img_pil)\n\n videoWriter.write(raw_img)\n cv2.waitKey(fps)\n ret, frame = cap.read()\n\n cap.release()\n cv2.destroyAllWindows()\n\n\n" ]
[ [ "numpy.hstack", "numpy.hsplit", "numpy.max", "numpy.array", "numpy.where", "numpy.sum" ] ]
bgallag6/specFit
[ "60dc329b8a7f15c219245ecb2296aee8787cae93" ]
[ "specVis_old.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 5 21:05:07 2018\n\n@author: Brendan\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.optimize import curve_fit as Fit\nimport sunpy\nimport sunpy.cm\nfrom scipy import fftpack\nfrom matplotlib import cm\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom matplotlib.widgets import Button, Slider\nfrom scipy.stats import f as ff\nfrom scipy.stats.stats import pearsonr\nimport os\nimport yaml\nfrom specModel import M1, M2, m2\nimport glob\nfrom sunpy.map import Map\n\nimport argparse\nparser = argparse.ArgumentParser(description='specVis.py')\nparser.add_argument('--processed_dir', type=str, default='images/processed/demo')\n#parser.add_argument('--processed_dir', type=str, default='images/processed/20120606/1600')\nparser.add_argument('--raw_dir', type=str, default='images/processed/demo')\nargs = parser.parse_args()\n\nraw_dir = args.raw_dir\nprocessed_dir = args.processed_dir\n\ndef ax2setup():\n global title, curveSpec, ax2\n global lined, legline, lines\n # set up spectra subplot\n ax2 = plt.subplot2grid((30,31),(4, 17), colspan=13, rowspan=16)\n \n title, = ([ax2.set_title('Pixel ( , )', fontsize=fontSize)])\n ax2.set_xlabel('Frequency [Hz]', fontsize=fontSize, labelpad=5)\n ax2.set_ylabel('Power', fontsize=fontSize, labelpad=5)\n ax2.set_ylim(ylow, yhigh)\n ax2.set_xlim(xlow, xhigh) \n \n #import pdb; pdb.set_trace() \n\n curveSpec, = ax2.loglog(freqs, emptyLine, 'k', linewidth=1.5)\n #curveM1A, = ax2.loglog(freqs, emptyLine, 'r', linewidth=1.3, label='M1')\n if haveParam:\n global curveM2, curveM1, curveLorentz\n curveM2, = ax2.loglog(freqs, emptyLine, c='r', lw=1.5, label='M2')\n curveM1, = ax2.loglog(freqs, emptyLine, c='g', lw=1.5, label='M2: Power Law')\n curveLorentz, = ax2.loglog(freqs, emptyLine, c='g', ls='--', lw=1.5, label='M2: Lorentzian')\n \n leg = ax2.legend(loc='lower left')\n leg.get_frame().set_alpha(0.4)\n \n lines = [curveM2, curveM1, curveLorentz]\n lined = dict()\n \n for legline, origline in zip(leg.get_lines(), lines):\n legline.set_picker(5) \n lined[legline] = origline\n \n\ndef onpick(event):\n # on the pick event, find the orig line corresponding to the\n # legend proxy line, and toggle the visibility\n #print(event.artist)\n if event.artist in lined:\n legline = event.artist\n origline = lined[legline]\n visb = not origline.get_visible()\n origline.set_visible(visb)\n # Change the alpha on the line in the legend so we can see what lines\n # have been toggled\n if visb:\n legline.set_alpha(1.0)\n else:\n legline.set_alpha(0.2)\n fig1.canvas.draw()\n\n \n\ndef update2(val):\n params = np.zeros((len(axsliders)))\n\n for i in range(len(axsliders)):\n params[i] = fnsliders[i].val\n fnsliders[i].valtext.set_text(text[i] % params[i])\n \"\"\"\n if i == 0:\n params[i] = 10**fnsliders[i].val\n else:\n params[i] = fnsliders[i].val\n if i == 4:\n fnsliders[i].valtext.set_text(text[i] % (1./(np.exp(params[4])*60.)))\n else:\n fnsliders[i].valtext.set_text(text[i] % params[i])\n \"\"\"\n \n s = M2(freqs, *params)\n \n #l.set_ydata(s)\n curveM2.set_ydata(s)\n curveM1.set_ydata(M1(freqs, *params[:3]))\n curveLorentz.set_ydata(m2(freqs, *params[3:6]))\n\ndef reset(event):\n for slider in fnsliders:\n slider.reset()\n c_m2.set_ydata(emptyLine)\n c_l2.set_ydata(emptyLine)\n params = [slider.val for slider in fnsliders]\n s = M2(freqs, *params)\n \n #l.set_ydata(s)\n curveM2.set_ydata(s)\n \ndef update(val):\n global mask_val\n mask_val = slid_mask.val\n return mask_val\n\ndef update3(val):\n global mask_val\n global im2\n cbar2.remove()\n im2.remove()\n #mask_val = np.log(slid_mask.val)\n #slid_mask.valtext.set_text(mask_val)\n mask_val = slid_mask2.val\n mask_val = 1./(mask_val*60)\n ax4.clear()\n ax4.set_xlim(0, h_map.shape[1]-1)\n ax4.set_ylim(0, h_map.shape[0]-1) \n title4.set_text('Period: %0.2f' % mask_val)\n \n idx = (np.abs(freqs - mask_val)).argmin()\n \n #param = np.zeros((spectra.shape[0], spectra.shape[1]))\n param = np.copy(spectra[:,:,idx])\n \n pflat = np.reshape(param, (param.shape[0]*param.shape[1]))\n pNaN = pflat[~np.isnan(pflat)]\n h_min = np.percentile(pNaN,1) # set heatmap vmin to 1% of data (could lower to 0.5% or 0.1%)\n h_max = np.percentile(pNaN,99) # set heatmap vmax to 99% of data (could up to 99.5% or 99.9%)\n \n #ax1.set_title(r'%s: %i $\\AA$ | %s | $f_{masked}$ = %0.1f%s' % (date_title, wavelength, titles[p], mask_percent, '%'), y = 1.01, fontsize=17)\n im2 = ax4.imshow(param, cmap='Greys', interpolation='nearest', vmin=h_min, vmax=h_max)\n colorBar2()\n return mask_val\n\n\ndef colorBar():\n global cax1\n global cbar1\n # design colorbar for heatmaps\n divider1 = make_axes_locatable(ax1)\n cax1 = divider1.append_axes(\"right\", size=\"3%\", pad=0.07)\n cbar1 = plt.colorbar(im,cax=cax1)\n cbar1.ax.tick_params(labelsize=13, pad=3) \n plt.colorbar(im,cax=cax1)\n plt.draw()\n\ndef colorBar2():\n global cax2\n global cbar2\n # design colorbar for heatmaps\n divider2 = make_axes_locatable(ax4)\n cax2 = divider2.append_axes(\"right\", size=\"3%\", pad=0.07)\n cbar2 = plt.colorbar(im2,cax=cax2)\n #cbar.set_label('%s' % cbar_labels[1], size=15, labelpad=10)\n cbar2.ax.tick_params(labelsize=13, pad=3) \n plt.colorbar(im2,cax=cax2)\n plt.draw()\n \n\ndef plotMap(p):\n global cbar1\n global im\n cbar1.remove()\n im.remove()\n param = h_map[:,:,p]\n pflat = np.reshape(param, (param.shape[0]*param.shape[1]))\n pNaN = pflat[~np.isnan(pflat)]\n h_min = np.percentile(pNaN,1)\n h_max = np.percentile(pNaN,99)\n if p == 4:\n c_map = 'jet_r'\n else:\n c_map = 'jet'\n im = ax1.imshow(param, cmap=c_map, interpolation='nearest', vmin=h_min, \n vmax=h_max, picker=True)\n ax1.set_title(r'%s' % titles[p], y = 1.01, fontsize=17)\n colorBar()\n \ndef plotMask(p):\n global mask_val\n global cbar1\n global im\n cbar1.remove()\n im.remove() \n \n param = h_map[:,:,p]\n pflat = np.reshape(param, (param.shape[0]*param.shape[1]))\n pNaN = pflat[~np.isnan(pflat)]\n h_min = np.percentile(pNaN,1)\n h_max = np.percentile(pNaN,99)\n \n # generate p-value heatmap + masked Lorentzian component heatmaps\n dof1, dof2 = 3, 6 # degrees of freedom for model M1, M2\n p_val = ff.sf(h_map[:,:,6], dof1, dof2)\n param_mask = np.copy(param) \n param_mask[p_val > mask_val] = np.NaN\n \n # determine percentage of region masked \n count = np.count_nonzero(np.isnan(param_mask)) \n total_pix = p_val.shape[0]*p_val.shape[1]\n mask_percent = ((np.float(count))/total_pix)*100\n \n if p == 4:\n c_map = 'jet_r'\n else:\n c_map = 'jet'\n im = ax1.imshow(param_mask, cmap=c_map, interpolation='nearest', \n vmin=h_min, vmax=h_max, picker=True)\n ax1.set_title(r'%s | $f_{masked}$ = %0.1f%s' % (titles[p], mask_percent, '%'), \n y=1.01, fontsize=17)\n colorBar()\n \ndef histMask(p):\n global mask_val\n global hist0\n\n param = h_map[:,:,p]\n \n # generate p-value heatmap + masked Lorentzian component heatmaps\n dof1, dof2 = 3, 6 # degrees of freedom for model M1, M2\n p_val = ff.sf(h_map[:,:,6], dof1, dof2)\n param_mask = np.copy(param) \n param_mask[p_val > mask_val] = 0.\n param1d = np.reshape(param_mask, (param_mask.shape[0]*param_mask.shape[1]))\n pmask = param1d[param1d != 0]\n pmask = pmask[~np.isnan(pmask)]\n title.set_text('Histogram: %s | Masked' % titles[marker])\n hist0 = ax2.hist(pmask, bins=25, edgecolor='black')\n \ndef visual():\n global cbar1\n global im\n cbar1.remove()\n im.remove()\n param = vis\n h_min = np.percentile(param,1)\n h_max = np.percentile(param,99)\n im = ax1.imshow(param, cmap='sdoaia1600', interpolation='nearest', \n vmin=h_min, vmax=h_max, picker=True)\n ax1.set_title(r'%s' % titles[7], y = 1.01, fontsize=17)\n colorBar()\n\ndef hist():\n global marker\n global toggle2\n global hist0\n #ax2.clear()\n if toggle2 == 0:\n title.set_text('Histogram: %s' % titles[marker])\n pflat = np.reshape(h_map[:,:,marker], (h_map[:,:,marker].shape[0]*h_map[:,:,marker].shape[1]))\n pNaN = pflat[~np.isnan(pflat)]\n hist0 = ax2.hist(pNaN, bins=25, edgecolor='black')\n ax2.set_xlim(0.3,4)\n ax2.set_ylim(0,1000)\n elif toggle2 == 1:\n histMask(marker)\n plt.draw()\n \ndef mask():\n global toggle2\n global marker\n if toggle2 == 0:\n toggle2 = 1\n plotMask(marker)\n elif toggle2 == 1:\n toggle2 = 0\n plotMap(marker) \n return toggle2\n\n\ndef setPre():\n global toggle3\n global l, c_m2, c_l2\n global axsaveFig, axreset, axreload, bsaveFig, breset, breload\n global axsliders, fnsliders\n\n if toggle3 == 2:\n ax3.remove()\n if haveParam:\n for button in axbutton:\n button.remove()\n axslider.remove()\n visual()\n \n if toggle3 == 3: \n ax4.remove()\n cbar2.remove()\n axslider2.remove()\n if haveParam:\n for button in axbutton:\n button.remove()\n axslider.remove()\n visual()\n\n if toggle3 != 1: \n toggle3 = 1\n \n emptyLine = [0 for i in range(len(freqs))]\n \n if 'ix' not in globals():\n global ix, iy\n ix = spectra.shape[1]//2\n iy = spectra.shape[0]//2\n \n ##have so that if no param file, then maybe load middle of param bounds\n spec = np.array(spectra[iy][ix])\n \n title.set_text('Pixel (%ix , %iy): Spectra' % (ix, iy))\n\n curveSpec.set_ydata(spec)\n \n ax1.scatter(ix, iy, s=200, marker='x', c='white', linewidth=2.5)\n \n axsliders = [] \n fnsliders = []\n \n if haveParam:\n param = h_map[iy,ix,:6]\n else:\n global curveM2\n param = (np.array(M2_low) + np.array(M2_high)) / 2\n curveM2, = ax2.loglog(freqs, emptyLine, c='r', lw=1.5, label='M2')\n \n #s = M2(freqs, *h_map[iy,ix,:6])\n s = M2(freqs, *param)\n \n # make parameter sliders\n for i, M2_label in enumerate(M2_labels):\n axsliders.append(plt.axes([0.15, 0.23-(0.04*i), 0.6, 0.02]))\n fnsliders.append(Slider(axsliders[i], M2_label, M2_low[i], M2_high[i], param[i]))\n fnsliders[i].on_changed(update2)\n fnsliders[i].valtext.set_text(text[i] % param[i])\n \n curveM2.set_ydata(s)\n #l, = ax2.loglog(freqs, s, lw=1.5, color='red')\n c_m2, = ax2.loglog(freqs, emptyLine, 'b', linewidth=1.3, label='M2 - Lorentz')\n c_l2, = ax2.loglog(freqs, emptyLine, 'b--', linewidth=1.3, label='Lorentz')\n \n plt.text(0.05, 11.5, \"*Using parameters found in: '%s'\" % param_dir)\n \n axreload = plt.axes([0.83, 0.18, 0.05, 0.05])\n axsaveFig = plt.axes([0.83, 0.11, 0.05, 0.05])\n axreset = plt.axes([0.83, 0.04, 0.05, 0.05])\n \n # add callbacks to each button - linking corresponding action\n callback = Index()\n \n breload = Button(axreload, 'Reload')\n breload.on_clicked(callback.reload)\n bsaveFig = Button(axsaveFig, 'Save')\n bsaveFig.on_clicked(callback.saveFig)\n breset = Button(axreset, 'Reset')\n breset.on_clicked(reset)\n\ndef setPost():\n global toggle3, ts, ax3, title3\n global axbutton, axslider, fnbutton, slid_mask\n\n if toggle3 == 1:\n for slider in axsliders:\n slider.remove()\n\n #l.remove()\n axsaveFig.remove()\n axreset.remove()\n if toggle3 == 2:\n pass\n else: \n if toggle3 == 3:\n ax4.remove()\n cbar2.remove()\n axslider2.remove()\n if haveParam:\n for button in axbutton:\n button.remove()\n axslider.remove()\n visual()\n \n toggle3 = 2\n \n if 'ix' not in globals():\n global ix, iy\n ix = spectra.shape[1]//2\n iy = spectra.shape[0]//2\n \n ax1.scatter(ix, iy, s=200, marker='x', c='white', linewidth=2.5)\n \n ax3 = plt.subplot2grid((30,31),(21, 1), colspan=29, rowspan=8)\n title3, = ([ax3.set_title('Pixel (%ix , %iy): Timeseries' % (ix, iy), fontsize=fontSize)])\n ax3.set_xlabel('Time', fontsize=fontSize, labelpad=5)\n ax3.set_ylabel('Intensity', fontsize=fontSize, labelpad=5)\n ax3.set_xlim(timestamps[0]-0.01*t_range, timestamps[-1]+0.01*t_range) \n #ax3.set_ylim(0,1)\n \n emptyLine2 = [-1 for i in range(len(timestamps))]\n \n ts, = ax3.plot(timestamps, emptyLine2, 'k')\n \n ax2setup()\n \n timeseries = np.array(imCube[iy+1][ix+1] / exposures)\n \n ts.set_ydata(timeseries) \n ax3.set_ylim(timeseries.min()*0.9, timeseries.max()*1.1) \n \n spec = np.array(spectra[iy][ix])\n \n title.set_text('Pixel (%ix , %iy): Spectra' % (ix, iy))\n \n curveSpec.set_ydata(spec)\n \n if haveParam:\n axbutton = []\n \n # make toggle buttons to display each parameter's heatmap\n #axspace = (0.6-(0.01*len(buttons)))/len(buttons)\n for i in range(len(buttons)):\n axbutton.append(plt.axes([0.01+(0.06*i), 0.9, 0.05, 0.063]))\n axslider = plt.axes([0.64, 0.915, 0.15, 0.03])\n \n # add callbacks to each button - linking corresponding action\n callback = Index()\n \n #bFunctions = ['coeff', 'index', 'tail', 'lorentz_amp', 'lorentz_loc', 'lorentz_wid', 'fstat', 'visual', 'hist', 'mask']\n \n fnbutton = []\n \n bcount = 0\n for button in buttons:\n fnbutton.append(Button(axbutton[bcount], button))\n #fnbutton[bcount].on_clicked(eval('callback.%s' % bFunctions[bcount]))\n fnbutton[bcount].on_clicked(callback.ax_loc)\n bcount += 1\n \n slid_mask = Slider(axslider, 'Masking', 0.001, 0.1, valinit=0.005)\n slid_mask.on_changed(update)\n \n fig1.canvas.mpl_connect('button_press_event', onclick) \n\n\ndef setPower():\n global axslider2, slid_mask2, ax4\n global im2, toggle3, title4\n \n if toggle3 != 3:\n if toggle3 != 2:\n setPost()\n \n ax3.remove()\n ax2.remove()\n \n toggle3 = 3 \n \n ax4 = plt.subplot2grid((30,31),(4, 17), colspan=13, rowspan=16)\n ax4.set_xlim(0, h_map.shape[1]-1)\n ax4.set_ylim(0, h_map.shape[0]-1) \n title4, = ([ax4.set_title(r'Period: %0.2f [min]' % 4., y = 1.01, fontsize=17)])\n \n idx = (np.abs(freqs - 1./(4*60))).argmin()\n param = np.copy(spectra[:,:,idx]) # set initial heatmap to power law index \n pflat = np.reshape(param, (param.shape[0]*param.shape[1]))\n pNaN = pflat[~np.isnan(pflat)]\n h_min = np.percentile(pNaN,1) # set heatmap vmin to 1% of data (could lower to 0.5% or 0.1%)\n h_max = np.percentile(pNaN,99) # set heatmap vmax to 99% of data (could up to 99.5% or 99.9%)\n im2, = ([ax4.imshow(param, cmap='Greys', interpolation='nearest', vmin=h_min, vmax=h_max)]) \n \n global cbar2\n # design colorbar for heatmaps\n divider2 = make_axes_locatable(ax4)\n cax2 = divider2.append_axes(\"right\", size=\"3%\", pad=0.07)\n cbar2 = plt.colorbar(im2,cax=cax2)\n cbar2.ax.tick_params(labelsize=13, pad=3) \n \n axslider2 = plt.axes([0.4, 0.2, 0.3, 0.04])\n \n #slid_mask = Slider(axslider, 'Frequency', f_fit[0], f_fit[-1], valinit=(1./240))\n #slid_mask = Slider(axslider, 'Period', (1./f_fit[-1])/60., (1./f_fit[0])/60., valinit=4., valfmt='%0.2f')\n slid_mask2 = Slider(axslider2, 'Period', (1./freqs[-1])/60., 50., valinit=4., valfmt='%0.2f')\n slid_mask2.on_changed(update3)\n \n \nclass Index(object):\n ind = 0\n \n def ax_loc(self, event):\n for i in range(len(axbutton)):\n if event.inaxes == axbutton[i]:\n if i == (len(axbutton)-1):\n mask()\n elif i == (len(axbutton)-2):\n hist()\n elif i == (len(axbutton)-3):\n visual()\n else:\n global marker\n marker = i\n plotMap(marker)\n return marker \n\n def pre(self, event):\n setPre()\n \n def post(self, event):\n setPost()\n \n def power(self, event):\n setPower()\n \n def saveFig(self, event):\n print('save params')\n \n def reload(self, event):\n global fnsliders, axsliders \n global M1_low, M1_high, M2_low, M2_high\n with open('specFit_config_test.yaml', 'r') as stream:\n cfg = yaml.load(stream)\n \n M1_low = cfg['M1_low']\n M1_high = cfg['M1_high']\n M2_low = cfg['M2_low']\n M2_high = cfg['M2_high']\n \n for slider in axsliders:\n slider.remove()\n \n axsliders = []\n fnsliders = []\n \n if haveParam:\n param = h_map[iy,ix,:6]\n else:\n param = (np.array(M2_low) + np.array(M2_high)) / 2\n \n # make parameter sliders\n for i, M2_label in enumerate(M2_labels):\n axsliders.append(plt.axes([0.15, 0.23-(0.04*i), 0.6, 0.02]))\n fnsliders.append(Slider(axsliders[i], M2_label, M2_low[i], M2_high[i], param[i]))\n fnsliders[i].on_changed(update2)\n fnsliders[i].valtext.set_text(text[i] % param[i])\n \n \n\ndef specFit(s, ds):\n ## fit data to combined power law plus gaussian component model \n try:\n m1_param = Fit(M1, freqs, s, p0=M1_guess, bounds=(M1_low, M1_high), \n sigma=ds, method='dogbox')[0]\n \n except RuntimeError: print(\"Error M1 - curve_fit failed\")\n except ValueError: print(\"Error M1 - inf/NaN\")\n \n A, n, C = m1_param # unpack model parameters\n \n \n try: \n m2_param0 = Fit(M2, freqs, s, p0=M2_guess, bounds=(M2_low, M2_high), \n sigma=ds, method='dogbox', max_nfev=3000)[0]\n \n except RuntimeError: print(\"Error M2 - curve_fit failed\")\n except ValueError: print(\"Error M2 - inf/NaN\")\n\n \n #A2, n2, C2, P2, fp2, fw2 = m2_param0\n #print nlfit_gp\n \n try: \n m2_param = Fit(M2, freqs, s, p0=m2_param0, bounds=(M2_low, M2_high),\n sigma=ds, max_nfev=3000)[0] \n \n except RuntimeError: print(\"Error M2 - curve_fit failed\")\n except ValueError: print(\"Error M2 - inf/NaN\")\n \n A22, n22, C22, P22, fp22, fw22 = m2_param \n #print m2_param\n \n # create models from parameters \n m1_fit = M1(freqs, *m1_param) \n lorentz = m2(freqs, P22, fp22, fw22)\n m2_fit2 = M2(freqs, *m2_param) \n m1_fit2 = M1(freqs, A22, n22, C22) \n \n \"\"\"\n residsM1 = (s - m1_fit)\n chisqrM1 = ((residsM1/ds)**2).sum() \n \n residsM22 = (s - m2_fit2)\n chisqrM22 = ((residsM22/ds)**2).sum()\n redchisqrM22 = ((residsM22/ds)**2).sum()/float(freqs.size-6) \n \n f_test2 = ((chisqrM1-chisqrM22)/(6-3))/((chisqrM22)/(freqs.size-6))\n \n dof1, dof2 = 3, 6 # degrees of freedom for model M1, M2\n #p_val = ff.sf(f_test2, dof1, dof2)\n \n # extract the lorentzian amplitude scaling factor\n amp_scale2 = M1(np.exp(fp22), A22, n22, C22) \n \"\"\"\n \n fwhm = (1. / (np.exp(fp22+fw22) - np.exp(fp22-fw22))) / 60.\n \n pLoc = (1./np.exp(fp22))/60.\n \n #curveM1A.set_ydata(m1_fit)\n curveM2.set_ydata(m2_fit2)\n curveM1.set_ydata(m1_fit2)\n curveLorentz.set_ydata(lorentz)\n \n p_index.set_text(r'$n$ = {0:0.2f}'.format(n22))\n p_amp.set_text(r'$\\alpha$ = {0:0.2e}'.format(P22))\n p_loc.set_text(r'$\\beta$ = {0:0.1f} [min]'.format(pLoc))\n p_wid.set_text(r'$FWHM$ = {0:0.1f} [min]'.format(fwhm)) \n\n\n# select pixel in ax1\ndef onclick(event):\n #global ix, iy\n global fnsliders\n global axsliders\n ixx, iyy = event.xdata, event.ydata\n \n if event.inaxes == ax1:\n global ix, iy\n del ax1.collections[:]\n plt.draw()\n\n #print(\"location: (%fx, %fy)\" % (ixx, iyy)) \n #print(\"location: (%ix, %iy)\" % (ixx, iyy))\n ix = int(round(ixx))\n iy = int(round(iyy))\n \n #print(spectra)\n s = np.array(spectra[iy][ix])\n \n if specVis_fit == True:\n # use 3x3 pixel-box std.dev. or adhoc method for fitting uncertainties\n if spec_unc == 'stddev':\n ds = np.array(stdDev[iy][ix])\n elif spec_unc == 'adhoc':\n ds = ds0\n specFit(s, ds)\n \n # update subplots\n ax1.scatter(ix, iy, s=200, marker='x', c='white', linewidth=2.5)\n \n title.set_text('Pixel (%ix , %iy): Spectra' % (ix, iy))\n\n curveSpec.set_ydata(s)\n \n timeseries = np.array(imCube[iy+1][ix+1] / exposures)\n \n if toggle3 == 2:\n ts.set_ydata(timeseries) \n ax3.set_ylim(timeseries.min()*0.9, timeseries.max()*1.1) \n title3.set_text('Pixel (%ix , %iy): Timeseries' % (ix, iy))\n if haveParam:\n curveM2.set_ydata(M2(freqs, *h_map[iy,ix,:6]))\n curveM1.set_ydata(M1(freqs, *h_map[iy,ix,:3]))\n curveLorentz.set_ydata(m2(freqs, *h_map[iy,ix,3:6]))\n \n if toggle3 == 1:\n \n for slider in axsliders:\n slider.remove()\n \n axsliders = []\n fnsliders = []\n \n if haveParam:\n param = h_map[iy,ix,:6]\n else:\n param = (np.array(M2_low) + np.array(M2_high)) / 2\n \n # make parameter sliders\n for i, M2_label in enumerate(M2_labels):\n axsliders.append(plt.axes([0.15, 0.23-(0.04*i), 0.6, 0.02]))\n fnsliders.append(Slider(axsliders[i], M2_label, M2_low[i], M2_high[i], param[i]))\n fnsliders[i].on_changed(update2)\n fnsliders[i].valtext.set_text(text[i] % param[i])\n \n plt.text(0.05, 11.5, \"*Using parameters found in: '%s'\" % param_dir)\n \n s = M2(freqs, *param)\n #l.set_ydata(s)\n curveM2.set_ydata(s)\n curveM1.set_ydata(M1(freqs, *param[:3]))\n curveLorentz.set_ydata(m2(freqs, *param[3:6]))\n \n\n\ndef labels2int(labels):\n '''Remove tick labels with fraction.'''\n newlabels = []\n for i in range(0,len(labels)):\n if int(labels[i]) != labels[i]:\n newlabels.append('')\n else:\n newlabels.append(str(int(labels[i])))\n return newlabels\n \n\n\"\"\"\n##############################################################################\n##############################################################################\n\"\"\"\n\n#processed_dir = 'C:/Users/Brendan/Desktop/specFit/images/processed/20120606/1600'\n#raw_dir = 'C:/Users/Brendan/Desktop/specFit/images/raw/20120606/1600/fits'\n\n#print(\"Starting specVis...\", flush=True)\n\nplt.rcParams[\"font.family\"] = \"Times New Roman\"\n#plt.rcParams[\"font.size\"] = 15\nfontSize = 15\n\nwith open('specFit_config_test.yaml', 'r') as stream:\n cfg = yaml.load(stream)\n\nmmap_spectra = cfg['mmap_spectra']\nM1_low = cfg['M1_low']\nM1_high = cfg['M1_high']\nM2_low = cfg['M2_low']\nM2_high = cfg['M2_high']\nspec_unc = cfg['spec_unc']\nM1_guess = cfg['M1_guess']\nM2_guess = cfg['M2_guess']\nM2_labels = cfg['M2_labels']\nmap_titles = cfg['M2_titles']\n#processed_dir = cfg['specVis_dir']\nspecVis_fit = False\nfits = False\ntext = ['%0.2e', '%0.2f', '%0.2e', '%0.2e', '%0.2f', '%0.2f']\n\ntitles = map_titles + ['F-Statistic', 'Averaged Visual Image']\n\nbuttons = M2_labels + ['F-Stat', 'Visual', 'Hist.', 'Mask']\n\nglobal spectra\n\nif mmap_spectra == True:\n # load memory-mapped array as read-only\n spectra = np.load('%s/specCube.npy' % processed_dir, mmap_mode='r')\n #stdDev = np.load('%s/specUnc.npy' % processed_dir, mmap_mode='r')\n imCube = np.load('%s/dataCube.npy' % processed_dir, mmap_mode='r')\nelse:\n spectra = np.load('%s/specCube.npy' % processed_dir)\n #stdDev = np.load('%s/specUnc.npy' % processed_dir)\n imCube = np.load('%s/dataCube.npy' % processed_dir)\n \nvis = np.load('%s/visual.npy' % processed_dir)\n\ntimestamps = np.load('%s/timestamps.npy' % processed_dir)\nexposures = np.load('%s/exposures.npy' % processed_dir)\n\nhaveParam = False\nif os.path.isfile('%s/param.npy' % processed_dir):\n h_map = np.load('%s/param.npy' % processed_dir)\n #h_map[:,:,4] = (1./(np.exp(h_map[:,:,4]))/60.)\n haveParam = True\n param_dir = './%s/param.npy' % processed_dir\nelse:\n param_dir = './specFit_config.yaml'\n \n \nglobal marker\nglobal count\nglobal mask_val\nglobal toggle, toggle2, toggle3\nmarker = 1\ncount = 0\nmask_val = 0.005\ntoggle, toggle2, toggle3 = 0, 0, 0\n\nglobal freqs\n\n### determine frequency values that FFT will evaluate\n## use frequencies array if exists\nif os.path.isfile('%s/frequencies.npy' % processed_dir):\n freqs = np.load('%s/frequencies.npy' % processed_dir)\n\n# assign equal weights to all parts of the curve\ndf = np.log10(freqs[1:len(freqs)]) - np.log10(freqs[0:len(freqs)-1])\ndf2 = np.zeros_like(freqs)\ndf2[0:len(df)] = df\ndf2[len(df2)-1] = df2[len(df2)-2]\nds0 = df2\n\n\n# create figure with heatmap and spectra side-by-side subplots\nfig1 = plt.figure(figsize=(18,9))\n\nax1 = plt.gca()\nax1 = plt.subplot2grid((30,31),(4, 1), colspan=14, rowspan=16)\n\n\ndef getProperties(filename):\n fmap = Map(filename)\n mapDate = fmap.date.strftime('%Y-%m-%d')\n mapWave = int(fmap.wavelength.value)\n mapXScale = fmap.scale[0].value\n mapYScale = fmap.scale[1].value\n \n return mapDate, mapWave, mapXScale, mapYScale\n\n# create a list of all the fits files\nflist = sorted(glob.glob(raw_dir))\n\n#if flist[0].find('.fits') != -1:\n# date, wavelength, xscale, yscale = getProperties(flist[0])\n# fits = True\n\n\n\nax1.set_title(r'$\\AA$ | Visual Average', y = 1.01, fontsize=17)\nparam = vis \n#param = h_map[:,:,1]\nh_min = np.percentile(param,1) \nh_max = np.percentile(param,99)\nim, = ([ax1.imshow(param, cmap='sdoaia1700', interpolation='nearest', vmin=h_min, \n vmax=h_max, picker=True)])\n \n\n \n\n#import pdb; pdb.set_trace() \n\nif param.size <= 100:\n ax1.set_xticks(-0.5+np.arange(0, param.shape[0], 1), minor=True)\n ax1.set_xticks(np.arange(0, param.shape[0], 1))\n ax1.set_yticks(-0.5+np.arange(0, param.shape[0], 1), minor=True)\n ax1.set_yticks(np.arange(0, param.shape[0], 1))\n\n ax1.grid(which='minor')\n \nax1.set_xlim(-0.5, param.shape[1]-0.5)\nax1.set_ylim(-0.5, param.shape[0]-0.5) \n\n# design colorbar for heatmaps\nglobal cbar1\ndivider = make_axes_locatable(ax1)\ncax1 = divider.append_axes(\"right\", size=\"3%\", pad=0.07)\ncbar1 = plt.colorbar(im,cax=cax1)\ncbar1.ax.tick_params(labelsize=13, pad=3) \n\n# add callbacks to each button - linking corresponding action\ncallback = Index()\n\naxpre = plt.axes([0.82, 0.91, 0.045, 0.045])\naxpost = plt.axes([0.88, 0.91, 0.045, 0.045])\naxpower = plt.axes([0.94, 0.91, 0.045, 0.045])\nbpre = Button(axpre, 'Show\\nParameters')\nbpre.on_clicked(callback.pre)\nbpost = Button(axpost, 'Show\\nTimeseries')\nbpost.on_clicked(callback.post)\nbpower = Button(axpower, 'Show\\nPowermaps')\nbpower.on_clicked(callback.power)\n\nfig1.canvas.mpl_connect('button_press_event', onclick)\n\nfig1.canvas.mpl_connect('pick_event', onpick) \n\nxspan = np.log10(freqs[-1]) - np.log10(freqs[0])\nxlow = 10**(np.log10(freqs[0]) - (xspan/10))\nxhigh = 10**(np.log10(freqs[-1]) + (xspan/10))\n\nIpos = np.where(spectra>0)\nyspan = np.log10(np.percentile(spectra[Ipos], 99.9)) - np.log10(np.percentile(spectra[Ipos], 0.1))\nylow = 10**(np.log10(np.percentile(spectra[Ipos], 0.1)) - (yspan/10))\nyhigh = 10**(np.log10(np.percentile(spectra[Ipos], 99.9)) + (yspan/10))\n\nemptyLine = [0 for i in range(len(freqs))]\n\nax2setup()\n\n\n\"\"\"\n# set up spectra subplot\nax2 = plt.subplot2grid((30,31),(4, 17), colspan=13, rowspan=16)\n\ntitle, = ([ax2.set_title('Pixel ( , )', fontsize=fontSize)])\nax2.set_xlabel('Frequency [Hz]', fontsize=fontSize, labelpad=5)\nax2.set_ylabel('Power', fontsize=fontSize, labelpad=5)\nax2.set_ylim(ylow, yhigh)\nax2.set_xlim(xlow, xhigh) \n\ncurveSpec, = ax2.loglog(freqs, emptyLine, 'k', linewidth=1.5)\n#curveM1A, = ax2.loglog(freqs, emptyLine, 'r', linewidth=1.3, label='M1')\nif haveParam:\n curveM2, = ax2.loglog(freqs, emptyLine, c='r', lw=1.5, label='M2')\nif specVis_fit:\n curveM2, = ax2.loglog(freqs, emptyLine, c='purple', lw=1.5, label='M2')\n curveM1, = ax2.loglog(freqs, emptyLine, c='g', lw=1.5, label='M2: Power Law')\n curveLorentz, = ax2.loglog(freqs, emptyLine, c='g', ls='--', lw=1.5, label='M2: Lorentz')\n #ax2.axvline(x=(1./300.), color='k', ls='dashed', label='5 minutes')\n #ax2.axvline(x=(1./180.), color='k', ls='dotted', label='3 minutes') \n legend = ax2.legend(loc='lower left', prop={'size':15}, labelspacing=0.35) \n for label in legend.get_lines():\n label.set_linewidth(2.0) # the legend line width\n \n p_index, = ([ax2.text(0.010, 10**-0.5, '', fontsize=fontSize)])\n p_amp, = ([ax2.text(0.010, 10**-0.75, '', fontsize=fontSize)])\n p_loc, = ([ax2.text(0.010, 10**-1.00, '', fontsize=fontSize)])\n p_wid, = ([ax2.text(0.00635, 10**-1.25, '', fontsize=fontSize)])\n\"\"\"\n\nt_range = timestamps[-1]-timestamps[0]\n\nplt.tight_layout()\n\nplt.show()" ]
[ [ "matplotlib.pyplot.axes", "numpy.zeros_like", "numpy.exp", "numpy.where", "matplotlib.pyplot.subplot2grid", "scipy.optimize.curve_fit", "matplotlib.pyplot.gca", "matplotlib.pyplot.tight_layout", "numpy.reshape", "numpy.arange", "numpy.copy", "numpy.load", "matplotlib.pyplot.text", "matplotlib.pyplot.figure", "numpy.isnan", "numpy.log10", "numpy.array", "matplotlib.pyplot.show", "numpy.abs", "matplotlib.widgets.Button", "numpy.percentile", "matplotlib.pyplot.draw", "matplotlib.pyplot.colorbar", "matplotlib.widgets.Slider", "scipy.stats.f.sf", "numpy.float" ] ]
macarl08/esc180_coursework
[ "16f2adda1f35875b91020e72cb4180d2e45690ce" ]
[ "misc/script/civ_midspan_deflection.py" ]
[ "# civ_midspan_deflection.py\n# CIV102 Bridge Project\n\n# Fall 2021\n# Group 403\n# Group Members:\n# - Carl Ma\n# - Abdullah Fawzy\n# - Albert Zhang\n\n\n# ------------------------------ IMPORT MODULES ------------------------------ #\n\nimport math\nimport numpy as np\n\n# ------------------------------ CONSTANTS: Material Property ------------------------------ #\n\nDIM = [813,1016,1.27]\nT_STRENGTH = 30\nC_STRENGTH = 6\nSHEAR_STRENGTH = 4\nYOUNG = 4000\nPOISSON = 0.2\nCEMENT_SHEAR = 2\n\nLENGTH = 1250\n\n# ------------------------------ 4.1-4.3 Shear force ------------------------------ #\n# 4.1 Shear force causing matboard shear failure\n# 4.2 Shear force causing glue shear failure\n# 4.3 Shear force causing matboard shear buckling failure\n\ndef bmd_to_curvature(bmd, E, I):\n\tx_cord, y_cord = zip(*bmd)\n\tx_cord_curvature = list(x_cord)\n\ty_cord_curvature = list(y_cord)\n\n\tfor i in range(len(y_cord_curvature)):\n\t\ty_cord_curvature[i] /= (E*I)\n\n\treturn x_cord_curvature, y_cord_curvature\n\n\ndef get_tangential_deviation_right(x_cord_curvature, y_cord_curvature):\n\treturn np.trapz(y_cord,x_cord)\n\n\ndef get_tangential_deviation_mid(x_cord_curvature, y_cord_curvature):\n\n\tnew_x_cord = [0]\n\tnew_y_cord = [0]\n\n\tfor i in range(1, len(x_cord)):\n\t\tstart = x_cord[i-1]\n\t\tend = x_cord[i]\n\t\tif start < LENGTH/2 and end >= LENGTH/2:\n\t\t\tbreak_x = LENGTH/2\n\t\t\tslope = (y_cord[i] - y_cord[i-1]) / (end - start)\n\t\t\tconstant = y_cord[i] - slope * end\n\t\t\tbreak_y = slope * break_x + constant\n\t\t\tnew_x_cord.append(break_x)\n\t\t\tnew_y_cord.append(break_y)\n\t\t\tbreak\n\n\t\tnew_x_cord.append(x_cord[i])\n\t\tnew_y_cord.append(y_cord[i])\n\n\treturn np.trapz(new_y_cord,new_x_cord)\n\ndef get_midspan_deflection(delta_right, delta_mid):\n\treturn delta_right * 0.5 - delta_mid\n\n\n# Sample Call\n# 1.374\n" ]
[ [ "numpy.trapz" ] ]
patrjon/pyigra2
[ "437ee3c17caa9393a3464aeac0559b6323382d3c" ]
[ "pyigra2/derived.py" ]
[ "# STD-lib\n# 3rd-party\nimport numpy as np\n\n# Local\nfrom pyigra2.base import IGRABase\n\n\nclass Derived(IGRABase):\n def __init__(self, filename):\n # Init parent class\n super().__init__(filename)\n\n # Set file specific headers and parameters\n # OBS! These index values are exactly what was given in \"igra2-derived-format.txt\". However, python start index\n # with zero. This is taken care of in parent class IGRABase._set_header() and IGRABase._set_parameters.\n\n # Header name and index\n self._header_name_index = {\n \"HEADREC\": [1, 1],\n \"ID\": [2, 12],\n \"YEAR\": [14, 17],\n \"MONTH\": [19, 20],\n \"DAY\": [22, 23],\n \"HOUR\": [25, 26],\n \"RELTIME\": [28, 31],\n \"NUMLEV\": [32, 36],\n \"PW\": [38, 43],\n \"INVPRESS\": [44, 49],\n \"INVHGT\": [50, 55],\n \"INVTEMPDIF\": [56, 61],\n \"MIXPRESS\": [62, 67],\n \"MIXHGT\": [68, 73],\n \"FRZPRESS\": [74, 79],\n \"FRZHGT\": [80, 85],\n \"LCLPRESS\": [86, 91],\n \"LCLHGT\": [92, 97],\n \"LFCPRESS\": [98, 103],\n \"LFCHGT\": [104, 109],\n \"LNBPRESS\": [110, 115],\n \"LNBHGT\": [116, 121],\n \"LI\": [122, 127],\n \"SI\": [128, 133],\n \"KI\": [134, 139],\n \"TTI\": [140, 145],\n \"CAPE\": [146, 151],\n \"CIN\": [152, 157],\n }\n\n # Header units:\n # Structure: header_name: [raw_unit, converted_unit]\n self._header_units = {\n \"HEADREC\": [\"-\", \"-\"],\n \"ID\": [\"-\", \"-\"],\n \"YEAR\": [\"yyyy\", \"yyyy\"],\n \"MONTH\": [\"mm\", \"mm\"],\n \"DAY\": [\"dd\", \"dd\"],\n \"HOUR\": [\"HH\", \"HH\"],\n \"RELTIME\": [\"HHMM\", \"HHMM\"],\n \"NUMLEV\": [\"-\", \"-\"],\n \"PW\": [\"mm*100\", \"mm\"],\n \"INVPRESS\": [\"Pa\", \"Pa\"],\n \"INVHGT\": [\"m\", \"m\"],\n \"INVTEMPDIF\": [\"K*10\", \"K\"],\n \"MIXPRESS\": [\"Pa\", \"Pa\"],\n \"MIXHGT\": [\"m\", \"m\"],\n \"FRZPRESS\": [\"Pa\", \"Pa\"],\n \"FRZHGT\": [\"m\", \"m\"],\n \"LCLPRESS\": [\"Pa\", \"Pa\"],\n \"LCLHGT\": [\"m\", \"m\"],\n \"LFCPRESS\": [\"Pa\", \"Pa\"],\n \"LFCHGT\": [\"m\", \"m\"],\n \"LNBPRESS\": [\"Pa\", \"Pa\"],\n \"LNBHGT\": [\"m\", \"m\"],\n \"LI\": [\"deg C\", \"K\"],\n \"SI\": [\"deg C\", \"K\"],\n \"KI\": [\"deg C\", \"K\"],\n \"TTI\": [\"deg C\", \"K\"],\n \"CAPE\": [\"J/kg\", \"J/kg\"],\n \"CIN\": [\"J/kg\", \"J/kg\"],\n }\n\n # Parameter name and index\n self._parameters_name_index = {\n \"PRESS\": [1, 7],\n \"REPGPH\": [9, 15],\n \"CALCGPH\": [17, 23],\n \"TEMP\": [25, 31],\n \"TEMPGRAD\": [33, 39],\n \"PTEMP\": [41, 47],\n \"PTEMPGRAD\": [49, 55],\n \"VTEMP\": [57, 63],\n \"VPTEMP\": [65, 71],\n \"VAPPRESS\": [73, 79],\n \"SATVAP\": [81, 87],\n \"REPRH\": [89, 95],\n \"CALCRH\": [97, 103],\n \"RHGRAD\": [105, 111],\n \"UWND\": [113, 119],\n \"UWDGRAD\": [121, 127],\n \"VWND\": [129, 135],\n \"VWNDGRAD\": [137, 143],\n \"N\": [145, 151],\n }\n\n # Parameter units:\n # Structure: parameter_name: [raw unit, converted unit]\n self._parameter_units = {\n \"PRESS\": [\"Pa\", \"Pa\"],\n \"REPGPH\": [\"m\", \"m\"],\n \"CALCGPH\": [\"m\", \"m\"],\n \"TEMP\": [\"K * 10\", \"K\"],\n \"TEMPGRAD\": [\"(K/km) * 10\", \"K/m\"],\n \"PTEMP\": [\"K * 10\", \"K\"],\n \"PTEMPGRAD\": [\"(K/km) * 10\", \"K/m\"],\n \"VTEMP\": [\"K * 10\", \"K\"],\n \"VPTEMP\": [\"K * 10\", \"K\"],\n \"VAPPRESS\": [\"mb * 1000\", \"Pa\"],\n \"SATVAP\": [\"mb * 1000\", \"Pa\"],\n \"REPRH\": [\"% * 10\", \"%\"],\n \"CALCRH\": [\"% * 10\", \"%\"],\n \"RHGRAD\": [\"(%/km) * 10\", \"%/m\"],\n \"UWND\": [\"(m/s) * 10\", \"m/s\"],\n \"UWDGRAD\": [\"(m/s per km) * 10\", \"(m/s) / m\"],\n \"VWND\": [\"(m/s) * 10\", \"m/s\"],\n \"VWNDGRAD\": [\"(m/s per km) * 10\", \"(m/s) / m\"],\n \"N\": [\"-\", \"-\"],\n }\n\n def _convert_header(self, header, date, hour):\n \"\"\"Convert header\n\n :param header: header to convert\n :param date, date to update\n :param hour: hour to update\n :return: None\n \"\"\"\n # Create target dict\n self.converted_data[date][hour][\"header\"] = {}\n\n # Remove whitespaces:\n for header_name, header_value in header.items():\n # Remove white space\n header_value = header_value.replace(\" \", \"\")\n\n # These variables have the following definitions:\n\n # HEADREC\t\tis the header record indicator (always set to \"#\").\n\n # ID\t\tis the station identification code. See \"igra2-stations.txt\"\n # \t\tfor a complete list of stations and their names and locations.\n\n # YEAR \t\tis the year of the sounding.\n\n # MONTH \t\tis the month of the sounding.\n\n # DAY \t\tis the day of the sounding.\n\n # HOUR \t\tis the hour of the sounding (99 = missing).\n\n # RELTIME \tis the release time of the sounding (format HHMM, missing=9999).\n\n # NUMLEV \t\tis the number of levels in the sounding (i.e., the number of\n # \t\tdata records that follow).\n if header_name == \"NUMLEV\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n # New unit: -\n\n # PW \t\tis the precipitable water (mm*100) between the surface and 500 hPa.\n if header_name == \"PW\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n header_value = header_value / 100.0\n # New unit: mm\n\n # INVPRESS \tis the pressure (in Pa or mb*100) at the level of the\n # \t\twarmest temperature in the sounding. Only provided if\n # \t\tthe warmest temperature is above the surface.\n if header_name == \"INVPRESS\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n # New unit: Pa\n\n # INVHGT \t\tis the height (in meters above the surface) of the warmest\n # \t\ttemperature in the sounding. Only provided when the\n # \t\twarmest temperature is above the surface.\n if header_name == \"INVHGT\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n # New unit: m\n\n # INVTEMPDIF \tis the difference between the warmest temperature in the\n # \t\tsounding and the surface temperature (K * 10). Only provided if\n # \t\tthe warmest temperature is above the surface.\n if header_name == \"INVTEMPDIF\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n header_value = header_value / 10.0\n # New unit: K\n\n # MIXPRESS \tis the pressure (in Pa or mb * 100) at the top of the\n # \t\tmixed layer as determined using the parcel method.\n if header_name == \"MIXPRESS\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n # New unit: Pa\n\n # MIXHGT \t\tis the height (in meters above the surface) of the top of the\n # \t\tmixed layer As determined using the parcel method.\n if header_name == \"MIXHGT\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n # New unit: m\n\n # FRZPRESS \tis the pressure (in Pa or mb * 100) where the temperature\n # \t\tfirst reaches the freezing point when moving upward from\n # \t\tthe surface. Determined by interpolating linearly with respect\n # \t\tto the logarithm of pressure between adjacent reported levels.\n # \t\tNot provided if the surface temperature is below freezing.\n if header_name == \"FRZPRESS\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n # New unit: Pa\n\n # FRZHGT \t\tis the height (in meters above the surface) where the temperature\n # \t\tfirst reaches the freezing point when moving upward from the\n # \t\tsurface. Determined analogously to FRZPRESS. Not provided if the\n # \t\tsurface temperature is below freezing.\n if header_name == \"FRZHGT\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n # New unit: m\n\n # LCLPRESS \tis the pressure (in Pa or mb * 100) of the lifting condensation\n # \t\tlevel.\n if header_name == \"LCLPRESS\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n # New unit: Pa\n\n # LCLHGT \t\tis the height (in meters above the surface) of the lifting\n # \t\tcondensation level.\n if header_name == \"LCLHGT\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n # New unit: m\n\n # LFCPRESS \tis the pressure (in Pa or mb * 100) of the level of free convection.\n if header_name == \"LFCPRESS\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n # New unit: Pa\n\n # LFCHGT \t\tis the height (in meters above the surface) of the level of free\n # \t\tconvection.\n if header_name == \"LFCHGT\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n # New unit: m\n\n # LNBPRESS \tis the pressure (in Pa or mb * 100) of the level of\n # \t\tneutral buoyancy (or equilibrium level).\n if header_name == \"LNBPRESS\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n # New unit: Pa\n\n # LNBHGT \t\tis the height (in meters above the surface) of the level of\n # \t\tneutral buoyancy (or equilibrium level).\n if header_name == \"LNBHGT\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n # New unit: m\n\n # LI \t\tis the lifted index (in degrees C).\n if header_name == \"LI\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n header_value = header_value + 273.15\n # New unit: K\n\n # SI \t\tis the Showalter index (in degrees C).\n if header_name == \"SI\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n header_value = header_value + 273.15\n # New unit: K\n\n # KI \t\tis the K index (in degrees C).\n if header_name == \"KI\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n header_value = header_value + 273.15\n # New unit: K\n\n # TTI \t\tis the total totals index (in degrees C).\n if header_name == \"TTI\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n header_value = header_value + 273.15\n # New unit: K\n\n # CAPE \t\tis the convective available potential energy (in J/kg).\n if header_name == \"CAPE\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n # New unit: J/kg\n\n # CIN \t\tis the convective inhibition (in J/kg).\n if header_name == \"CIN\":\n header_value = IGRABase._missing_test(\"-99999\", header_value)\n # New unit: J/kg\n\n # Add to new header\n self.converted_data[date][hour][\"header\"][header_name] = header_value\n\n def _convert_parameters(self, parameters, date, hour):\n \"\"\"Convert data\n\n :param parameters: parameters to convert\n :param date, date to update\n :param hour: hour to update\n :return: None\n \"\"\"\n # Create target dict\n self.converted_data[date][hour][\"parameters\"] = {}\n\n for param_name, value_lst in parameters.items():\n # For every parameter do:\n\n # Convert to numpy array with dtype str\n array = np.array(value_lst, dtype=np.str)\n\n # Remove white spaces\n array = np.char.replace(array, \" \", \"\")\n\n # Convert to float due to nans\n array = array.astype(np.float)\n\n # Missing values: -99999\n array[array == -99999] = np.nan\n\n # Convert specific parameters:\n # PRESS \t\tis the reported pressure (Pa or mb * 100).\n\n # REPGPH \t\tis the reported geopotential height (meters). This value is\n # \t\toften not available at significant levels.\n\n # CALCGPH \tis the calculated geopotential height (meters). The geopotential\n # \t\theight has been estimated by applying the hydrostatic balance to\n # \t\tthe atmospheric layer between the next lower level with a\n # \t\treported geopotential height and the current level.\n\n # TEMP \t\tis the reported temperature (K * 10).\n if param_name == \"TEMP\":\n array = array / 10.0\n # New unit: K\n\n # TEMPGRAD \tis the temperature gradient between the current level and\n # \t\tthe next higher level with a temperature [(K/km) * 10, positive\n # \t\tif temperature increases with height].\n if param_name == \"TEMPGRAD\":\n array = array / 10000.0\n # New unit: K/m\n\n # PTEMP \t\tis the potential temperature (K * 10).\n if param_name == \"PTEMP\":\n array = array / 10.0\n # New unit: K\n\n # PTEMPGRAD \tis the potential temperature gradient between the current level\n # \t\tand the next higher level with a potential temperature\n # \t\t[(K/km) * 10, positive if potential temperature increases\n # \t\twith height].\n if param_name == \"PTEMPGRAD\":\n array = array / 10000.0\n # New unit: K/m\n\n # VTEMP \t\tis the virtual temperature (K * 10).\n if param_name == \"VTEMP\":\n array = array / 10.0\n # New unit: K\n\n # VPTEMP \t\tis the virtual potential temperature (K * 10).\n if param_name == \"VPTEMP\":\n array = array / 10.0\n # New unit: K\n\n # VAPPRESS \tis the vapor pressure (mb * 1000) as computed from temperature,\n # \t\tpressure, and dewpoint depression at the same level.\n if param_name == \"VAPPRESS\":\n array = array / 10.0\n # New unit: Pa\n\n # SATVAP \t\tis the saturation vapor pressure (mb * 1000) as computed from\n # \t\tpressure and temperature at the same level.\n if param_name == \"SATVAP\":\n array = array / 10.0\n # New unit: Pa\n\n # REPRH \t\tis the relative humidity (Percent * 10) as reported in the\n # \t\toriginal sounding.\n if param_name == \"REPRH\":\n array = array / 10.0\n # New unit: %\n\n # CALCRH\t\tis the relative humidity (Percent * 10) as calculated from vapor\n # \t\tpressure, saturation vapor pressure, and pressure at the same\n # \t\tlevel.\n if param_name == \"CALCRH\":\n array = array / 10.0\n # New unit: %\n\n # RHGRAD \t\tis the relative humidity gradient between the current level and\n # \t\tthe next higher usable level [(%/km) * 10, positive if relative\n # \t\thumidity increases with height].\n if param_name == \"RHGRAD\":\n array = array / 10000.0\n # New unit: %/m\n\n # UWND \t\tis the zonal wind component [(m/s) * 10] as computed from the\n # \t\treported wind speed and direction.\n if param_name == \"UWND\":\n array = array / 10.0\n # New unit: m/s\n\n # UWDGRAD \tis the vertical gradient of the zonal wind between the current\n # \t\tlevel and the next higher level with a wind observation\n # \t\t[(m/s per km) * 10, positive if zonal wind becomes more\n # \t\tpositive with height].\n if param_name == \"UWDGRAD\":\n array = array / 10000.0\n # New unit: (m/s) / m\n\n # VWND \t\tis the meridional wind component [(m/s) * 10] as computed\n # \t\tfrom the reported wind speed and direction.\n if param_name == \"VWND\":\n array = array / 10.0\n # New unit: m/s\n\n # VWNDGRAD \tis the vertical gradient of the meridional wind component\n # \t\tbetween the current level and the next higher level with a wind\n # \t\tobservation [(m/s per km) * 10, positive if the meridional\n # \t\twind becomes more positive with height].\n if param_name == \"VWNDGRAD\":\n array = array / 10000.0\n # New unit: (m/s) / m\n\n # N \t\tis the refractive index (unitless).\n\n # Add data to converted data\n self.converted_data[date][hour][\"parameters\"][param_name] = array\n" ]
[ [ "numpy.char.replace", "numpy.array" ] ]
adiso75/mlrun
[ "0da2e72a1e2aa189074bd2ec059f2bc452f349cf" ]
[ "tests/system/feature_store/test_feature_store.py" ]
[ "import os\nimport random\nimport string\nimport uuid\nfrom datetime import datetime\n\nimport fsspec\nimport pandas as pd\nimport pyarrow.parquet as pq\nimport pytest\nfrom storey import EmitAfterMaxEvent, MapClass\n\nimport mlrun\nimport mlrun.feature_store as fs\nfrom mlrun.data_types.data_types import ValueType\nfrom mlrun.datastore.sources import CSVSource, ParquetSource\nfrom mlrun.datastore.targets import (\n CSVTarget,\n NoSqlTarget,\n ParquetTarget,\n TargetTypes,\n get_default_prefix_for_target,\n)\nfrom mlrun.feature_store import Entity, FeatureSet\nfrom mlrun.feature_store.feature_set import aggregates_step\nfrom mlrun.feature_store.steps import FeaturesetValidator\nfrom mlrun.features import MinMaxValidator\nfrom tests.system.base import TestMLRunSystem\n\nfrom .data_sample import quotes, stocks, trades\n\n\nclass MyMap(MapClass):\n def __init__(self, multiplier=1, **kwargs):\n super().__init__(**kwargs)\n self._multiplier = multiplier\n\n def do(self, event):\n event[\"xx\"] = event[\"bid\"] * self._multiplier\n event[\"zz\"] = 9\n return event\n\n\ndef myfunc1(x, context=None):\n assert context is not None, \"context is none\"\n x = x.drop(columns=[\"exchange\"])\n return x\n\n\ndef _generate_random_name():\n random_name = \"\".join([random.choice(string.ascii_letters) for i in range(10)])\n return random_name\n\n\n# Marked as enterprise because of v3io mount and pipelines\[email protected]_test_if_env_not_configured\[email protected]\nclass TestFeatureStore(TestMLRunSystem):\n def custom_setup(self):\n pass\n\n def _ingest_stocks_featureset(self):\n stocks_set = fs.FeatureSet(\n \"stocks\", entities=[Entity(\"ticker\", ValueType.STRING)]\n )\n df = fs.ingest(stocks_set, stocks, infer_options=fs.InferOptions.default())\n\n self._logger.info(f\"output df:\\n{df}\")\n stocks_set[\"name\"].description = \"some name\"\n\n self._logger.info(f\"stocks spec: {stocks_set.to_yaml()}\")\n assert (\n stocks_set.spec.features[\"name\"].description == \"some name\"\n ), \"description was not set\"\n assert len(df) == len(stocks), \"dataframe size doesnt match\"\n assert stocks_set.status.stats[\"exchange\"], \"stats not created\"\n\n def _ingest_quotes_featureset(self):\n quotes_set = FeatureSet(\"stock-quotes\", entities=[Entity(\"ticker\")])\n\n flow = quotes_set.graph\n flow.to(\"MyMap\", multiplier=3).to(\n \"storey.Extend\", _fn=\"({'z': event['bid'] * 77})\"\n ).to(\"storey.Filter\", \"filter\", _fn=\"(event['bid'] > 51.92)\").to(\n FeaturesetValidator()\n )\n\n quotes_set.add_aggregation(\"asks1\", \"ask\", [\"sum\", \"max\"], \"1h\", \"10m\")\n quotes_set.add_aggregation(\"asks2\", \"ask\", [\"sum\", \"max\"], \"5h\", \"10m\")\n quotes_set.add_aggregation(\"bids\", \"bid\", [\"min\", \"max\"], \"1h\", \"10m\")\n\n df = fs.infer_metadata(\n quotes_set,\n quotes,\n entity_columns=[\"ticker\"],\n timestamp_key=\"time\",\n options=fs.InferOptions.default(),\n )\n self._logger.info(f\"quotes spec: {quotes_set.spec.to_yaml()}\")\n assert df[\"zz\"].mean() == 9, \"map didnt set the zz column properly\"\n quotes_set[\"bid\"].validator = MinMaxValidator(min=52, severity=\"info\")\n\n quotes_set.plot(\n str(self.results_path / \"pipe.png\"), rankdir=\"LR\", with_targets=True\n )\n df = fs.ingest(quotes_set, quotes, return_df=True)\n self._logger.info(f\"output df:\\n{df}\")\n assert quotes_set.status.stats.get(\"asks1_sum_1h\"), \"stats not created\"\n\n def _get_offline_vector(self, features, features_size):\n vector = fs.FeatureVector(\"myvector\", features, \"stock-quotes.xx\")\n resp = fs.get_offline_features(\n vector, entity_rows=trades, entity_timestamp_column=\"time\",\n )\n assert len(vector.spec.features) == len(\n features\n ), \"unexpected num of requested features\"\n assert (\n len(vector.status.features) == features_size\n ), \"unexpected num of returned features\"\n assert (\n len(vector.status.stats) == features_size\n ), \"unexpected num of feature stats\"\n assert vector.status.label_column == \"xx\", \"unexpected label_column name\"\n\n df = resp.to_dataframe()\n columns = trades.shape[1] + features_size - 2 # - 2 keys\n assert df.shape[1] == columns, \"unexpected num of returned df columns\"\n resp.to_parquet(str(self.results_path / \"query.parquet\"))\n\n # check simple api without join with other df\n resp = fs.get_offline_features(vector)\n df = resp.to_dataframe()\n assert df.shape[1] == features_size, \"unexpected num of returned df columns\"\n\n def _get_online_features(self, features, features_size):\n # test real-time query\n vector = fs.FeatureVector(\"my-vec\", features)\n svc = fs.get_online_feature_service(vector)\n # check non existing column\n resp = svc.get([{\"bb\": \"AAPL\"}])\n\n resp = svc.get([{\"ticker\": \"a\"}])\n assert resp[0] is None\n resp = svc.get([{\"ticker\": \"GOOG\"}, {\"ticker\": \"MSFT\"}])\n resp = svc.get([{\"ticker\": \"AAPL\"}])\n assert (\n resp[0][\"name\"] == \"Apple Inc\" and resp[0][\"exchange\"] == \"NASDAQ\"\n ), \"unexpected online result\"\n resp2 = svc.get([{\"ticker\": \"AAPL\"}], as_list=True)\n assert (\n len(resp2[0]) == features_size - 1\n ), \"unexpected online vector size\" # -1 label\n svc.close()\n\n def test_ingest_and_query(self):\n\n self._logger.debug(\"Creating stocks feature set\")\n self._ingest_stocks_featureset()\n\n self._logger.debug(\"Creating stock-quotes feature set\")\n self._ingest_quotes_featureset()\n\n self._logger.debug(\"Get offline feature vector\")\n features = [\n \"stock-quotes.bid\",\n \"stock-quotes.asks2_sum_5h\",\n \"stock-quotes.ask as mycol\",\n \"stocks.*\",\n ]\n features_size = (\n len(features) + 1 + 1\n ) # (*) returns 2 features, label adds 1 feature\n self._get_offline_vector(features, features_size)\n\n self._logger.debug(\"Get online feature vector\")\n self._get_online_features(features, features_size)\n\n def test_feature_set_db(self):\n name = \"stocks_test\"\n stocks_set = fs.FeatureSet(name, entities=[Entity(\"ticker\", ValueType.STRING)])\n fs.infer_metadata(\n stocks_set, stocks,\n )\n stocks_set.save()\n db = mlrun.get_run_db()\n\n sets = db.list_feature_sets(self.project_name, name)\n assert len(sets) == 1, \"bad number of results\"\n\n feature_set = fs.get_feature_set(name, self.project_name)\n assert feature_set.metadata.name == name, \"bad feature set response\"\n\n fs.delete_feature_set(name, self.project_name)\n sets = db.list_feature_sets(self.project_name, name)\n assert not sets, \"Feature set should be deleted\"\n\n def test_feature_vector_db(self):\n name = \"fvec-test\"\n fvec = fs.FeatureVector(name=name)\n\n db = mlrun.get_run_db()\n\n # TODO: Using to_dict due to a bug in httpdb api which will be fixed in another PR\n db.create_feature_vector(\n feature_vector=fvec.to_dict(), project=self.project_name\n )\n\n vecs = db.list_feature_vectors(self.project_name, name)\n assert len(vecs) == 1, \"bad number of results\"\n\n feature_vec = fs.get_feature_vector(name, self.project_name)\n assert feature_vec.metadata.name == name, \"bad feature set response\"\n\n fs.delete_feature_vector(name, self.project_name)\n vecs = db.list_feature_vectors(self.project_name, name)\n assert not vecs, \"Feature vector should be deleted\"\n\n def test_serverless_ingest(self):\n key = \"patient_id\"\n measurements = fs.FeatureSet(\n \"measurements\", entities=[Entity(key)], timestamp_key=\"timestamp\"\n )\n target_path = os.path.relpath(str(self.results_path / \"mycsv.csv\"))\n source = CSVSource(\n \"mycsv\", path=os.path.relpath(str(self.assets_path / \"testdata.csv\"))\n )\n targets = [CSVTarget(\"mycsv\", path=target_path)]\n if os.path.exists(target_path):\n os.remove(target_path)\n\n fs.ingest(\n measurements,\n source,\n targets,\n infer_options=fs.InferOptions.schema() + fs.InferOptions.Stats,\n run_config=fs.RunConfig(local=True),\n )\n assert os.path.exists(target_path), \"result file was not generated\"\n features = sorted(measurements.spec.features.keys())\n stats = sorted(measurements.status.stats.keys())\n print(features)\n print(stats)\n stats.remove(\"timestamp\")\n assert features == stats, \"didnt infer stats for all features\"\n\n def test_ingest_with_timestamp(self):\n key = \"patient_id\"\n measurements = fs.FeatureSet(\n \"measurements\", entities=[Entity(key)], timestamp_key=\"timestamp\"\n )\n source = CSVSource(\n \"mycsv\",\n path=os.path.relpath(str(self.assets_path / \"testdata.csv\")),\n time_field=\"timestamp\",\n )\n resp = fs.ingest(measurements, source)\n assert resp[\"timestamp\"].head(n=1)[0] == datetime.fromisoformat(\n \"2020-12-01 17:24:15.906352\"\n )\n\n def test_featureset_column_types(self):\n data = pd.DataFrame(\n {\n \"key\": [\"key1\", \"key2\"],\n \"str\": [\"my_string1\", \"my_string2\"],\n \"int\": [123456, 234567],\n \"float\": [123.456, 234.567],\n \"bool\": [True, False],\n \"timestamp\": [\n pd.Timestamp(\"1980-02-04 17:21:50.781\"),\n pd.Timestamp(\"2020-03-04 12:12:45.120\"),\n ],\n \"category\": pd.Categorical(\n [\"a\", \"c\"], categories=[\"d\", \"c\", \"b\", \"a\"], ordered=True\n ),\n }\n )\n for key in data.keys():\n verify_ingest(data, key)\n verify_ingest(data, key, infer=True)\n\n # Timedelta isn't supported in parquet\n data[\"timedelta\"] = pd.Timedelta(\"-1 days 2 min 3us\")\n\n for key in [\"key\", \"timedelta\"]:\n verify_ingest(data, key, targets=[TargetTypes.nosql])\n verify_ingest(data, key, targets=[TargetTypes.nosql], infer=True)\n\n def test_filtering_parquet_by_time(self):\n key = \"patient_id\"\n measurements = fs.FeatureSet(\n \"measurements\", entities=[Entity(key)], timestamp_key=\"timestamp\"\n )\n source = ParquetSource(\n \"myparquet\",\n path=os.path.relpath(str(self.assets_path / \"testdata.parquet\")),\n time_field=\"timestamp\",\n start_time=datetime(2020, 12, 1, 17, 33, 15),\n end_time=\"2020-12-01 17:33:16\",\n )\n\n resp = fs.ingest(measurements, source, return_df=True,)\n assert len(resp) == 10\n\n @pytest.mark.parametrize(\"key_bucketing_number\", [None, 0, 4])\n @pytest.mark.parametrize(\"partition_cols\", [None, [\"department\"]])\n @pytest.mark.parametrize(\"time_partitioning_granularity\", [None, \"day\"])\n def test_ingest_partitioned_by_key_and_time(\n self, key_bucketing_number, partition_cols, time_partitioning_granularity\n ):\n key = \"patient_id\"\n name = f\"measurements_{uuid.uuid4()}\"\n measurements = fs.FeatureSet(name, entities=[Entity(key)])\n source = CSVSource(\n \"mycsv\",\n path=os.path.relpath(str(self.assets_path / \"testdata.csv\")),\n time_field=\"timestamp\",\n )\n measurements.set_targets(\n targets=[\n ParquetTarget(\n partitioned=True,\n key_bucketing_number=key_bucketing_number,\n partition_cols=partition_cols,\n time_partitioning_granularity=time_partitioning_granularity,\n )\n ],\n with_defaults=False,\n )\n resp1 = fs.ingest(measurements, source)\n\n features = [\n f\"{name}.*\",\n ]\n vector = fs.FeatureVector(\"myvector\", features)\n resp = fs.get_offline_features(vector)\n resp2 = resp.to_dataframe()\n\n assert resp1.to_dict() == resp2.to_dict()\n\n file_system = fsspec.filesystem(\"v3io\")\n kind = TargetTypes.parquet\n path = f\"{get_default_prefix_for_target(kind)}/sets/{name}-latest\"\n path = path.format(name=name, kind=kind, project=\"system-test-project\")\n dataset = pq.ParquetDataset(path, filesystem=file_system,)\n partitions = [key for key, _ in dataset.pieces[0].partition_keys]\n\n if key_bucketing_number is None:\n expected_partitions = []\n elif key_bucketing_number == 0:\n expected_partitions = [\"igzpart_key\"]\n else:\n expected_partitions = [f\"igzpart_hash{key_bucketing_number}_key\"]\n expected_partitions += partition_cols or []\n if all(\n value is None\n for value in [\n key_bucketing_number,\n partition_cols,\n time_partitioning_granularity,\n ]\n ):\n time_partitioning_granularity = \"hour\"\n if time_partitioning_granularity:\n for unit in [\"year\", \"month\", \"day\", \"hour\"]:\n expected_partitions.append(f\"igzpart_{unit}\")\n if unit == time_partitioning_granularity:\n break\n\n assert partitions == expected_partitions\n\n resp = fs.get_offline_features(\n vector,\n start_time=datetime(2020, 12, 1, 17, 33, 15),\n end_time=datetime(2020, 12, 1, 17, 33, 16),\n entity_timestamp_column=\"timestamp\",\n )\n resp2 = resp.to_dataframe()\n assert len(resp2) == 10\n\n def test_ordered_pandas_asof_merge(self):\n targets = [ParquetTarget(), NoSqlTarget()]\n left_set, left = prepare_feature_set(\n \"left\", \"ticker\", trades, timestamp_key=\"time\", targets=targets\n )\n right_set, right = prepare_feature_set(\n \"right\", \"ticker\", quotes, timestamp_key=\"time\", targets=targets\n )\n\n features = [\"left.*\", \"right.*\"]\n feature_vector = fs.FeatureVector(\"test_fv\", features, description=\"test FV\")\n res = fs.get_offline_features(feature_vector, entity_timestamp_column=\"time\")\n res = res.to_dataframe()\n assert res.shape[0] == left.shape[0]\n\n def test_left_not_ordered_pandas_asof_merge(self):\n left = trades.sort_values(by=\"price\")\n\n left_set, left = prepare_feature_set(\n \"left\", \"ticker\", left, timestamp_key=\"time\"\n )\n right_set, right = prepare_feature_set(\n \"right\", \"ticker\", quotes, timestamp_key=\"time\"\n )\n\n features = [\"left.*\", \"right.*\"]\n feature_vector = fs.FeatureVector(\"test_fv\", features, description=\"test FV\")\n res = fs.get_offline_features(feature_vector, entity_timestamp_column=\"time\")\n res = res.to_dataframe()\n assert res.shape[0] == left.shape[0]\n\n def test_right_not_ordered_pandas_asof_merge(self):\n right = quotes.sort_values(by=\"bid\")\n\n left_set, left = prepare_feature_set(\n \"left\", \"ticker\", trades, timestamp_key=\"time\"\n )\n right_set, right = prepare_feature_set(\n \"right\", \"ticker\", right, timestamp_key=\"time\"\n )\n\n features = [\"left.*\", \"right.*\"]\n feature_vector = fs.FeatureVector(\"test_fv\", features, description=\"test FV\")\n res = fs.get_offline_features(feature_vector, entity_timestamp_column=\"time\")\n res = res.to_dataframe()\n assert res.shape[0] == left.shape[0]\n\n def test_read_csv(self):\n from storey import CSVSource, ReduceToDataFrame, build_flow\n\n csv_path = str(self.results_path / _generate_random_name() / \".csv\")\n targets = [CSVTarget(\"mycsv\", path=csv_path)]\n stocks_set = fs.FeatureSet(\n \"tests\", entities=[Entity(\"ticker\", ValueType.STRING)]\n )\n fs.ingest(\n stocks_set, stocks, infer_options=fs.InferOptions.default(), targets=targets\n )\n\n # reading csv file\n controller = build_flow([CSVSource(csv_path), ReduceToDataFrame()]).run()\n termination_result = controller.await_termination()\n\n expected = pd.DataFrame(\n {\n 0: [\"ticker\", \"MSFT\", \"GOOG\", \"AAPL\"],\n 1: [\"name\", \"Microsoft Corporation\", \"Alphabet Inc\", \"Apple Inc\"],\n 2: [\"exchange\", \"NASDAQ\", \"NASDAQ\", \"NASDAQ\"],\n }\n )\n\n assert termination_result.equals(\n expected\n ), f\"{termination_result}\\n!=\\n{expected}\"\n os.remove(csv_path)\n\n def test_multiple_entities(self):\n name = f\"measurements_{uuid.uuid4()}\"\n current_time = pd.Timestamp.now()\n data = pd.DataFrame(\n {\n \"time\": [\n current_time,\n current_time - pd.Timedelta(minutes=1),\n current_time - pd.Timedelta(minutes=2),\n current_time - pd.Timedelta(minutes=3),\n current_time - pd.Timedelta(minutes=4),\n current_time - pd.Timedelta(minutes=5),\n ],\n \"first_name\": [\"moshe\", \"yosi\", \"yosi\", \"yosi\", \"moshe\", \"yosi\"],\n \"last_name\": [\"cohen\", \"levi\", \"levi\", \"levi\", \"cohen\", \"levi\"],\n \"bid\": [2000, 10, 11, 12, 2500, 14],\n }\n )\n\n # write to kv\n data_set = fs.FeatureSet(\n name, entities=[Entity(\"first_name\"), Entity(\"last_name\")]\n )\n\n data_set.add_aggregation(\n name=\"bids\",\n column=\"bid\",\n operations=[\"sum\", \"max\"],\n windows=\"1h\",\n period=\"10m\",\n emit_policy=EmitAfterMaxEvent(1),\n )\n fs.infer_metadata(\n data_set,\n data, # source\n entity_columns=[\"first_name\", \"last_name\"],\n timestamp_key=\"time\",\n options=fs.InferOptions.default(),\n )\n\n data_set.plot(\n str(self.results_path / \"pipe.png\"), rankdir=\"LR\", with_targets=True\n )\n fs.ingest(data_set, data, return_df=True)\n\n features = [\n f\"{name}.bids_sum_1h\",\n ]\n\n vector = fs.FeatureVector(\"my-vec\", features)\n svc = fs.get_online_feature_service(vector)\n\n resp = svc.get([{\"first_name\": \"yosi\", \"last_name\": \"levi\"}])\n assert resp[0][\"bids_sum_1h\"] == 47.0\n\n svc.close()\n\n def test_offline_features_filter_non_partitioned(self):\n data = pd.DataFrame(\n {\n \"time_stamp\": [\n pd.Timestamp(\"2021-06-09 09:30:06.008\"),\n pd.Timestamp(\"2021-06-09 10:29:07.009\"),\n pd.Timestamp(\"2021-06-09 09:29:08.010\"),\n ],\n \"data\": [10, 20, 30],\n \"string\": [\"ab\", \"cd\", \"ef\"],\n }\n )\n\n data_set1 = fs.FeatureSet(\"fs1\", entities=[Entity(\"string\")])\n fs.ingest(data_set1, data, infer_options=fs.InferOptions.default())\n features = [\"fs1.*\"]\n vector = fs.FeatureVector(\"vector\", features)\n resp = fs.get_offline_features(\n vector,\n entity_timestamp_column=\"time_stamp\",\n start_time=datetime(2021, 6, 9, 9, 30),\n end_time=datetime(2021, 6, 9, 10, 30),\n )\n assert len(resp.to_dataframe()) == 2\n\n def test_unaggregated_columns(self):\n test_base_time = datetime(2020, 12, 1, 17, 33, 15)\n\n data = pd.DataFrame(\n {\n \"time\": [test_base_time, test_base_time - pd.Timedelta(minutes=1)],\n \"first_name\": [\"moshe\", \"yosi\"],\n \"last_name\": [\"cohen\", \"levi\"],\n \"bid\": [2000, 10],\n }\n )\n\n name = f\"measurements_{uuid.uuid4()}\"\n\n # write to kv\n data_set = fs.FeatureSet(name, entities=[Entity(\"first_name\")])\n\n data_set.add_aggregation(\n name=\"bids\",\n column=\"bid\",\n operations=[\"sum\", \"max\"],\n windows=\"1h\",\n period=\"10m\",\n )\n\n fs.ingest(data_set, data, return_df=True)\n\n features = [f\"{name}.bids_sum_1h\", f\"{name}.last_name\"]\n\n vector = fs.FeatureVector(\"my-vec\", features)\n svc = fs.get_online_feature_service(vector)\n\n resp = svc.get([{\"first_name\": \"moshe\"}])\n expected = {\"bids_sum_1h\": 2000.0, \"last_name\": \"cohen\"}\n assert resp[0] == expected\n svc.close()\n\n _split_graph_expected_default = pd.DataFrame(\n {\n \"time\": [\n pd.Timestamp(\"2016-05-25 13:30:00.023\"),\n pd.Timestamp(\"2016-05-25 13:30:00.048\"),\n pd.Timestamp(\"2016-05-25 13:30:00.049\"),\n pd.Timestamp(\"2016-05-25 13:30:00.072\"),\n ],\n \"ticker\": [\"GOOG\", \"GOOG\", \"AAPL\", \"GOOG\"],\n \"bid\": [720.50, 720.50, 97.99, 720.50],\n \"ask\": [720.93, 720.93, 98.01, 720.88],\n \"xx\": [2161.50, 2161.50, 293.97, 2161.50],\n \"zz\": [9, 9, 9, 9],\n \"extra\": [55478.50, 55478.50, 7545.23, 55478.50],\n }\n )\n\n _split_graph_expected_side = pd.DataFrame(\n {\n \"time\": [\n pd.Timestamp(\"2016-05-25 13:30:00.023\"),\n pd.Timestamp(\"2016-05-25 13:30:00.023\"),\n pd.Timestamp(\"2016-05-25 13:30:00.030\"),\n pd.Timestamp(\"2016-05-25 13:30:00.041\"),\n pd.Timestamp(\"2016-05-25 13:30:00.048\"),\n pd.Timestamp(\"2016-05-25 13:30:00.049\"),\n pd.Timestamp(\"2016-05-25 13:30:00.072\"),\n pd.Timestamp(\"2016-05-25 13:30:00.075\"),\n ],\n \"ticker\": [\"GOOG\", \"MSFT\", \"MSFT\", \"MSFT\", \"GOOG\", \"AAPL\", \"GOOG\", \"MSFT\"],\n \"bid\": [720.50, 51.95, 51.97, 51.99, 720.50, 97.99, 720.50, 52.01],\n \"ask\": [720.93, 51.96, 51.98, 52.00, 720.93, 98.01, 720.88, 52.03],\n \"extra2\": [\n 12248.50,\n 883.15,\n 883.49,\n 883.83,\n 12248.50,\n 1665.83,\n 12248.50,\n 884.17,\n ],\n }\n )\n\n def test_split_graph(self):\n quotes_set = fs.FeatureSet(\"stock-quotes\", entities=[fs.Entity(\"ticker\")])\n\n quotes_set.graph.to(\"MyMap\", \"somemap1\", field=\"multi1\", multiplier=3).to(\n \"storey.Extend\", _fn=\"({'extra': event['bid'] * 77})\"\n ).to(\"storey.Filter\", \"filter\", _fn=\"(event['bid'] > 70)\").to(\n FeaturesetValidator()\n )\n\n side_step_name = \"side-step\"\n quotes_set.graph.to(\n \"storey.Extend\", name=side_step_name, _fn=\"({'extra2': event['bid'] * 17})\"\n )\n with pytest.raises(mlrun.errors.MLRunPreconditionFailedError):\n fs.infer_metadata(quotes_set, quotes)\n\n non_default_target_name = \"side-target\"\n quotes_set.set_targets(\n targets=[\n CSVTarget(name=non_default_target_name, after_state=side_step_name)\n ],\n default_final_step=\"FeaturesetValidator\",\n )\n\n quotes_set.plot(with_targets=True)\n\n inf_out = fs.infer_metadata(quotes_set, quotes)\n ing_out = fs.ingest(quotes_set, quotes, return_df=True)\n\n default_file_path = quotes_set.get_target_path(TargetTypes.parquet)\n side_file_path = quotes_set.get_target_path(non_default_target_name)\n\n side_file_out = pd.read_csv(side_file_path)\n default_file_out = pd.read_parquet(default_file_path)\n self._split_graph_expected_default.set_index(\"ticker\", inplace=True)\n\n assert all(self._split_graph_expected_default == default_file_out.round(2))\n assert all(self._split_graph_expected_default == ing_out.round(2))\n assert all(self._split_graph_expected_default == inf_out.round(2))\n\n assert all(\n self._split_graph_expected_side.sort_index(axis=1)\n == side_file_out.sort_index(axis=1).round(2)\n )\n\n def test_none_value(self):\n data = pd.DataFrame(\n {\"first_name\": [\"moshe\", \"yossi\"], \"bid\": [2000, 10], \"bool\": [True, None]}\n )\n\n # write to kv\n data_set = fs.FeatureSet(\"tests2\", entities=[Entity(\"first_name\")])\n fs.ingest(data_set, data, return_df=True)\n features = [\"tests2.*\"]\n vector = fs.FeatureVector(\"my-vec\", features)\n svc = fs.get_online_feature_service(vector)\n\n resp = svc.get([{\"first_name\": \"yossi\"}])\n assert resp[0] == {\"bid\": 10, \"bool\": None}\n\n svc.close()\n\n def test_forced_columns_target(self):\n columns = [\"time\", \"ask\"]\n targets = [ParquetTarget(columns=columns)]\n quotes_set, _ = prepare_feature_set(\n \"forced-columns\", \"ticker\", quotes, timestamp_key=\"time\", targets=targets\n )\n\n df = pd.read_parquet(quotes_set.get_target_path())\n assert all(df.columns.values == columns)\n\n def test_csv_parquet_index_alignment(self):\n targets = [CSVTarget()]\n csv_align_set, _ = prepare_feature_set(\n \"csv-align\", \"ticker\", quotes, timestamp_key=\"time\", targets=targets\n )\n csv_df = csv_align_set.to_dataframe()\n\n features = [\"csv-align.*\"]\n csv_vec = fs.FeatureVector(\"csv-align-vector\", features)\n resp = fs.get_offline_features(csv_vec)\n csv_vec_df = resp.to_dataframe()\n\n targets = [ParquetTarget()]\n parquet_align_set, _ = prepare_feature_set(\n \"parquet-align\", \"ticker\", quotes, timestamp_key=\"time\", targets=targets\n )\n parquet_df = parquet_align_set.to_dataframe()\n features = [\"parquet-align.*\"]\n parquet_vec = fs.FeatureVector(\"parquet-align-vector\", features)\n resp = fs.get_offline_features(parquet_vec)\n parquet_vec_df = resp.to_dataframe()\n\n assert all(csv_df == parquet_df)\n assert all(csv_vec_df == parquet_vec_df)\n\n def test_sync_pipeline(self):\n stocks_set = fs.FeatureSet(\n \"stocks-sync\",\n entities=[Entity(\"ticker\", ValueType.STRING)],\n engine=\"pandas\",\n )\n\n stocks_set.graph.to(name=\"s1\", handler=\"myfunc1\")\n # df = fs.infer(my_set, df.head())\n df = fs.ingest(stocks_set, stocks)\n self._logger.info(f\"output df:\\n{df}\")\n\n features = list(stocks_set.spec.features.keys())\n assert len(features) == 1, \"wrong num of features\"\n assert \"exchange\" not in features, \"field was not dropped\"\n assert len(df) == len(stocks), \"dataframe size doesnt match\"\n\n def test_target_list_validation(self):\n targets = [ParquetTarget()]\n verify_target_list_fail(targets, with_defaults=True)\n\n targets = [ParquetTarget(path=\"path1\"), ParquetTarget(path=\"path2\")]\n verify_target_list_fail(targets, with_defaults=False)\n\n targets = [ParquetTarget(name=\"parquet1\"), ParquetTarget(name=\"parquet2\")]\n verify_target_list_fail(targets)\n\n targets = [\n ParquetTarget(name=\"same-name\", path=\"path1\"),\n ParquetTarget(name=\"same-name\", path=\"path2\"),\n ]\n verify_target_list_fail(targets, with_defaults=False)\n\n targets = [\n ParquetTarget(name=\"parquet1\", path=\"same-path\"),\n ParquetTarget(name=\"parquet2\", path=\"same-path\"),\n ]\n verify_target_list_fail(targets)\n\n def test_same_target_type(self):\n parquet_path1 = str(\n self.results_path / _generate_random_name() / \"par1.parquet\"\n )\n parquet_path2 = str(\n self.results_path / _generate_random_name() / \"par2.parquet\"\n )\n\n targets = [\n ParquetTarget(name=\"parquet1\", path=parquet_path1),\n ParquetTarget(name=\"parquet2\", path=parquet_path2),\n ]\n feature_set, _ = prepare_feature_set(\n \"same-target-type\", \"ticker\", quotes, timestamp_key=\"time\", targets=targets\n )\n parquet1 = pd.read_parquet(feature_set.get_target_path(name=\"parquet1\"))\n parquet2 = pd.read_parquet(feature_set.get_target_path(name=\"parquet2\"))\n\n assert all(parquet1 == quotes.set_index(\"ticker\"))\n assert all(parquet1 == parquet2)\n\n os.remove(parquet_path1)\n os.remove(parquet_path2)\n\n def test_post_aggregation_step(self):\n quotes_set = fs.FeatureSet(\"post-aggregation\", entities=[fs.Entity(\"ticker\")])\n agg_step = quotes_set.add_aggregation(\n \"asks\", \"ask\", [\"sum\", \"max\"], \"1h\", \"10m\"\n )\n agg_step.to(\"MyMap\", \"somemap1\", field=\"multi1\", multiplier=3)\n\n # Make sure the map step was added right after the aggregation step\n assert len(quotes_set.graph.states) == 2\n assert quotes_set.graph.states[aggregates_step].after is None\n assert quotes_set.graph.states[\"somemap1\"].after == [aggregates_step]\n\n def test_featureset_uri(self):\n stocks_set = fs.FeatureSet(\"stocks01\", entities=[fs.Entity(\"ticker\")])\n stocks_set.save()\n fs.ingest(stocks_set.uri, stocks)\n\n\ndef verify_target_list_fail(targets, with_defaults=None):\n feature_set = fs.FeatureSet(name=\"target-list-fail\", entities=[fs.Entity(\"ticker\")])\n with pytest.raises(mlrun.errors.MLRunInvalidArgumentError):\n if with_defaults:\n feature_set.set_targets(targets=targets, with_defaults=with_defaults)\n else:\n feature_set.set_targets(targets=targets)\n with pytest.raises(mlrun.errors.MLRunInvalidArgumentError):\n fs.ingest(feature_set, quotes, targets=targets)\n\n\ndef verify_ingest(\n base_data, keys, infer=False, targets=None, infer_options=fs.InferOptions.default()\n):\n if isinstance(keys, str):\n keys = [keys]\n feature_set = fs.FeatureSet(\"my-feature-set\")\n if infer:\n data = base_data.copy()\n fs.infer_metadata(feature_set, data, entity_columns=keys)\n else:\n data = base_data.set_index(keys=keys)\n if targets:\n feature_set.set_targets(targets=targets, with_defaults=False)\n df = fs.ingest(feature_set, data, infer_options=infer_options)\n\n assert len(df) == len(data)\n if infer:\n data.set_index(keys=keys, inplace=True)\n for idx in range(len(df)):\n assert all(df.values[idx] == data.values[idx])\n\n\ndef prepare_feature_set(\n name: str, entity: str, data: pd.DataFrame, timestamp_key=None, targets=None\n):\n df_source = mlrun.datastore.sources.DataFrameSource(data, entity, timestamp_key)\n\n feature_set = fs.FeatureSet(\n name, entities=[fs.Entity(entity)], timestamp_key=timestamp_key\n )\n feature_set.set_targets(targets=targets, with_defaults=False if targets else True)\n df = fs.ingest(feature_set, df_source, infer_options=fs.InferOptions.default())\n return feature_set, df\n" ]
[ [ "pandas.read_csv", "pandas.Categorical", "pandas.Timedelta", "pandas.DataFrame", "pandas.read_parquet", "pandas.Timestamp.now", "pandas.Timestamp" ] ]
spectre-team/spectre-divik
[ "8e5cec5bc0040eb01cf6621bfb0753886f58524b" ]
[ "test/kmeans/__init__.py" ]
[ "import numpy as np\n\ndata = np.array([\n [1, 1, 1, 1],\n [2, 4, 2, 2],\n [1.9, 4.2, 1.9, 1.9],\n [2, 2, 2, 2],\n [1.1, 0.8, 1.1, 1.1],\n [1000, 490231, -412342, -7012]\n])\n" ]
[ [ "numpy.array" ] ]
cash/dworp
[ "b7b0280183d4fa54b65bf5a3d4008bf64b7434dc" ]
[ "examples/axelrod_aurora_test1.py" ]
[ "__author__ = 'schmiac1'\n\n\"\"\"\nAurora's Attempt to quickly implement Axelrod model of...\n\nThe Dissemination of Culture: A Model with Local Convergence and Global Polarization\nRobert Axelrod\nJournal of Conflict Resolution\nVol 41, Issue 2, pp. 203 - 226\nApril 1, 1997\nhttp://journals.sagepub.com/doi/10.1177/0022002797041002001#articleCitationDownloadContainer\n\nTime spent info.\nMay 1\nBegan reading paper cited above at 5:28pm\nBased initial code on copy of the shorts.py example\nBegan editing code 5:35pm (using igraph Lattice for the graph)\n6:25pm done with initial draft. Still need to modify the observer function so we can record outcomes\nMay 3\n5:46pm looking to fix the observer\n7pm finished the observer, tested the printing of number of cultural regions, appears to work\n\"\"\"\nimport dworp\nimport igraph\nimport logging\nimport numpy as np\nimport pdb\n\n\nclass Site(dworp.Agent):\n\n #cultural_features = np.zeros(5) # there are 5 cultural features that have integer values\n # the values of the cultural features are represented by the digits 0 through 9\n # these values are initialized uniformly at random for each site\n\n def __init__(self, vertex, numfeatures=5, numtraitsper=10):\n super().__init__(vertex.index, numfeatures)\n vertex['agent'] = self\n self.vertex = vertex\n self.numtraits = numtraitsper\n\n def init(self, start_time, env):\n #self.state.fill(0)\n for i in range(0,len(self.state)):\n self.state[i] = float(np.random.randint(0,high=self.numtraits))\n\n # note to aurora: you need to modify next_state here!\n def step(self, new_time, env):\n # start by initializing next_state to the current state\n for i in range(0,len(self.state)):\n self.next_state[i] = self.state[i]\n\n neighbors = self.vertex.neighbors()\n logstring = \"\"\n if len(neighbors) > 0:\n selectedind = np.random.randint(0,len(neighbors))\n randfeatureind = np.random.randint(0,len(self.state))\n nvert = neighbors[selectedind]\n neighborstate = nvert[\"agent\"].state\n if (abs(self.state[randfeatureind]-neighborstate[randfeatureind]) < 0.001):\n # go ahead and interact\n # first compute G(s,n)\n indsdiffer = []\n for i in range(0,len(self.state)):\n if (abs(self.state[i]-neighborstate[i]) > 0.001):\n indsdiffer.append(i)\n if len(indsdiffer) > 0:\n # G(s,n) is not empty so choose one of these features at random (to harmonize)\n thischoice = np.random.randint(0,len(indsdiffer))\n self.next_state[indsdiffer[thischoice]] = neighborstate[indsdiffer[thischoice]]\n logstring = \"%sAgent %d changed trait %d to value %d like neighbor %d\" % (logstring,self.agent_id,indsdiffer[thischoice],int(neighborstate[indsdiffer[thischoice]]),nvert[\"agent\"].agent_id)\n else:\n logstring = \"%sAgent %d had no differing traits from neighbor %d\" % (logstring,self.agent_id,nvert[\"agent\"].agent_id)\n else:\n logstring = \"%sAgent %d chose not to interact with neighbor %d\" % (logstring,self.agent_id,nvert[\"agent\"].agent_id)\n else:\n logstring = \"%sAgent %d has no neighbors!\" % (logstring,self.agent_id)\n self.logger.info(\"%s\" % (logstring))\n\n @property\n def cultural_state(self):\n logstring = \"\"\n for i in range(0,len(self.state)):\n logstring = \"%s%d\" % (logstring,int(self.state[i]))\n return logstring\n\n\nclass AxelrodEnvironment(dworp.NetworkEnvironment):\n\n def __init__(self, network):\n super().__init__(1, network)\n\n def init(self, start_time):\n self.state.fill(0)\n\n def step(self, new_time, agents):\n #self.state[self.TEMP] = np.random.randint(self.MIN_TEMP, self.MAX_TEMP)\n self.logger.info(\"AxelrodEnvironment did not need to update\")\n\n\n\nclass AxelrodObserver(dworp.Observer):\n def __init__(self, printby):\n self.printby = printby\n\n def computenumregions(self, time, agents, env):\n # Method: we construct a dictionary whose keys are a features array and whose values are a list of lists of\n # contiguous agents. As we step through the entire list of agents, if that agent's features array is already in\n # the dict, then we check if is is a neighbor of any of the agents in lists. If it's a neighbor to more than one\n # list, then we merge the lists\n regiondict = dict()\n for i in range(0,len(agents)):\n curstate = tuple(agents[i].state.tolist())\n try:\n curval = regiondict[curstate]\n myneighbors = agents[i].vertex.neighbors()\n myneighborIDs = [a[\"agent\"].agent_id for a in myneighbors]\n myNset = set(myneighborIDs)\n indsIamIn = []\n for k in range(0,len(curval)):\n curlistagents = curval[k]\n curlistagentIDs = [b.agent_id for b in curlistagents]\n if not myNset.isdisjoint(curlistagentIDs):\n indsIamIn.append(k)\n # we should have a list now of indices of sublists I am in\n if len(indsIamIn) > 1: # we need to merge\n newlist = []\n mergedlist = []\n newlist.append(mergedlist)\n place = 1\n for k in range(0,len(curval)):\n if k in indsIamIn:\n mergedlist.extend(curval[k])\n else:\n #newlist[place] = curval[k]\n newlist.append(curval[k])\n place = place + 1\n mergedlist.append(agents[i])\n regiondict[curstate] = newlist\n elif len(indsIamIn) == 1: # just need to add to the right list\n thislist = curval[indsIamIn[0]]\n thislist.append(agents[i])\n else: # need to make a new list\n newlist = []\n newlist.append(agents[i])\n curval.append(newlist)\n except KeyError:\n newlist = []\n componentlist = []\n componentlist.append(agents[i])\n newlist.append(componentlist)\n regiondict[curstate] = newlist\n # when done, the count is the same as the number of element lists in the vals of the regiondict\n count = 0\n for key in regiondict.keys():\n curval = regiondict[key]\n count = count + len(curval)\n return count\n\n def step(self, time, agents, env):\n # A cultural region is defined as a set of contiguous sites with identical cultural features\n # We need to count the cultural regions at desired time-steps\n # (you may not want to do this expensive computation every time)\n if time % self.printby == 0:\n count = self.computenumregions(time, agents, env)\n print(\"{}: we have {} cultural regions\".format(time,count))\n\n def done(self, agents, env):\n print(\"Simulation over\")\n\n\n\n# if self.terminator.test(current_time, self.agents, self.env):\nclass AxelrodTerminator():\n def __init__(self, printby):\n self.printby = printby\n\n def test(self, current_time, agents, env):\n # no more changes can happen when all neighboring sites either no features in common or all features in common\n # make sure you only check this when current_time modulo printby == 0 (otherwise too much computation)\n if current_time % self.printby != 0:\n return False\n else:\n found_pair_that_can_change = False\n for i in range(0,len(agents)):\n curstate = agents[i].state\n myneighbors = agents[i].vertex.neighbors()\n for j in range(0,len(myneighbors)):\n curneivert = myneighbors[j]\n neistate = curneivert[\"agent\"].state\n # are they all the same\n #if not np.all(curstate == neistate) or np.all(curstate != neistate):\n if not (np.sum(abs(curstate - neistate)) < 0.001 or np.all(abs(curstate - neistate) > 0.001)):\n # if not (this pair has the same features) or (this pair shares no common features),\n # => this pair must have some features that are the same, but not all\n found_pair_that_can_change = True\n #pdb.set_trace()\n break\n if found_pair_that_can_change:\n break\n terminate = not found_pair_that_can_change # dont terminate if you found change could happen\n if terminate:\n print(\"Terminating simulation early at time = {} because no neighboring agents can change\".format(current_time))\n return terminate\n\n\n# class AxelrodTwoStageSimWithResult(dworp.TwoStageSimulation):\n# \"\"\"This version has a result variable\n# \"\"\"\n# logger = logging.getLogger(__name__)\n#\n# def __init__(self, agents, env, time, scheduler, observer, terminator=None):\n# super().__init__(agents, env, time, scheduler, observer, terminator, True)\n# self.numregions = 0\n\n\nlogging.basicConfig(level=logging.WARN)\n# ensuring reproducibility by setting the seed\nnp.random.seed(34756)\nxdim = 10\nydim = 10\nn_tsteps = 8000 # because we cycle through the 100 sites each time, this represents 80K events\ng = igraph.Graph.Lattice([xdim,ydim], nei=1, directed=False, circular=False)\nagents = [Site(v) for v in g.vs]\nenv = AxelrodEnvironment(g)\ntime = dworp.BasicTime(n_tsteps)\n# ensuring reproducibility by setting the seed\nscheduler = dworp.RandomOrderScheduler(np.random.RandomState(4587))\nobserver = AxelrodObserver(1000)\nterm = AxelrodTerminator(1000)\nsim = dworp.TwoStageSimulation(agents, env, time, scheduler, observer,terminator=term)\n\nsim.run()\n\nlastcount = observer.computenumregions(0,agents,env)\nprint(\"Last Count = %d\" % (lastcount))" ]
[ [ "numpy.random.RandomState", "numpy.random.seed", "numpy.random.randint" ] ]
arled-papa/marc
[ "cb94636d786e215195e914b37131277f835bcf52" ]
[ "plot_functions/mem_plot_heatmap.py" ]
[ "#!/usr/bin/env python3\n#\n# Copyright (c) 2021 Arled Papa\n# Author: Arled Papa <[email protected]>\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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\n# Choose the controller you want to plot: 1) flexran 2) 5gempower 3) altflexran\ncontroller = \"flexran\"\n# Location of the input folder according to the chosen controller\ninput_folder = \"data/{}_measurements\".format(controller)\n\n# Location of the output folder storing the generated figures\noutput_folder = \"output_plots/\"\n# The type of the measurement to plot\nmeasurement = \"Memory\"\n\n\n# Boxplot related function to manipulate the color of the boxplots\ndef set_box_color(bp, color):\n print(color)\n for box in bp['boxes']:\n # change outline color\n box.set(color='#5f9ea0', linewidth=2)\n # change fill color\n box.set(color=color)\n\n # Change color and linewidth of the whiskers\n for whisker in bp['whiskers']:\n whisker.set(color=color, linewidth=2)\n\n # Change color and linewidth of the caps\n for cap in bp['caps']:\n cap.set(color=color, linewidth=2)\n\n # Change color and linewidth of the medians\n for median in bp['medians']:\n median.set(color='black', linewidth=2)\n\n # Change the style of fliers and their fill\n for flier in bp['fliers']:\n flier.set(marker='o', color='#cd5c5c', alpha=0.1)\n\n\n# Markers used for plotting\nmarkers = ['s', 'o', 'p', 'd', 'x']\n\n# Colors used for plotting\ncolors = ['burlywood', 'darkcyan', 'olive', 'firebrick']\n\n# Figure related parameters\nfig_width = 6.9 # Convert pt to inch\ngolden_mean = (math.sqrt(5) - 1.0) / 2.0 # Aesthetic ratio\nfig_height = fig_width * golden_mean # height in inches\n\nfig = plt.figure(figsize=(fig_width, fig_height))\nax = fig.add_subplot(111)\n\n\"\"\"\nDictionary that stores the data that need to be stored: \nkey: The amount of users according to the users list\nvalue: A list of the generated Memory values for each agent in the agent list\n\"\"\"\ntoPlot = {}\n# Total number of runs\nnumber_runs = 10\n# List of users to plot\nlist_users = ['None', 10, 30, 50, 100]\n# List of agents to plot\nlist_agents = [1, 5, 10, 30, 50]\n\nfor users in list_users:\n # For each user create a list for the average Memory values for each agent\n toPlot[users] = []\n for agents in list_agents:\n # List the contains the final average Memory measurements for each agent\n results = []\n for run in range(number_runs):\n # List the contains the provisional Memory measurements for each configuration\n provisional = []\n # Open the file containing the measurements for the respective configuration\n with open(\"../{}/mem_agent_{}/Agents_{}_Users_{}_{}\".format(input_folder, agents, agents, users, run)) as fp:\n for line in fp:\n t = (line.split(\" \"))\n # Append the provisional Memory measurement to a list\n provisional.append(float(t[0].rstrip(\"\\n\\r\")))\n\n # Collect only the middle measurement points to avoid the transient phase of the measurements\n if run == 0:\n results = provisional[100:350]\n else:\n results = np.add(results, provisional[100:350])\n\n # Store in the results to plot the average of all runs\n results[:] = [element / number_runs for element in results]\n\n # Append the results in the list of agents for each user, given a 16 GB RAM convertion\n toPlot[users].append(np.mean(results) * (16000 / 100))\n\nx = np.array(range(len(list_users) + 1))\ny = np.array(range(len(list_agents) + 1))\n\n# Heatmap related parameters\nintensity = []\nfor key in toPlot:\n intensity.append(toPlot[key])\n\n# Setup the 2D grid with Numpy\nx, y = np.meshgrid(x, y)\n\ncmap = plt.get_cmap('hot')\n\nim = ax.pcolormesh(x, y, intensity, cmap=cmap)\ncb = plt.colorbar(im)\ncb.ax.tick_params(labelsize=18)\ncb.set_label('Memory Utilization [MB]', fontsize=18)\n# Xlabel\nplt.xlabel('Number of Users', fontsize=24)\n# Ylabel\nplt.ylabel('Number of Agents', fontsize=24)\nplt.tick_params(labelsize=22)\n# Tick labels\nax.set_xticklabels([0, 10, 30, 50, 100])\nax.set_yticklabels(list_agents)\n# Tick positions\nax.set_xticks([0.5, 1.5, 2.5, 3.5, 4.5])\n# Tick positions\nax.set_yticks([0.5, 1.5, 2.5, 3.5, 4.5])\nplt.tight_layout()\n# Store the figure in the correct output format according to the chosen controller\nplt.savefig(\"{}/{}_memory.pdf\".format(output_folder, controller))\nplt.show()\n" ]
[ [ "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.get_cmap", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.ylabel", "numpy.add", "numpy.mean", "matplotlib.pyplot.xlabel", "numpy.meshgrid", "matplotlib.pyplot.tick_params", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
VinulaUthsara/FYP-PrototypeV2
[ "e7b629c30c10e6042b8ff2bd68fd6c7df3d46d4b" ]
[ "test.py" ]
[ "# -*- coding: utf-8 -*-\n# @Date : 2019-07-25\n# @Author : Xinyu Gong ([email protected])\n# @Link : None\n# @Version : 0.0\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport cfg\nimport models\nfrom functions import validate\nfrom utils.utils import set_log_dir, create_logger\nfrom utils.inception_score import _init_inception\nfrom utils.fid_score import create_inception_graph, check_or_download_inception\n\nimport torch\nimport os\nimport numpy as np\nfrom tensorboardX import SummaryWriter\n\ntorch.backends.cudnn.enabled = True\ntorch.backends.cudnn.benchmark = True\n\n\ndef main():\n args = cfg.parse_args()\n torch.cuda.manual_seed(args.random_seed)\n assert args.exp_name\n assert args.load_path.endswith('.pth')\n assert os.path.exists(args.load_path)\n args.path_helper = set_log_dir('logs_eval', args.exp_name)\n logger = create_logger(args.path_helper['log_path'], phase='test')\n\n # set tf env\n _init_inception()\n inception_path = check_or_download_inception(None)\n create_inception_graph(inception_path)\n\n # import network\n gen_net = eval('models.'+args.gen_model+'.Generator')(args=args).cuda()\n\n # fid stat\n if args.dataset.lower() == 'cifar10':\n fid_stat = 'fid_stat/fid_stats_cifar10_train.npz'\n elif args.dataset.lower() == 'stl10':\n fid_stat = 'fid_stat/stl10_train_unlabeled_fid_stats_48.npz'\n else:\n raise NotImplementedError(f'no fid stat for {args.dataset.lower()}')\n assert os.path.exists(fid_stat)\n\n # initial\n fixed_z = torch.cuda.FloatTensor(np.random.normal(0, 1, (25, args.latent_dim)))\n\n # set writer\n logger.info(f'=> resuming from {args.load_path}')\n checkpoint_file = args.load_path\n assert os.path.exists(checkpoint_file)\n checkpoint = torch.load(checkpoint_file)\n\n if 'avg_gen_state_dict' in checkpoint:\n gen_net.load_state_dict(checkpoint['avg_gen_state_dict'])\n epoch = checkpoint['epoch']\n logger.info(f'=> loaded checkpoint {checkpoint_file} (epoch {epoch})')\n else:\n gen_net.load_state_dict(checkpoint)\n logger.info(f'=> loaded checkpoint {checkpoint_file}')\n\n logger.info(args)\n writer_dict = {\n 'writer': SummaryWriter(args.path_helper['log_path']),\n 'valid_global_steps': 0,\n }\n inception_score, fid_score = validate(args, fixed_z, fid_stat, gen_net, writer_dict, clean_dir=False)\n logger.info(f'Inception score: {inception_score}, FID score: {fid_score}.')\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.random.normal", "torch.cuda.manual_seed", "torch.load" ] ]
bytedance/raylink
[ "cd83a4377fede1ac645037df567010f2ddac5a69" ]
[ "raylink/algorithms/demo/policy.py" ]
[ "from .model import Model\nimport numpy as np\nimport time\n\n\ndef softmax(x):\n r\"\"\"Compute softmax values for each sets of scores in $x$.\n\n Args:\n x (numpy.ndarray): Input vector to compute softmax\n\n Returns:\n numpy.ndarray: softmax(x)\n \"\"\"\n e_x = np.exp(x - np.max(x))\n return e_x / e_x.sum()\n\n\nclass Policy(object):\n \"\"\"A basic policy class\"\"\"\n\n TYPE = 'policy'\n\n def __init__(self, obs_n, act_n):\n self.obs_n = obs_n\n self.act_n = act_n\n self.learn_step = 0\n\n def setup(self):\n \"\"\"Initialize policy model\"\"\"\n\n self.model = Model(self.obs_n, self.act_n)\n self.model.setup()\n\n def sample(self, obs):\n \"\"\"Sample actions with respect to the observation\n\n Args:\n obs (numpy.ndarray): The observation.\n\n Returns:\n np.ndarray: Sampled actions.\n \"\"\"\n\n logit = self.model.forward(obs)\n p = softmax(logit)[0]\n a = np.random.choice(self.act_n, 1, p=p)[0]\n return a\n\n def learn(self, sample):\n \"\"\"Learn with sample\n\n Args:\n sample (numpy.ndarray): Samples containing 'r'\n \"\"\"\n r = sample['r']\n r = np.transpose(r)[0]\n loss = r[0]\n params = self.model.get_params()\n grad = loss - np.random.randn(*params.shape)\n params += grad\n self.model.set_params(params)\n time.sleep(0.1)\n" ]
[ [ "numpy.max", "numpy.random.randn", "numpy.transpose", "numpy.random.choice" ] ]
dylanturpin/client
[ "fe84c4a3aed292c96912c5239e4cf1c9e4fec009" ]
[ "wandb/sklearn/__init__.py" ]
[ "from __future__ import absolute_import, division, print_function, unicode_literals\nimport wandb\nimport time\nimport itertools\nimport sklearn\nimport numpy as np\nimport scipy as sp\nfrom wandb.sklearn.utils import *\nfrom sklearn.base import clone\nfrom joblib import Parallel, delayed\nfrom sklearn import model_selection\nfrom sklearn import datasets\nfrom sklearn import metrics\nfrom sklearn.metrics import roc_curve, auc, precision_recall_curve, average_precision_score\nfrom sklearn.metrics import (brier_score_loss, precision_score, recall_score, f1_score)\nfrom sklearn.metrics import silhouette_score, silhouette_samples\nfrom sklearn.preprocessing import label_binarize\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.calibration import calibration_curve\nfrom sklearn import naive_bayes\nfrom sklearn.utils.multiclass import unique_labels, type_of_target\nfrom sklearn.calibration import CalibratedClassifierCV, calibration_curve\nfrom sklearn.linear_model import LogisticRegression\nfrom warnings import simplefilter\n# ignore all future warnings\nsimplefilter(action='ignore', category=FutureWarning)\n\nfrom wandb.plots.roc import roc\nfrom wandb.plots.precision_recall import precision_recall\n\ndef round_3(n):\n return round(n, 3)\ndef round_2(n):\n return round(n, 2)\nchart_limit = 1000\ndef get_named_labels(labels, numeric_labels):\n return np.array([labels[num_label] for num_label in numeric_labels])\n\n\ndef plot_classifier(model, X_train, X_test,\n y_train, y_test, y_pred, y_probas,\n labels, is_binary=False, model_name='Classifier',\n feature_names=None):\n \"\"\"\n Generates all sklearn classifier plots supported by W&B.\n The following plots are generated:\n feature importances, learning curve, confusion matrix, summary metrics,\n class balance plot, calibration curve, roc curve & precision recall curve.\n\n Should only be called with a fitted classifer (otherwise an error is thrown).\n\n Arguments:\n model (classifier): Takes in a fitted classifier.\n X_train (arr): Training set features.\n y_train (arr): Training set labels.\n X_test (arr): Test set features.\n y_test (arr): Test set labels.\n y_pred (arr): Test set predictions by the model passed.\n y_probas (arr): Test set predicted probabilities by the model passed.\n labels (list): Named labels for target varible (y). Makes plots easier to\n read by replacing target values with corresponding index.\n For example labels= ['dog', 'cat', 'owl'] all 0s are\n replaced by 'dog', 1s by 'cat'.\n is_binary (bool): Is the model passed a binary classifier? Defaults to False\n model_name (str): Model name. Defaults to 'Classifier'\n feature_names (list): Names for features. Makes plots easier to read by\n replacing feature indexes with corresponding names.\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_classifier(model, X_train, X_test, y_train, y_test,\n y_pred, y_probas, ['cat', 'dog'], False,\n 'RandomForest', ['barks', 'drools, 'plays_fetch', 'breed'])\n \"\"\"\n wandb.termlog('\\nPlotting %s.'%model_name)\n plot_feature_importances(model, feature_names)\n wandb.termlog('Logged feature importances.')\n plot_learning_curve(model, X_train, y_train)\n wandb.termlog('Logged learning curve.')\n plot_confusion_matrix(y_test, y_pred, labels)\n wandb.termlog('Logged confusion matrix.')\n plot_summary_metrics(model, X=X_train, y=y_train, X_test=X_test, y_test=y_test)\n wandb.termlog('Logged summary metrics.')\n plot_class_proportions(y_train, y_test, labels)\n wandb.termlog('Logged class proportions.')\n if(not isinstance(model, naive_bayes.MultinomialNB)):\n plot_calibration_curve(model, X_train, y_train, model_name)\n wandb.termlog('Logged calibration curve.')\n plot_roc(y_test, y_probas, labels)\n wandb.termlog('Logged roc curve.')\n plot_precision_recall(y_test, y_probas, labels)\n wandb.termlog('Logged precision recall curve.')\n # if is_binary:\n # plot_decision_boundaries(model, X_train, y_train)\n # wandb.termlog('Logged decision boundary plot.')\n\n\ndef plot_regressor(model, X_train, X_test, y_train, y_test, model_name='Regressor'):\n \"\"\"\n Generates all sklearn regressor plots supported by W&B.\n The following plots are generated:\n learning curve, summary metrics, residuals plot, outlier candidates.\n\n Should only be called with a fitted regressor (otherwise an error is thrown).\n\n Arguments:\n model (regressor): Takes in a fitted regressor.\n X_train (arr): Training set features.\n y_train (arr): Training set labels.\n X_test (arr): Test set features.\n y_test (arr): Test set labels.\n model_name (str): Model name. Defaults to 'Regressor'\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_regressor(reg, X_train, X_test, y_train, y_test, 'Ridge')\n \"\"\"\n wandb.termlog('\\nPlotting %s.'%model_name)\n plot_summary_metrics(model, X_train, y_train, X_test, y_test)\n wandb.termlog('Logged summary metrics.')\n plot_learning_curve(model, X_train, y_train)\n wandb.termlog('Logged learning curve.')\n plot_outlier_candidates(model, X_train, y_train)\n wandb.termlog('Logged outlier candidates.')\n plot_residuals(model, X_train, y_train)\n wandb.termlog('Logged residuals.')\n\n\ndef plot_clusterer(model, X_train, cluster_labels, labels=None, model_name='Clusterer'):\n \"\"\"\n Generates all sklearn clusterer plots supported by W&B.\n The following plots are generated:\n elbow curve, silhouette plot.\n\n Should only be called with a fitted clusterer (otherwise an error is thrown).\n\n Arguments:\n model (clusterer): Takes in a fitted clusterer.\n X_train (arr): Training set features.\n cluster_labels (list): Names for cluster labels. Makes plots easier to read\n by replacing cluster indexes with corresponding names.\n labels (list): Named labels for target varible (y). Makes plots easier to\n read by replacing target values with corresponding index.\n For example labels= ['dog', 'cat', 'owl'] all 0s are\n replaced by 'dog', 1s by 'cat'.\n model_name (str): Model name. Defaults to 'Clusterer'\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_clusterer(kmeans, X, cluster_labels, labels, 'KMeans')\n \"\"\"\n wandb.termlog('\\nPlotting %s.'%model_name)\n if isinstance(model, sklearn.cluster.KMeans):\n plot_elbow_curve(model, X_train)\n wandb.termlog('Logged elbow curve.')\n plot_silhouette(model, X_train, cluster_labels, labels=labels, kmeans=True)\n else:\n plot_silhouette(model, X_train, cluster_labels, kmeans=False)\n wandb.termlog('Logged silhouette plot.')\n\n\ndef summary_metrics(model=None, X=None, y=None, X_test=None, y_test=None):\n \"\"\"\n Calculates summary metrics (like mse, mae, r2 score) for both regression and\n classification algorithms.\n\n Called by plot_summary_metrics to visualize metrics. Please use the function\n plot_summary_metric() if you wish to visualize your summary metrics.\n \"\"\"\n if (test_missing(model=model, X=X, y=y, X_test=X_test, y_test=y_test) and\n test_types(model=model, X=X, y=y, X_test=X_test, y_test=y_test) and\n test_fitted(model)):\n y = np.asarray(y)\n y_test = np.asarray(y_test)\n metric_name=[]\n metric_value=[]\n model_name = model.__class__.__name__\n\n params = {}\n # Log model params to wandb.config\n for v in vars(model):\n if isinstance(getattr(model, v), str) \\\n or isinstance(getattr(model, v), bool) \\\n or isinstance(getattr(model, v), int) \\\n or isinstance(getattr(model, v), float):\n params[v] = getattr(model, v)\n\n # Classifier Metrics\n if sklearn.base.is_classifier(model):\n y_pred = model.predict(X_test)\n y_probas = model.predict_proba(X_test)\n\n metric_name.append(\"accuracy_score\")\n metric_value.append(round_2(sklearn.metrics.accuracy_score(y_test, y_pred)))\n metric_name.append(\"precision\")\n metric_value.append(round_2(sklearn.metrics.precision_score(y_test, y_pred, average=\"weighted\")))\n metric_name.append(\"recall\")\n metric_value.append(round_2(sklearn.metrics.recall_score(y_test, y_pred, average=\"weighted\")))\n metric_name.append(\"f1_score\")\n metric_value.append(round_2(sklearn.metrics.f1_score(y_test, y_pred, average=\"weighted\")))\n\n # Regression Metrics\n elif sklearn.base.is_regressor(model):\n y_pred = model.predict(X_test)\n\n metric_name.append(\"mae\")\n metric_value.append(round_2(sklearn.metrics.mean_absolute_error(y_test, y_pred)))\n metric_name.append(\"mse\")\n metric_value.append(round_2(sklearn.metrics.mean_squared_error(y_test, y_pred)))\n metric_name.append(\"r2_score\")\n metric_value.append(round_2(sklearn.metrics.r2_score(y_test, y_pred)))\n\n return wandb.visualize(\n 'wandb/metrics/v1', wandb.Table(\n columns=['metric_name', 'metric_value', 'model_name'],\n data= [\n [metric_name[i], metric_value[i], model_name] for i in range(len(metric_name))\n ]\n ))\n\n\ndef plot_summary_metrics(model=None, X=None, y=None, X_test=None, y_test=None):\n \"\"\"\n Logs the charts generated by summary_metrics in wandb.\n\n Should only be called with a fitted model (otherwise an error is thrown).\n\n Arguments:\n model (clf or reg): Takes in a fitted regressor or classifier.\n X (arr): Training set features.\n y (arr): Training set labels.\n X_test (arr): Test set features.\n y_test (arr): Test set labels.\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_summary_metrics(model, X_train, X_test, y_train, y_test)\n \"\"\"\n wandb.log({'summary_metrics': summary_metrics(model, X, y, X_test, y_test)})\n\n\n\ndef learning_curve(model, X, y, cv=None,\n shuffle=False, random_state=None,\n train_sizes=None, n_jobs=1, scoring=None):\n \"\"\"\n Trains model on datasets of varying lengths and generates a plot of\n scores vs training sizes for both training and test sets.\n\n Called by plot_learning_curve to visualize learning curve. Please use the function\n plot_learning_curve() if you wish to visualize your learning curves.\n\n \"\"\"\n if train_sizes is None:\n train_sizes = np.linspace(.1, 1.0, 5)\n if (test_missing(model=model, X=X, y=y) and\n test_types(model=model, X=X, y=y)):\n y = np.asarray(y)\n train_sizes, train_scores, test_scores = model_selection.learning_curve(\n model, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes,\n scoring=scoring, shuffle=shuffle, random_state=random_state)\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n\n def learning_curve_table(train, test, trainsize):\n data=[]\n for i in range(len(train)):\n if i >= chart_limit/2:\n wandb.termwarn(\"wandb uses only the first %d datapoints to create the plots.\"% wandb.Table.MAX_ROWS)\n break\n train_set = [\"train\", round(train[i],2), trainsize[i]]\n test_set = [\"test\", round(test[i],2), trainsize[i]]\n data.append(train_set)\n data.append(test_set)\n return wandb.visualize(\n 'wandb/learning_curve/v1', wandb.Table(\n columns=['dataset', 'score', 'train_size'],\n data=data\n ))\n\n return learning_curve_table(train_scores_mean, test_scores_mean, train_sizes)\n\n\ndef plot_learning_curve(model=None, X=None, y=None, cv=None,\n shuffle=False, random_state=None,\n train_sizes=None, n_jobs=1, scoring=None):\n \"\"\"\n Logs the plots generated by learning_curve() to wandb.\n Please note this function fits the model to datasets of varying sizes when called.\n\n Arguments:\n model (clf or reg): Takes in a fitted regressor or classifier.\n X (arr): Dataset features.\n y (arr): Dataset labels.\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_learning_curve(model, X, y)\n \"\"\"\n wandb.log({'learning_curve': learning_curve(model, X, y, cv, shuffle,\n random_state, train_sizes, n_jobs, scoring)})\n\n\ndef plot_roc(y_true=None, y_probas=None, labels=None,\n plot_micro=True, plot_macro=True, classes_to_plot=None):\n \"\"\"\n Logs the plots generated by roc() to wandb.\n\n Arguments:\n y_true (arr): Test set labels.\n y_probas (arr): Test set predicted probabilities.\n labels (list): Named labels for target varible (y). Makes plots easier to\n read by replacing target values with corresponding index.\n For example labels= ['dog', 'cat', 'owl'] all 0s are\n replaced by 'dog', 1s by 'cat'.\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_roc(y_true, y_probas, labels)\n \"\"\"\n wandb.log({'roc': roc(y_true, y_probas, labels, plot_micro, plot_macro, classes_to_plot)})\n\n\n\ndef confusion_matrix(y_true=None, y_pred=None, labels=None, true_labels=None,\n pred_labels=None, title=None, normalize=False,\n hide_zeros=False, hide_counts=False):\n \"\"\"\n Computes the confusion matrix to evaluate the accuracy of a classification.\n\n Called by plot_confusion_matrix to visualize roc curves. Please use the function\n plot_confusion_matrix() if you wish to visualize your confusion matrix.\n \"\"\"\n y_true = np.asarray(y_true)\n y_pred = np.asarray(y_pred)\n\n if (test_missing(y_true=y_true, y_pred=y_pred) and\n test_types(y_true=y_true, y_pred=y_pred)):\n cm = metrics.confusion_matrix(y_true, y_pred)\n if labels is None:\n classes = unique_labels(y_true, y_pred)\n else:\n classes = np.asarray(labels)\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n cm = np.around(cm, decimals=2)\n cm[np.isnan(cm)] = 0.0\n\n if true_labels is None:\n true_classes = classes\n else:\n validate_labels(classes, true_labels, \"true_labels\")\n\n true_label_indexes = np.in1d(classes, true_labels)\n\n true_classes = classes[true_label_indexes]\n cm = cm[true_label_indexes]\n\n if pred_labels is None:\n pred_classes = classes\n else:\n validate_labels(classes, pred_labels, \"pred_labels\")\n\n pred_label_indexes = np.in1d(classes, pred_labels)\n\n pred_classes = classes[pred_label_indexes]\n cm = cm[:, pred_label_indexes]\n\n def confusion_matrix_table(cm, pred_classes, true_classes):\n data=[]\n count = 0\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n if labels is not None and (isinstance(pred_classes[i], int)\n or isinstance(pred_classes[0], np.integer)):\n pred_dict = labels[pred_classes[i]]\n true_dict = labels[true_classes[j]]\n else:\n pred_dict = pred_classes[i]\n true_dict = true_classes[j]\n data.append([pred_dict, true_dict, cm[i,j]])\n count+=1\n if count >= chart_limit:\n wandb.termwarn(\"wandb uses only the first %d datapoints to create the plots.\"% wandb.Table.MAX_ROWS)\n break\n return wandb.visualize(\n 'wandb/confusion_matrix/v1', wandb.Table(\n columns=['Predicted', 'Actual', 'Count'],\n data=data\n ))\n\n return confusion_matrix_table(cm, pred_classes, true_classes)\n\n\ndef plot_confusion_matrix(y_true=None, y_pred=None, labels=None, true_labels=None,\n pred_labels=None, title=None, normalize=False,\n hide_zeros=False, hide_counts=False):\n \"\"\"\n Logs the plots generated by confusion_matrix() to wandb.\n\n Arguments:\n y_true (arr): Test set labels.\n y_probas (arr): Test set predicted probabilities.\n labels (list): Named labels for target varible (y). Makes plots easier to\n read by replacing target values with corresponding index.\n For example labels= ['dog', 'cat', 'owl'] all 0s are\n replaced by 'dog', 1s by 'cat'.\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_confusion_matrix(y_true, y_probas, labels)\n \"\"\"\n wandb.log({'confusion_matrix': confusion_matrix(y_true, y_pred, labels, true_labels,\n pred_labels, title, normalize,\n hide_zeros, hide_counts)})\n\n\ndef plot_precision_recall(y_true=None, y_probas=None, labels=None,\n plot_micro=True, classes_to_plot=None):\n \"\"\"\n Logs the plots generated by precision_recall() to wandb.\n\n Arguments:\n y_true (arr): Test set labels.\n y_probas (arr): Test set predicted probabilities.\n labels (list): Named labels for target varible (y). Makes plots easier to\n read by replacing target values with corresponding index.\n For example labels= ['dog', 'cat', 'owl'] all 0s are\n replaced by 'dog', 1s by 'cat'.\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_precision_recall(y_true, y_probas, labels)\n \"\"\"\n wandb.log({'precision_recall':precision_recall(y_true, y_probas,\n labels, plot_micro, classes_to_plot)})\n\n\ndef plot_feature_importances(model=None, feature_names=None,\n title='Feature Importance', max_num_features=50):\n \"\"\"\n Evaluates & plots the importance of each feature for the classification task.\n\n Should only be called with a fitted classifer (otherwise an error is thrown).\n Only works with classifiers that have a feature_importances_ attribute, like trees.\n\n Arguments:\n model (clf): Takes in a fitted classifier.\n feature_names (list): Names for features. Makes plots easier to read by\n replacing feature indexes with corresponding names.\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_feature_importances(model, ['width', 'height, 'length'])\n \"\"\"\n attributes_to_check = ['feature_importances_', 'coef_']\n def get_attributes_as_formatted_string():\n result = ''\n for index in range(len(attributes_to_check) - 1):\n if result == '':\n result = attributes_to_check[index]\n else:\n result = \", \".join([result, attributes_to_check[index]])\n\n return \" or \".join([result, attributes_to_check[-1]])\n\n def check_for_attribute_on(model):\n for each in attributes_to_check:\n if hasattr(model, each):\n return each\n return None\n\n found_attribute = check_for_attribute_on(model)\n if found_attribute is None:\n wandb.termwarn(\"%s attribute not in classifier. Cannot plot feature importances.\" % get_attributes_as_formatted_string())\n return\n\n if (test_missing(model=model) and test_types(model=model) and\n test_fitted(model)):\n feature_names = np.asarray(feature_names)\n if found_attribute == 'feature_importances_':\n importances = model.feature_importances_\n if found_attribute == 'coef_': # ElasticNet or ElasticNetCV like models\n importances = model.coef_\n\n indices = np.argsort(importances)[::-1]\n\n if feature_names is None:\n feature_names = indices\n else:\n feature_names = np.array(feature_names)[indices]\n\n max_num_features = min(max_num_features, len(importances))\n\n # Draw a stem plot with the influence for each instance\n # format:\n # x = feature_names[:max_num_features]\n # y = importances[indices][:max_num_features]\n def feature_importances_table(feature_names, importances):\n return wandb.visualize(\n 'wandb/feature_importances/v1', wandb.Table(\n columns=['feature_names', 'importances'],\n data=[\n [feature_names[i], importances[i]] for i in range(len(feature_names))\n ]\n ))\n wandb.log({'feature_importances': feature_importances_table(feature_names, importances)})\n return feature_importances_table(feature_names, importances)\n\ndef plot_elbow_curve(clusterer=None, X=None, cluster_ranges=None, n_jobs=1,\n show_cluster_time=True):\n \"\"\"\n Measures and plots the percentage of variance explained as a function of the\n number of clusters, along with training times. Useful in picking the\n optimal number of clusters.\n\n Should only be called with a fitted clusterer (otherwise an error is thrown).\n Please note this function fits the model on the training set when called.\n\n Arguments:\n model (clusterer): Takes in a fitted clusterer.\n X (arr): Training set features.\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_elbow_curve(model, X_train)\n \"\"\"\n if not hasattr(clusterer, 'n_clusters'):\n wandb.termlog('n_clusters attribute not in classifier. Cannot plot elbow method.')\n return\n if (test_missing(clusterer=clusterer) and test_types(clusterer=clusterer) and\n test_fitted(clusterer)):\n if cluster_ranges is None:\n cluster_ranges = range(1, 10, 2)\n else:\n cluster_ranges = sorted(cluster_ranges)\n\n if not hasattr(clusterer, 'n_clusters'):\n raise TypeError('\"n_clusters\" attribute not in classifier. '\n 'Cannot plot elbow method.')\n\n def _clone_and_score_clusterer(clusterer, X, n_clusters):\n start = time.time()\n clusterer = clone(clusterer)\n setattr(clusterer, 'n_clusters', n_clusters)\n return clusterer.fit(X).score(X), time.time() - start\n\n tuples = Parallel(n_jobs=n_jobs)(delayed(_clone_and_score_clusterer)\n (clusterer, X, i) for i in cluster_ranges)\n clfs, times = zip(*tuples)\n\n clfs = np.absolute(clfs)\n\n # Elbow curve\n # ax.plot(cluster_ranges, np.absolute(clfs), 'b*-')\n\n # Cluster time\n # ax2.plot(cluster_ranges, times, ':', alpha=0.75, color=ax2_color)\n\n # format:\n # cluster_ranges - x axis\n # errors = clfs - y axis\n # clustering_time = times - y axis2\n\n def elbow_curve(cluster_ranges, clfs, times):\n return wandb.visualize(\n 'wandb/elbow/v1',\n wandb.Table(\n columns=['cluster_ranges', 'errors', 'clustering_time'],\n data=[\n [cluster_ranges[i], clfs[i], times[i]] for i in range(len(cluster_ranges))\n ]\n ))\n wandb.log({'elbow_curve': elbow_curve(cluster_ranges, clfs, times)})\n return\n\n\ndef plot_silhouette(clusterer=None, X=None, cluster_labels=None, labels=None,\n metric='euclidean', kmeans=True):\n \"\"\"\n Measures & plots a measure of how close each point in one cluster is to points\n in the neighboring clusters. Silhouette coefficients near +1 indicate that\n the sample is far away from the neighboring clusters. A value of 0 indicates\n that the sample is on or very close to the decision boundary between two\n neighboring clusters and negative values indicate that those samples might\n have been assigned to the wrong cluster.\n\n Should only be called with a fitted clusterer (otherwise an error is thrown).\n Please note this function fits the model on the training set when called.\n\n Arguments:\n model (clusterer): Takes in a fitted clusterer.\n X (arr): Training set features.\n cluster_labels (list): Names for cluster labels. Makes plots easier to read\n by replacing cluster indexes with corresponding names.\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_silhouette(model, X_train, ['spam', 'not spam'])\n \"\"\"\n if (test_missing(clusterer=clusterer) and test_types(clusterer=clusterer) and\n test_fitted(clusterer)):\n if isinstance(X, (pd.DataFrame)):\n X = X.values\n # Run clusterer for n_clusters in range(len(cluster_ranges), get cluster labels\n # TODO - keep/delete once we decide if we should train clusterers\n # or ask for trained models\n # clusterer.set_params(n_clusters=n_clusters, random_state=42)\n # cluster_labels = clusterer.fit_predict(X)\n cluster_labels = np.asarray(cluster_labels)\n labels = np.asarray(labels)\n\n le = LabelEncoder()\n cluster_labels_encoded = le.fit_transform(cluster_labels)\n n_clusters = len(np.unique(cluster_labels))\n\n # The silhouette_score gives the average value for all the samples.\n # This gives a perspective into the density and separation of the formed\n # clusters\n silhouette_avg = silhouette_score(X, cluster_labels, metric=metric)\n\n # Compute the silhouette scores for each sample\n sample_silhouette_values = silhouette_samples(X, cluster_labels,\n metric=metric)\n\n # Plot 1: Silhouette Score\n # y = np.arange(y_lower, y_upper)[]\n # x1 = 0\n # x2 = ith_cluster_silhouette_values[]\n # color = le.classes_[n_clusters]\n # rule_line = silhouette_avg\n\n y_sil = []\n x_sil = []\n color_sil = []\n\n y_lower = 10\n count = 0\n for i in range(n_clusters):\n # Aggregate the silhouette scores for samples belonging to\n # cluster i, and sort them\n ith_cluster_silhouette_values = \\\n sample_silhouette_values[cluster_labels == i]\n\n ith_cluster_silhouette_values.sort()\n\n size_cluster_i = ith_cluster_silhouette_values.shape[0]\n y_upper = y_lower + size_cluster_i\n\n y_values = np.arange(y_lower, y_upper)\n\n for j in range(len(y_values)):\n y_sil.append(y_values[j])\n x_sil.append(ith_cluster_silhouette_values[j])\n color_sil.append(i)\n count+=1\n if count >= chart_limit:\n wandb.termwarn(\"wandb uses only the first %d datapoints to create the plots.\"% wandb.Table.MAX_ROWS)\n break\n\n # Compute the new y_lower for next plot\n y_lower = y_upper + 10 # 10 for the 0 samples\n\n # Plot 2: Scatter Plot showing the actual clusters formed\n if kmeans:\n centers = clusterer.cluster_centers_\n def silhouette(x, y, colors, centerx, centery, y_sil, x_sil, color_sil, silhouette_avg):\n return wandb.visualize(\n 'wandb/silhouette_/v1', wandb.Table(\n columns=['x', 'y', 'colors', 'centerx', 'centery', 'y_sil', 'x1', 'x2', 'color_sil', 'silhouette_avg'],\n data=[\n [x[i], y[i], colors[i], centerx[colors[i]], centery[colors[i]],\n y_sil[i], 0, x_sil[i], color_sil[i], silhouette_avg]\n for i in range(len(color_sil))\n ]\n ))\n wandb_key = 'silhouette_plot'\n wandb.log({wandb_key: silhouette(X[:, 0], X[:, 1], cluster_labels, centers[:, 0], centers[:, 1], y_sil, x_sil, color_sil, silhouette_avg)})\n else:\n centerx = [None] * len(color_sil)\n centery = [None] * len(color_sil)\n def silhouette(x, y, colors, centerx, centery, y_sil, x_sil, color_sil, silhouette_avg):\n return wandb.visualize(\n 'wandb/silhouette_/v1', wandb.Table(\n columns=['x', 'y', 'colors', 'centerx', 'centery', 'y_sil', 'x1', 'x2', 'color_sil', 'silhouette_avg'],\n data=[\n [x[i], y[i], colors[i], None, None,\n y_sil[i], 0, x_sil[i], color_sil[i], silhouette_avg]\n for i in range(len(color_sil))\n ]\n ))\n wandb_key = 'silhouette_plot'\n wandb.log({wandb_key: silhouette(X[:, 0], X[:, 1], cluster_labels, centerx, centery, y_sil, x_sil, color_sil, silhouette_avg)})\n return\n\n\ndef plot_class_proportions(y_train=None, y_test=None, labels=None):\n \"\"\"\n Plots the distribution of target classses in training and test sets.\n Useful for detecting imbalanced classes.\n\n Arguments:\n y_train (arr): Training set labels.\n y_test (arr): Test set labels.\n labels (list): Named labels for target varible (y). Makes plots easier to\n read by replacing target values with corresponding index.\n For example labels= ['dog', 'cat', 'owl'] all 0s are\n replaced by 'dog', 1s by 'cat'.\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_class_proportions(y_train, y_test, ['dog', 'cat', 'owl'])\n \"\"\"\n if (test_missing(y_train=y_train, y_test=y_test) and\n test_types(y_train=y_train, y_test=y_test)):\n # Get the unique values from the dataset\n y_train = np.array(y_train)\n y_test = np.array(y_test)\n targets = (y_train,) if y_test is None else (y_train, y_test)\n classes_ = np.array(unique_labels(*targets))\n\n # Compute the class counts\n class_counts_train = np.array([(y_train == c).sum() for c in classes_])\n class_counts_test = np.array([(y_test == c).sum() for c in classes_])\n\n def class_proportions(classes_, class_counts_train, class_counts_test):\n class_dict = []\n dataset_dict = []\n count_dict = []\n for i in range(len(classes_)):\n # add class counts from training set\n class_dict.append(classes_[i])\n dataset_dict.append(\"train\")\n count_dict.append(class_counts_train[i])\n # add class counts from test set\n class_dict.append(classes_[i])\n dataset_dict.append(\"test\")\n count_dict.append(class_counts_test[i])\n if i >= chart_limit:\n wandb.termwarn(\"wandb uses only the first %d datapoints to create the plots.\"% wandb.Table.MAX_ROWS)\n break\n\n if labels is not None and (isinstance(class_dict[0], int)\n or isinstance(class_dict[0], np.integer)):\n class_dict = get_named_labels(labels, class_dict)\n return wandb.visualize(\n 'wandb/class_proportions/v1', wandb.Table(\n columns=['class', 'dataset', 'count'],\n data=[\n [class_dict[i], dataset_dict[i], count_dict[i]] for i in range(len(class_dict))\n ]\n ))\n wandb.log({'class_proportions': class_proportions(classes_, class_counts_train, class_counts_test)})\n\n\ndef plot_calibration_curve(clf=None, X=None, y=None, clf_name='Classifier'):\n \"\"\"\n Plots how well calibrated the predicted probabilities of a classifier are and\n how to calibrate an uncalibrated classifier. Compares estimated predicted\n probabilities by a baseline logistic regression model, the model passed as\n an argument, and by both its isotonic calibration and sigmoid calibrations.\n The closer the calibration curves are to a diagonal the better.\n A sine wave like curve represents an overfitted classifier, while a cosine\n wave like curve represents an underfitted classifier.\n By training isotonic and sigmoid calibrations of the model and comparing\n their curves we can figure out whether the model is over or underfitting and\n if so which calibration (sigmoid or isotonic) might help fix this.\n For more details, see https://scikit-learn.org/stable/auto_examples/calibration/plot_calibration_curve.html.\n\n Should only be called with a fitted classifer (otherwise an error is thrown).\n Please note this function fits variations of the model on the training set when called.\n\n Arguments:\n model (clf): Takes in a fitted classifier.\n X (arr): Training set features.\n y (arr): Training set labels.\n model_name (str): Model name. Defaults to 'Classifier'\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_calibration_curve(clf, X, y, 'RandomForestClassifier')\n \"\"\"\n if (test_missing(clf=clf, X=X, y=y) and\n test_types(clf=clf, X=X, y=y) and\n test_fitted(clf)):\n y = np.asarray(y)\n # Create dataset of classification task with many redundant and few\n # informative features\n X, y = datasets.make_classification(n_samples=100000, n_features=20,\n n_informative=2, n_redundant=10,\n random_state=42)\n\n X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.99,\n random_state=42)\n # Calibrated with isotonic calibration\n isotonic = CalibratedClassifierCV(clf, cv=2, method='isotonic')\n\n # Calibrated with sigmoid calibration\n sigmoid = CalibratedClassifierCV(clf, cv=2, method='sigmoid')\n\n # Logistic regression with no calibration as baseline\n lr = LogisticRegression(C=1.)\n\n model_dict = [] # color\n frac_positives_dict = [] # y axis\n mean_pred_value_dict = [] # x axis\n hist_dict = [] # barchart y\n edge_dict = [] # barchart x\n\n # Add curve for perfectly calibrated model\n # format: model, fraction_of_positives, mean_predicted_value\n model_dict.append('Perfectly calibrated')\n frac_positives_dict.append(0)\n mean_pred_value_dict.append(0)\n hist_dict.append(0)\n edge_dict.append(0)\n model_dict.append('Perfectly calibrated')\n hist_dict.append(0)\n edge_dict.append(0)\n frac_positives_dict.append(1)\n mean_pred_value_dict.append(1)\n\n X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.98,\n random_state=42)\n\n # Add curve for LogisticRegression baseline and other models\n for clf, name in [(lr, 'Logistic'),\n (clf, clf_name),\n (isotonic, clf_name + ' + Isotonic'),\n (sigmoid, clf_name + ' + Sigmoid')]:\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n if hasattr(clf, \"predict_proba\"):\n prob_pos = clf.predict_proba(X_test)[:, 1]\n else: # use decision function\n prob_pos = clf.decision_function(X_test)\n prob_pos = \\\n (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min())\n\n clf_score = brier_score_loss(y_test, prob_pos, pos_label=y.max())\n\n fraction_of_positives, mean_predicted_value = \\\n calibration_curve(y_test, prob_pos, n_bins=10)\n hist, edges = np.histogram(\n prob_pos,\n bins=10,\n density=False)\n\n # format: model, fraction_of_positives, mean_predicted_value\n for i in range(len(fraction_of_positives)):\n hist_dict.append(hist[i])\n edge_dict.append(edges[i])\n model_dict.append(name)\n frac_positives_dict.append(round_3(fraction_of_positives[i]))\n mean_pred_value_dict.append(round_3(mean_predicted_value[i]))\n if i >= (chart_limit-2):\n wandb.termwarn(\"wandb uses only the first %d datapoints to create the plots.\"% wandb.Table.MAX_ROWS)\n break\n\n def calibration_curves(model_dict, frac_positives_dict, mean_pred_value_dict, hist_dict, edge_dict):\n return wandb.visualize(\n 'wandb/calibration/v1', wandb.Table(\n columns=['model', 'fraction_of_positives', 'mean_predicted_value', 'hist_dict', 'edge_dict'],\n data=[\n [model_dict[i], frac_positives_dict[i], mean_pred_value_dict[i], hist_dict[i], edge_dict[i]] for i in range(len(model_dict))\n ]\n ))\n wandb.log({'calibration_curve': calibration_curves(model_dict, frac_positives_dict, mean_pred_value_dict, hist_dict, edge_dict)})\n\n\ndef plot_outlier_candidates(regressor=None, X=None, y=None):\n \"\"\"\n Measures a datapoint's influence on regression model via cook's distance.\n Instances with heavily skewed influences could potentially be\n outliers. Useful for outlier detection.\n\n Should only be called with a fitted regressor (otherwise an error is thrown).\n Please note this function fits the model on the training set when called.\n\n Arguments:\n model (regressor): Takes in a fitted regressor.\n X (arr): Training set features.\n y (arr): Training set labels.\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_outlier_candidates(model, X, y)\n \"\"\"\n if (test_missing(regressor=regressor, X=X, y=y) and\n test_types(regressor=regressor, X=X, y=y) and\n test_fitted(regressor)):\n y = np.asarray(y)\n # Fit a linear model to X and y to compute MSE\n regressor.fit(X, y)\n\n # Leverage is computed as the diagonal of the projection matrix of X\n leverage = (X * np.linalg.pinv(X).T).sum(1)\n\n # Compute the rank and the degrees of freedom of the OLS model\n rank = np.linalg.matrix_rank(X)\n df = X.shape[0] - rank\n\n # Compute the MSE from the residuals\n residuals = y - regressor.predict(X)\n mse = np.dot(residuals, residuals) / df\n\n # Compute Cook's distance\n residuals_studentized = residuals / np.sqrt(mse) / np.sqrt(1 - leverage)\n distance_ = residuals_studentized ** 2 / X.shape[1]\n distance_ *= leverage / (1 - leverage)\n\n # Compute the p-values of Cook's Distance\n p_values_ = sp.stats.f.sf(distance_, X.shape[1], df)\n\n # Compute the influence threshold rule of thumb\n influence_threshold_ = 4 / X.shape[0]\n outlier_percentage_ = (\n sum(distance_ >= influence_threshold_) / X.shape[0]\n )\n outlier_percentage_ *= 100.0\n\n distance_dict = []\n count = 0\n for d in distance_:\n distance_dict.append(d)\n count+=1\n if count >= chart_limit:\n wandb.termwarn(\"wandb uses only the first %d datapoints to create the plots.\"% wandb.Table.MAX_ROWS)\n break\n\n # Draw a stem plot with the influence for each instance\n # format: distance_, len(distance_), influence_threshold_, round_3(outlier_percentage_)\n def outlier_candidates(distance, outlier_percentage, influence_threshold):\n return wandb.visualize(\n 'wandb/outliers/v1', wandb.Table(\n columns=['distance', 'instance_indicies', 'outlier_percentage', 'influence_threshold'],\n data=[\n [distance[i], i, round_3(outlier_percentage_), influence_threshold_] for i in range(len(distance))\n ]\n ))\n wandb.log({'outlier_candidates': outlier_candidates(distance_dict, outlier_percentage_, influence_threshold_)})\n return\n\n\ndef plot_residuals(regressor=None, X=None, y=None):\n \"\"\"\n Measures and plots the predicted target values (y-axis) vs the difference\n between actual and predicted target values (x-axis), as well as the\n distribution of the residual error.\n\n Should only be called with a fitted regressor (otherwise an error is thrown).\n Please note this function fits variations of the model on the training set when called.\n\n Arguments:\n model (regressor): Takes in a fitted regressor.\n X (arr): Training set features.\n y (arr): Training set labels.\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_residuals(model, X, y)\n \"\"\"\n if (test_missing(regressor=regressor, X=X, y=y) and\n test_types(regressor=regressor, X=X, y=y) and\n test_fitted(regressor)):\n y = np.asarray(y)\n # Create the train and test splits\n X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.2)\n\n # Store labels and colors for the legend ordered by call\n _labels, _colors = [], []\n regressor.fit(X_train, y_train)\n train_score_ = regressor.score(X_train, y_train)\n test_score_ = regressor.score(X_test, y_test)\n\n y_pred_train = regressor.predict(X_train)\n residuals_train = y_pred_train - y_train\n\n y_pred_test = regressor.predict(X_test)\n residuals_test = y_pred_test - y_test\n\n # format:\n # Legend: train_score_, test_score_ (play with opacity)\n # Scatterplot: dataset(train, test)(color), y_pred(x), residuals(y)\n # Histogram: dataset(train, test)(color), residuals(y), aggregate(residuals(x)) with bins=50\n def residuals(y_pred_train, residuals_train, y_pred_test, residuals_test, train_score_, test_score_):\n y_pred_dict = []\n dataset_dict = []\n residuals_dict = []\n datapoints = 0\n max_datapoints_train = 900\n max_datapoints_train = 100\n for pred, residual in zip(y_pred_train, residuals_train):\n # add class counts from training set\n y_pred_dict.append(pred)\n dataset_dict.append(\"train\")\n residuals_dict.append(residual)\n datapoints += 1\n if(datapoints >= max_datapoints_train):\n wandb.termwarn(\"wandb uses only the first %d datapoints to create the plots.\"% wandb.Table.MAX_ROWS)\n break\n datapoints = 0\n for pred, residual in zip(y_pred_test, residuals_test):\n # add class counts from training set\n y_pred_dict.append(pred)\n dataset_dict.append(\"test\")\n residuals_dict.append(residual)\n datapoints += 1\n if(datapoints >= max_datapoints_train):\n wandb.termwarn(\"wandb uses only the first %d datapoints to create the plots.\"% wandb.Table.MAX_ROWS)\n break\n\n return wandb.visualize(\n 'wandb/residuals_plot/v1', wandb.Table(\n columns=['dataset', 'y_pred', 'residuals', 'train_score', 'test_score'],\n data=[\n [dataset_dict[i], y_pred_dict[i], residuals_dict[i], train_score_, test_score_] for i in range(len(y_pred_dict))\n ]\n ))\n wandb.log({'residuals': residuals(y_pred_train, residuals_train, y_pred_test, residuals_test, train_score_, test_score_)})\n\n\ndef plot_decision_boundaries(binary_clf=None, X=None, y=None):\n \"\"\"\n Visualizes decision boundaries by sampling from the feature space where the\n classifier's uncertainty > 0.5 and projecting these point to 2D space.\n Useful for measuring model (decision boundary) complexity, visualizing\n regions where the model falters and determine whether any over or\n underfitting occured.\n\n Should only be called with a fitted **binary** classifer (otherwise an error is\n thrown). Please note this function fits variations of the model on the\n training set when called.\n\n Arguments:\n model (clf): Takes in a fitted binary classifier.\n X_train (arr): Training set features.\n y_train (arr): Training set labels.\n\n Returns:\n Nothing. To see plots, go to your W&B run page then expand the 'media' tab\n under 'auto visualizations'.\n\n Example:\n wandb.sklearn.plot_decision_boundaries(binary_classifier, X, y)\n \"\"\"\n if (test_missing(binary_clf=binary_clf, X=X, y=y) and\n test_types(binary_clf=binary_clf, X=X, y=y)):\n y = np.asarray(y)\n # plot high-dimensional decision boundary\n db = DBPlot(binary_clf)\n db.fit(X, y)\n decision_boundary_x, decision_boundary_y, decision_boundary_color, train_x, train_y, train_color, test_x, test_y, test_color = db.plot()\n def decision_boundaries(decision_boundary_x, decision_boundary_y,\n decision_boundary_color, train_x, train_y,\n train_color, test_x, test_y, test_color):\n x_dict = []\n y_dict = []\n color_dict = []\n shape_dict = []\n for i in range(min(len(decision_boundary_x),100)):\n x_dict.append(decision_boundary_x[i])\n y_dict.append(decision_boundary_y[i])\n color_dict.append(decision_boundary_color)\n for i in range(300):\n x_dict.append(test_x[i])\n y_dict.append(test_y[i])\n color_dict.append(test_color[i])\n for i in range(min(len(train_x),600)):\n x_dict.append(train_x[i])\n y_dict.append(train_y[i])\n color_dict.append(train_color[i])\n\n return wandb.visualize(\n 'wandb/decision_boundaries/v1', wandb.Table(\n columns=['x', 'y', 'color'],\n data=[\n [x_dict[i], y_dict[i], color_dict[i]] for i in range(len(x_dict))\n ]\n ))\n wandb.log({'decision_boundaries': decision_boundaries(decision_boundary_x,\n decision_boundary_y, decision_boundary_color,\n train_x, train_y, train_color, test_x, test_y,\n test_color)})\n" ]
[ [ "numpy.dot", "sklearn.datasets.make_classification", "numpy.linalg.matrix_rank", "numpy.linspace", "sklearn.metrics.silhouette_score", "numpy.asarray", "sklearn.metrics.silhouette_samples", "numpy.around", "numpy.in1d", "numpy.sqrt", "sklearn.metrics.confusion_matrix", "sklearn.metrics.mean_absolute_error", "sklearn.metrics.mean_squared_error", "sklearn.metrics.r2_score", "sklearn.base.clone", "numpy.mean", "sklearn.metrics.f1_score", "sklearn.preprocessing.LabelEncoder", "numpy.histogram", "numpy.unique", "numpy.arange", "numpy.std", "sklearn.base.is_classifier", "sklearn.base.is_regressor", "sklearn.calibration.calibration_curve", "numpy.isnan", "sklearn.metrics.precision_score", "sklearn.model_selection.train_test_split", "numpy.argsort", "numpy.array", "sklearn.utils.multiclass.unique_labels", "sklearn.metrics.recall_score", "numpy.absolute", "sklearn.linear_model.LogisticRegression", "sklearn.model_selection.learning_curve", "numpy.linalg.pinv", "sklearn.calibration.CalibratedClassifierCV", "scipy.stats.f.sf", "sklearn.metrics.accuracy_score" ] ]
matkovic/Wi-Mind
[ "86e1e3c365776665fc1c647bbf19294dffe60e55" ]
[ "FeatureExtractionModule/src/datareader.py" ]
[ "import scipy\nimport re\nimport os\nfrom datetime import datetime\nimport numpy as np\nimport pandas as pd\nfrom _bisect import bisect\nfrom itertools import groupby\n\n\nclass DataReader:\n \"\"\"Provides functions to read raw data acquired during the cognitive load study\n i.e. tasks information and wireless data).\"\"\"\n\n def __init__(self, path, ident):\n \"\"\"\n :param path: (str) Path to a files\n :param ident: (str) User identifier\n \"\"\"\n self.path = path\n self.ident = ident\n self.phase = None\n self.time = None\n self.extracted_cog_res = None\n\n def read_grc_data(self):\n \"\"\"Loads data from given path (self.path) and identifier (self.ident)\n\n :returns: Array of [time and phase] values.\n \"\"\"\n self.phase = scipy.fromfile(open(self.path+'/'+self.ident+'/'+self.ident+'-phase-new.dat'), dtype=scipy.float32)\n self.time = scipy.fromfile(open(self.path+'/'+self.ident+'/'+self.ident+'-time-new.dat'), dtype=scipy.float32)\n\n # fixes different lenghts of data phase and time, this does not significantly \"destroy\" data\n if len(self.phase) < len(self.time):\n self.time = self.time[:len(self.phase)]\n elif len(self.phase) > len(self.time):\n self.phase = self.phase[:len(self.time)]\n\n return [self.time, self.phase]\n\n def fix_grc_data_and_save(self):\n \"\"\"Fix repetitive / \"duplicate\" values from the signal and save to files.\n This fixes data, acquired directly with GNU Radio. (can be done in GNU Radio, if possible)\"\"\"\n ph = [x[0] for x in groupby(self.phase)]\n ti = [x[0] for x in groupby(self.time)]\n np.array(ph).tofile(self.path+'/'+self.ident+'/'+self.ident+'-phase-new.dat')\n np.array(ti).tofile(self.path+'/'+self.ident+'/'+self.ident+'-time-new.dat')\n\n def unwrap_grc_data(self):\n \"\"\"\n :returns: Array of [time and unwrapped phase] values.\n \"\"\"\n return [self.time, np.unwrap(self.phase)]\n\n def extract_cognitive_load_study(self, save_path=None):\n \"\"\"Reads relevant data from study files (task information) and saves to file.\n\n :param save_path: (str) Path to output file\n\n :returns: Output data (same as output file data)\n \"\"\"\n\n global client_id\n reset_global()\n\n directory = self.path+self.ident+'/'\n mSF = re.compile(r\"(\\w+)-primary.txt\")\n\n if save_path:\n try:\n os.remove(save_path)\n except OSError:\n pass\n\n for filename in os.listdir(directory):\n if mSF.search(filename):\n reset_user()\n reset_task()\n client_id = mSF.search(filename).group(1)\n f = open(os.path.join(directory, filename), \"r\", encoding=\"utf8\")\n for line in f:\n # print line\n parse(line, save_path)\n continue\n else:\n continue\n\n results = []\n for filename in os.listdir(directory):\n if mSF.search(filename):\n f = open(os.path.join(save_path), \"r\", encoding=\"utf8\")\n for line in f:\n # print line\n results.append([x.strip() if not x.isdigit() else int(x.strip()) for x in line.split(' ')])\n continue\n else:\n continue\n\n # also save to object var\n self.extracted_cog_res = results\n return results\n\n def read_cognitive_load_study(self, file):\n \"\"\"Use if you already have the extracted file. This reads data from the extracted file.\n\n :param file: (str) Name of the file, that contains extracted data from the study (tasks information).\n :returns: Dataframe of extracted file.\n \"\"\"\n filepath = self.path+self.ident+'/'+file\n readfile = pd.read_csv(filepath, sep=\" \", header=None)\n readfile.columns = ['task_number', 'person_id', 'task_label',\n 'task_complexity', 'start_time', 'time_on_task',\n 'num_correct', 'num_incorrect', 'num_all_correct',\n 'task_load_index', 'finished']\n return readfile\n\n def get_data_task_timestamps(self, return_indexes=False):\n \"\"\"Returns times of each task time frame start-end.\n\n :param return_indexes: True - return index in array; False - return actual time in array.\n :return: Array of tuples, where each tuple presents beginning and end of a task time frame.\n \"\"\"\n data = [self.time, self.phase]\n end_time = self.get_end_time_cognitive_load_study()\n cognitive_study_results = self.read_cognitive_load_study(self.ident+'-primary-extract.txt')\n\n timestamps = []\n for i in range(len(cognitive_study_results)):\n task_1_start = cognitive_study_results['start_time'][i]\n task_1_length = cognitive_study_results['time_on_task'][i]\n\n difference = (end_time - task_1_start) / 1000\n\n start_on_data = data[0][-1] - difference\n end_on_data = start_on_data + task_1_length / 1000\n\n if return_indexes:\n start_on_data = bisect(data[0], start_on_data)\n end_on_data = bisect(data[0], end_on_data)\n\n timestamps.append((start_on_data, end_on_data))\n\n return timestamps\n\n def get_relax_timestamps(self, return_indexes=False):\n \"\"\"Returns times of each relax time frame start-end.\n\n :param return_indexes: True - return index in array; False - return actual time in array.\n :return: Array of tuples, where each tuple presents beginning and end of a relax time frame.\n \"\"\"\n dataread = self\n end_time = self.get_end_time_cognitive_load_study()\n relax_timestamps = dataread.get_relax_timestamps_from_file()\n data = [self.time, self.phase]\n\n timestamps = []\n for i in range(0, len(relax_timestamps) - 1, 2):\n relax_start = relax_timestamps[i]\n relax_stop = relax_timestamps[i + 1]\n\n difference1 = (end_time - relax_start) / 1000\n difference2 = (end_time - relax_stop) / 1000\n\n start_on_data = data[0][-1] - difference1\n stop_on_data = data[0][-1] - difference2\n\n if return_indexes:\n start_on_data = bisect(data[0], start_on_data)\n stop_on_data = bisect(data[0], stop_on_data)\n\n timestamps.append((start_on_data, stop_on_data))\n\n return timestamps\n\n def get_end_time_cognitive_load_study(self):\n \"\"\"Returns the end time of the study (used to synchronize the data from GNU Radio).\n\n :return: Unix epoch time.\n \"\"\"\n\n global client_id\n reset_global()\n\n directory = self.path+self.ident+'/'\n mSF = re.compile(r\"(\\w+)-primary.txt\")\n\n for filename in os.listdir(directory):\n if mSF.search(filename):\n reset_user()\n reset_task()\n f = open(os.path.join(directory, filename), \"r\", encoding=\"utf8\")\n linelist = f.readlines()\n f.close()\n return convert_to_epoch([x.strip() for x in linelist[-1].split(',')][0])\n continue\n else:\n continue\n return 0\n\n def get_relax_timestamps_from_file(self):\n \"\"\"Read relax timestamps from file.\n\n :return: Array of times, where each value presents either beginning (i) or end (i+1) of a relax time frame.\n \"\"\"\n\n global client_id\n reset_global()\n\n directory = self.path+self.ident+'/'\n mSF = re.compile(r\"(\\w+)-primary.txt\")\n\n times = []\n for filename in os.listdir(directory):\n if mSF.search(filename):\n reset_user()\n reset_task()\n client_id = mSF.search(filename).group(1)\n f = open(os.path.join(directory, filename), \"r\", encoding=\"utf8\")\n for line in f:\n # print line\n time = parse_relax_times(line)\n if time!=None:\n times.append(time)\n continue\n else:\n continue\n\n # also save to object var\n # self.extracted_cog_res = results\n return times\n\n\n\"\"\"Code below is used to extract relevant data from the study.\"\"\"\n\n# Reset the whole process - taskIds start from zero\ndef reset_global():\n global SEED_TASK_ID\n global SEED_SEC_TASK_ID\n SEED_TASK_ID = 224\n SEED_SEC_TASK_ID = 1730\n\n\ndef reset_user():\n global client_id\n client_id = \"\"\n\n\n# For each new Task - reset all task-related params\ndef reset_task():\n global start_time\n global end_time\n global state_prim\n global state_sec\n global task_type\n global label\n global finished\n global num_all_correct\n global num_correct\n global num_incorrect\n global curr_task_id\n global curr_sec_task_id\n global task_load_index\n\n start_time = 0\n end_time = 0\n num_correct = 0\n num_incorrect = 0\n num_all_correct = 0\n label = \"\"\n task_type = \"\"\n task_load_index = 0\n finished = True\n state_prim = 0\n state_sec = 0\n curr_task_id = -1\n curr_sec_task_id = -1\n\n\n# This function is called when a primary task end is detected\ndef process_end(file_path):\n global state_prim\n global start_time\n global end_time\n global task_type\n global label\n global finished\n global num_all_correct\n global num_correct\n global num_incorrect\n global curr_task_id\n global client_id\n global task_load_index\n global cursor\n\n time_on_task = end_time - start_time\n\n if task_type == 'HP':\n num_all_correct = 21\n if task_type == 'FA':\n # We know that there are 2 groups, 5 A-words in evey group\n num_all_correct = 10\n if task_type == 'GC':\n num_all_correct = 5\n if task_type == 'NC':\n if label == \"low\":\n num_all_correct = 11\n elif label == \"medium\":\n num_all_correct = 14\n elif label == \"high\":\n num_all_correct = 4\n if task_type == 'SX':\n num_all_correct = 20\n if task_type == 'PT':\n num_all_correct = 10\n\n if curr_task_id > -1:\n if not file_path:\n print(curr_task_id, client_id, task_type, label, start_time, time_on_task, num_correct, num_incorrect,\n num_all_correct, task_load_index, finished)\n else:\n with open(file_path, 'a') as save_file:\n save_file.write(str(curr_task_id)+' '+str(client_id)+' '+str(task_type)+' '+str(label)+' '+str(start_time)+' '+str(time_on_task)+' '+str(num_correct)+' '+str(num_incorrect)+' '+\n str(num_all_correct)+' '+str(task_load_index)+' '+str(finished)+'\\n')\n\n\ndef convert_to_epoch(value):\n datetime_object = datetime.strptime(value, '%Y:%m:%d:%H:%M:%S:%f')\n return int(datetime_object.timestamp()) * 1000 + int(datetime_object.microsecond / 1000)\n\n\ndef generate_task_ID():\n global SEED_TASK_ID\n SEED_TASK_ID += 1\n return SEED_TASK_ID\n\n\n# Result checker for PT task\ndef PT_checker(num1, num2, task_type):\n low_map = {\n \"1\": \"3\",\n \"2\": \"4\",\n \"3\": \"1\",\n \"4\": \"2\",\n \"5\": \"6\",\n \"6\": \"5\",\n \"7\": \"9\",\n \"8\": \"10\",\n \"9\": \"7\",\n \"10\": \"8\",\n }\n\n medium_map = {\n \"1\": \"5\",\n \"2\": \"6\",\n \"3\": \"2\",\n \"4\": \"8\",\n \"5\": \"10\",\n \"6\": \"1\",\n \"7\": \"3\",\n \"8\": \"9\",\n \"9\": \"4\",\n \"10\": \"6\",\n }\n\n high_map = {\n \"1\": \"9\",\n \"2\": \"8\",\n \"3\": \"10\",\n \"4\": \"7\",\n \"5\": \"6\",\n \"6\": \"5\",\n \"7\": \"4\",\n \"8\": \"3\",\n \"9\": \"1\",\n \"10\": \"2\",\n }\n\n if task_type == \"low\":\n return num2 == low_map.get(num1)\n elif task_type == \"medium\":\n return num2 == medium_map.get(num1)\n elif task_type == \"high\":\n return num2 == high_map.get(num1)\n\n\n# TLX string value to int mapping\ndef TLX(value, measure_type):\n M_map = {\n \"Zelo nizko\": 1,\n \"Nizko\": 2,\n \"Srednje\": 3,\n \"Visoko\": 4,\n \"Zelo visoko\": 5,\n }\n\n P_map = {\n \"Zelo dobro\": 1,\n \"Dobro\": 2,\n \"Srednje\": 3,\n \"Slabo\": 4,\n \"Zelo slabo\": 5,\n }\n\n E_map = {\n \"Zelo malo\": 1,\n \"Malo\": 2,\n \"Srednje\": 3,\n \"Veliko\": 4,\n \"Zelo veliko\": 5,\n }\n\n if measure_type == \"Physical\" or measure_type == \"Mental\" or measure_type == \"Temporal\" or measure_type == \"Frustration\":\n return M_map.get(value)\n if measure_type == \"Performance\":\n return P_map.get(value)\n if measure_type == \"Effort\":\n return E_map.get(value)\n\n\n# Each line of text in the file should be processed, so that primary and secondary tasks are identified\ndef parse(line, file_path):\n global curr_task_id\n global curr_sec_task_id\n global num_correct\n global num_incorrect\n global label\n global finished\n global task_load_index\n global start_time\n global start_time_sec\n global end_time\n global state_prim\n global state_sec\n global task_type\n global cursor\n\n mHP = re.compile(r\"(\\S+), Hidden Pattern Question Slide, HiddenPattern(\\d).txt, (\\w+),\")\n mHPres = mHP.search(line)\n if mHPres and state_prim == 0:\n task_type = 'HP'\n label = mHPres.group(3).lower()\n start_time = convert_to_epoch(mHPres.group(1))\n state_prim = 1\n curr_task_id = generate_task_ID()\n # print(start_time, task_type, label, curr_task_id)\n\n mFA = re.compile(r\"(\\S+), Finding A's Question Slide, FindingAs_(\\d).txt, (\\w+)\")\n mFAres = mFA.search(line)\n if mFAres and state_prim == 0:\n task_type = 'FA'\n label = mFAres.group(3).lower()\n start_time = convert_to_epoch(mFAres.group(1))\n state_prim = 1\n curr_task_id = generate_task_ID()\n # print(start_time, task_type, label, curr_task_id)\n\n mGC = re.compile(r\"(\\S+), Gestalt Completion Question Slide, GestaltCompletion(\\d).txt, (\\w+)\")\n mGCres = mGC.search(line)\n if mGCres and state_prim == 0:\n task_type = 'GC'\n label = mGCres.group(3).lower()\n start_time = convert_to_epoch(mGCres.group(1))\n state_prim = 1\n curr_task_id = generate_task_ID()\n # print(start_time, task_type, label, curr_task_id)\n\n mNC = re.compile(r\"(\\S+), Number Comparison Question Slide, NumberComparison_(\\d).txt, (\\w+)\")\n mNCres = mNC.search(line)\n if mNCres and state_prim == 0:\n task_type = 'NC'\n label = mNCres.group(3).lower()\n start_time = convert_to_epoch(mNCres.group(1))\n state_prim = 1\n curr_task_id = generate_task_ID()\n # print(start_time, task_type, label, curr_task_id)\n\n mSX = re.compile(r\"(\\S+), Scattered X's Question Slide, ScatteredXs_(\\d).txt, (\\w+)\")\n mSXres = mSX.search(line)\n if mSXres and state_prim == 0:\n task_type = 'SX'\n label = mSXres.group(3).lower()\n start_time = convert_to_epoch(mSXres.group(1))\n state_prim = 1\n curr_task_id = generate_task_ID()\n # print(start_time, task_type, label, curr_task_id)\n\n mPT = re.compile(r\"(\\S+), Pursuit Test Question Slide, Pursuit_(\\d).txt, (\\w+)\")\n mPTres = mPT.search(line)\n if mPTres and state_prim == 0:\n task_type = 'PT'\n label = mPTres.group(3).lower()\n start_time = convert_to_epoch(mPTres.group(1))\n state_prim = 1\n curr_task_id = generate_task_ID()\n # print(start_time, task_type, label, curr_task_id)\n\n mHProw = re.compile(r\"'image/HiddenPatterns/(\\S+)_(\\w+).jpg' selected\")\n mHProwres = mHProw.search(line)\n if mHProwres:\n result = mHProwres.group(2)\n if result == \"true\":\n num_correct += 1\n elif result == \"false\":\n num_incorrect += 1\n\n mFArow = re.compile(r\" '([a-zA-Z]+)' selected\")\n mFArowres = mFArow.search(line)\n if mFArowres:\n result = mFArowres.group(1).lower()\n if 'a' in result:\n num_correct += 1\n else:\n num_incorrect += 1\n\n mNCrow = re.compile(r\" '([0-9]+)-([0-9]+)' selected\")\n mNCrowres = mNCrow.search(line)\n if mNCrowres:\n num1 = mNCrowres.group(1)\n num2 = mNCrowres.group(2)\n if num1 != num2:\n num_correct += 1\n else:\n num_incorrect += 1\n\n mSXrow = re.compile(\" \\(\\d+,\\d+\\), \\(\\d+,\\d+\\)\")\n mSXrowres = mSXrow.search(line)\n if mSXrowres:\n num_correct += 1\n\n mPTrow = re.compile(\", (\\d+), '(\\d+)'\")\n mPTrowres = mPTrow.search(line)\n if mPTrowres:\n num1 = mPTrowres.group(1)\n num2 = mPTrowres.group(2)\n if PT_checker(num1, num2, label):\n num_correct += 1\n else:\n num_incorrect += 1\n\n mTIU = re.compile(r\"TimeIsUp Slide\")\n mTIUres = mTIU.search(line)\n if mTIUres:\n finished = False\n\n mR = re.compile(r\"(\\S+), Rating Slide\")\n mRres = mR.search(line)\n if mRres:\n end_time = convert_to_epoch(mRres.group(1))\n\n mRM = re.compile(r\"(Mental|Physical|Temporal|Performance|Effort|Frustration), ([\\s\\w]+)\")\n mRMres = mRM.search(line)\n if mRMres:\n task_load_index += TLX(mRMres.group(2).rstrip(), mRMres.group(1).rstrip())\n\n mB = re.compile(r\"(Break|End) Slide\")\n mBres = mB.search(line)\n if mBres and state_prim == 1:\n process_end(file_path)\n reset_task()\n\n\ndef parse_relax_times(line):\n mB = re.compile(r\"(\\S+), (Break|End) Slide\")\n mBres = mB.search(line)\n if mBres:\n start_time = convert_to_epoch(mBres.group(1))\n return start_time\n\n mR = re.compile(r\"(\\S+), Test Continues Slide\")\n mRres = mR.search(line)\n if mRres:\n end_time = convert_to_epoch(mRres.group(1))\n return end_time\n" ]
[ [ "numpy.array", "numpy.unwrap", "pandas.read_csv" ] ]
jle3/pandas
[ "c322b2436cdbb447a430bb9eb1aff965d07e7e4e" ]
[ "pandas/core/indexes/interval.py" ]
[ "\"\"\" define the IntervalIndex \"\"\"\nfrom __future__ import annotations\n\nfrom functools import wraps\nfrom operator import le, lt\nimport textwrap\nfrom typing import TYPE_CHECKING, Any, Hashable, List, Optional, Tuple, Union, cast\n\nimport numpy as np\n\nfrom pandas._config import get_option\n\nfrom pandas._libs import lib\nfrom pandas._libs.interval import Interval, IntervalMixin, IntervalTree\nfrom pandas._libs.tslibs import BaseOffset, Timedelta, Timestamp, to_offset\nfrom pandas._typing import Dtype, DtypeObj\nfrom pandas.errors import InvalidIndexError\nfrom pandas.util._decorators import Appender, cache_readonly\nfrom pandas.util._exceptions import rewrite_exception\n\nfrom pandas.core.dtypes.cast import (\n find_common_type,\n infer_dtype_from_scalar,\n maybe_box_datetimelike,\n maybe_downcast_numeric,\n)\nfrom pandas.core.dtypes.common import (\n ensure_platform_int,\n is_categorical_dtype,\n is_datetime64tz_dtype,\n is_datetime_or_timedelta_dtype,\n is_dtype_equal,\n is_float,\n is_float_dtype,\n is_integer,\n is_integer_dtype,\n is_interval_dtype,\n is_list_like,\n is_number,\n is_object_dtype,\n is_scalar,\n)\nfrom pandas.core.dtypes.dtypes import IntervalDtype\n\nfrom pandas.core.algorithms import take_1d, unique\nfrom pandas.core.arrays.interval import IntervalArray, _interval_shared_docs\nimport pandas.core.common as com\nfrom pandas.core.indexers import is_valid_positional_slice\nimport pandas.core.indexes.base as ibase\nfrom pandas.core.indexes.base import (\n Index,\n _index_shared_docs,\n default_pprint,\n ensure_index,\n maybe_extract_name,\n)\nfrom pandas.core.indexes.datetimes import DatetimeIndex, date_range\nfrom pandas.core.indexes.extension import ExtensionIndex, inherit_names\nfrom pandas.core.indexes.multi import MultiIndex\nfrom pandas.core.indexes.timedeltas import TimedeltaIndex, timedelta_range\nfrom pandas.core.ops import get_op_result_name\n\nif TYPE_CHECKING:\n from pandas import CategoricalIndex\n\n_index_doc_kwargs = dict(ibase._index_doc_kwargs)\n\n_index_doc_kwargs.update(\n {\n \"klass\": \"IntervalIndex\",\n \"qualname\": \"IntervalIndex\",\n \"target_klass\": \"IntervalIndex or list of Intervals\",\n \"name\": textwrap.dedent(\n \"\"\"\\\n name : object, optional\n Name to be stored in the index.\n \"\"\"\n ),\n }\n)\n\n\ndef _get_next_label(label):\n dtype = getattr(label, \"dtype\", type(label))\n if isinstance(label, (Timestamp, Timedelta)):\n dtype = \"datetime64\"\n if is_datetime_or_timedelta_dtype(dtype) or is_datetime64tz_dtype(dtype):\n return label + np.timedelta64(1, \"ns\")\n elif is_integer_dtype(dtype):\n return label + 1\n elif is_float_dtype(dtype):\n return np.nextafter(label, np.infty)\n else:\n raise TypeError(f\"cannot determine next label for type {repr(type(label))}\")\n\n\ndef _get_prev_label(label):\n dtype = getattr(label, \"dtype\", type(label))\n if isinstance(label, (Timestamp, Timedelta)):\n dtype = \"datetime64\"\n if is_datetime_or_timedelta_dtype(dtype) or is_datetime64tz_dtype(dtype):\n return label - np.timedelta64(1, \"ns\")\n elif is_integer_dtype(dtype):\n return label - 1\n elif is_float_dtype(dtype):\n return np.nextafter(label, -np.infty)\n else:\n raise TypeError(f\"cannot determine next label for type {repr(type(label))}\")\n\n\ndef _new_IntervalIndex(cls, d):\n \"\"\"\n This is called upon unpickling, rather than the default which doesn't have\n arguments and breaks __new__.\n \"\"\"\n return cls.from_arrays(**d)\n\n\ndef setop_check(method):\n \"\"\"\n This is called to decorate the set operations of IntervalIndex\n to perform the type check in advance.\n \"\"\"\n op_name = method.__name__\n\n @wraps(method)\n def wrapped(self, other, sort=False):\n self._validate_sort_keyword(sort)\n self._assert_can_do_setop(other)\n other, result_name = self._convert_can_do_setop(other)\n\n if op_name == \"difference\":\n if not isinstance(other, IntervalIndex):\n result = getattr(self.astype(object), op_name)(other, sort=sort)\n return result.astype(self.dtype)\n\n elif not self._should_compare(other):\n # GH#19016: ensure set op will not return a prohibited dtype\n result = getattr(self.astype(object), op_name)(other, sort=sort)\n return result.astype(self.dtype)\n\n return method(self, other, sort)\n\n return wrapped\n\n\n@Appender(\n _interval_shared_docs[\"class\"]\n % {\n \"klass\": \"IntervalIndex\",\n \"summary\": \"Immutable index of intervals that are closed on the same side.\",\n \"name\": _index_doc_kwargs[\"name\"],\n \"versionadded\": \"0.20.0\",\n \"extra_attributes\": \"is_overlapping\\nvalues\\n\",\n \"extra_methods\": \"\",\n \"examples\": textwrap.dedent(\n \"\"\"\\\n Examples\n --------\n A new ``IntervalIndex`` is typically constructed using\n :func:`interval_range`:\n\n >>> pd.interval_range(start=0, end=5)\n IntervalIndex([(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]],\n dtype='interval[int64, right]')\n\n It may also be constructed using one of the constructor\n methods: :meth:`IntervalIndex.from_arrays`,\n :meth:`IntervalIndex.from_breaks`, and :meth:`IntervalIndex.from_tuples`.\n\n See further examples in the doc strings of ``interval_range`` and the\n mentioned constructor methods.\n \"\"\"\n ),\n }\n)\n@inherit_names([\"set_closed\", \"to_tuples\"], IntervalArray, wrap=True)\n@inherit_names([\"__array__\", \"overlaps\", \"contains\"], IntervalArray)\n@inherit_names([\"is_non_overlapping_monotonic\", \"closed\"], IntervalArray, cache=True)\nclass IntervalIndex(IntervalMixin, ExtensionIndex):\n _typ = \"intervalindex\"\n _comparables = [\"name\"]\n _attributes = [\"name\", \"closed\"]\n\n # we would like our indexing holder to defer to us\n _defer_to_indexing = True\n\n _data: IntervalArray\n _values: IntervalArray\n _can_hold_strings = False\n\n # --------------------------------------------------------------------\n # Constructors\n\n def __new__(\n cls,\n data,\n closed=None,\n dtype: Optional[Dtype] = None,\n copy: bool = False,\n name=None,\n verify_integrity: bool = True,\n ):\n\n name = maybe_extract_name(name, data, cls)\n\n with rewrite_exception(\"IntervalArray\", cls.__name__):\n array = IntervalArray(\n data,\n closed=closed,\n copy=copy,\n dtype=dtype,\n verify_integrity=verify_integrity,\n )\n\n return cls._simple_new(array, name)\n\n @classmethod\n def _simple_new(cls, array: IntervalArray, name: Hashable = None):\n \"\"\"\n Construct from an IntervalArray\n\n Parameters\n ----------\n array : IntervalArray\n name : Label, default None\n Attached as result.name\n \"\"\"\n assert isinstance(array, IntervalArray), type(array)\n\n result = IntervalMixin.__new__(cls)\n result._data = array\n result.name = name\n result._cache = {}\n result._reset_identity()\n return result\n\n @classmethod\n @Appender(\n _interval_shared_docs[\"from_breaks\"]\n % {\n \"klass\": \"IntervalIndex\",\n \"examples\": textwrap.dedent(\n \"\"\"\\\n Examples\n --------\n >>> pd.IntervalIndex.from_breaks([0, 1, 2, 3])\n IntervalIndex([(0, 1], (1, 2], (2, 3]],\n dtype='interval[int64, right]')\n \"\"\"\n ),\n }\n )\n def from_breaks(\n cls,\n breaks,\n closed: str = \"right\",\n name=None,\n copy: bool = False,\n dtype: Optional[Dtype] = None,\n ):\n with rewrite_exception(\"IntervalArray\", cls.__name__):\n array = IntervalArray.from_breaks(\n breaks, closed=closed, copy=copy, dtype=dtype\n )\n return cls._simple_new(array, name=name)\n\n @classmethod\n @Appender(\n _interval_shared_docs[\"from_arrays\"]\n % {\n \"klass\": \"IntervalIndex\",\n \"examples\": textwrap.dedent(\n \"\"\"\\\n Examples\n --------\n >>> pd.IntervalIndex.from_arrays([0, 1, 2], [1, 2, 3])\n IntervalIndex([(0, 1], (1, 2], (2, 3]],\n dtype='interval[int64, right]')\n \"\"\"\n ),\n }\n )\n def from_arrays(\n cls,\n left,\n right,\n closed: str = \"right\",\n name=None,\n copy: bool = False,\n dtype: Optional[Dtype] = None,\n ):\n with rewrite_exception(\"IntervalArray\", cls.__name__):\n array = IntervalArray.from_arrays(\n left, right, closed, copy=copy, dtype=dtype\n )\n return cls._simple_new(array, name=name)\n\n @classmethod\n @Appender(\n _interval_shared_docs[\"from_tuples\"]\n % {\n \"klass\": \"IntervalIndex\",\n \"examples\": textwrap.dedent(\n \"\"\"\\\n Examples\n --------\n >>> pd.IntervalIndex.from_tuples([(0, 1), (1, 2)])\n IntervalIndex([(0, 1], (1, 2]],\n dtype='interval[int64, right]')\n \"\"\"\n ),\n }\n )\n def from_tuples(\n cls,\n data,\n closed: str = \"right\",\n name=None,\n copy: bool = False,\n dtype: Optional[Dtype] = None,\n ):\n with rewrite_exception(\"IntervalArray\", cls.__name__):\n arr = IntervalArray.from_tuples(data, closed=closed, copy=copy, dtype=dtype)\n return cls._simple_new(arr, name=name)\n\n # --------------------------------------------------------------------\n\n @cache_readonly\n def _engine(self):\n left = self._maybe_convert_i8(self.left)\n right = self._maybe_convert_i8(self.right)\n return IntervalTree(left, right, closed=self.closed)\n\n def __contains__(self, key: Any) -> bool:\n \"\"\"\n return a boolean if this key is IN the index\n We *only* accept an Interval\n\n Parameters\n ----------\n key : Interval\n\n Returns\n -------\n bool\n \"\"\"\n hash(key)\n if not isinstance(key, Interval):\n return False\n\n try:\n self.get_loc(key)\n return True\n except KeyError:\n return False\n\n @cache_readonly\n def _multiindex(self) -> MultiIndex:\n return MultiIndex.from_arrays([self.left, self.right], names=[\"left\", \"right\"])\n\n def __array_wrap__(self, result, context=None):\n # we don't want the superclass implementation\n return result\n\n def __reduce__(self):\n d = {\"left\": self.left, \"right\": self.right}\n d.update(self._get_attributes_dict())\n return _new_IntervalIndex, (type(self), d), None\n\n @Appender(Index.astype.__doc__)\n def astype(self, dtype, copy: bool = True):\n with rewrite_exception(\"IntervalArray\", type(self).__name__):\n new_values = self._values.astype(dtype, copy=copy)\n return Index(new_values, dtype=new_values.dtype, name=self.name)\n\n @property\n def inferred_type(self) -> str:\n \"\"\"Return a string of the type inferred from the values\"\"\"\n return \"interval\"\n\n @Appender(Index.memory_usage.__doc__)\n def memory_usage(self, deep: bool = False) -> int:\n # we don't use an explicit engine\n # so return the bytes here\n return self.left.memory_usage(deep=deep) + self.right.memory_usage(deep=deep)\n\n # IntervalTree doesn't have a is_monotonic_decreasing, so have to override\n # the Index implementation\n @cache_readonly\n def is_monotonic_decreasing(self) -> bool:\n \"\"\"\n Return True if the IntervalIndex is monotonic decreasing (only equal or\n decreasing values), else False\n \"\"\"\n return self[::-1].is_monotonic_increasing\n\n @cache_readonly\n def is_unique(self) -> bool:\n \"\"\"\n Return True if the IntervalIndex contains unique elements, else False.\n \"\"\"\n left = self.left\n right = self.right\n\n if self.isna().sum() > 1:\n return False\n\n if left.is_unique or right.is_unique:\n return True\n\n seen_pairs = set()\n check_idx = np.where(left.duplicated(keep=False))[0]\n for idx in check_idx:\n pair = (left[idx], right[idx])\n if pair in seen_pairs:\n return False\n seen_pairs.add(pair)\n\n return True\n\n @property\n def is_overlapping(self) -> bool:\n \"\"\"\n Return True if the IntervalIndex has overlapping intervals, else False.\n\n Two intervals overlap if they share a common point, including closed\n endpoints. Intervals that only have an open endpoint in common do not\n overlap.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n bool\n Boolean indicating if the IntervalIndex has overlapping intervals.\n\n See Also\n --------\n Interval.overlaps : Check whether two Interval objects overlap.\n IntervalIndex.overlaps : Check an IntervalIndex elementwise for\n overlaps.\n\n Examples\n --------\n >>> index = pd.IntervalIndex.from_tuples([(0, 2), (1, 3), (4, 5)])\n >>> index\n IntervalIndex([(0, 2], (1, 3], (4, 5]],\n dtype='interval[int64, right]')\n >>> index.is_overlapping\n True\n\n Intervals that share closed endpoints overlap:\n\n >>> index = pd.interval_range(0, 3, closed='both')\n >>> index\n IntervalIndex([[0, 1], [1, 2], [2, 3]],\n dtype='interval[int64, both]')\n >>> index.is_overlapping\n True\n\n Intervals that only have an open endpoint in common do not overlap:\n\n >>> index = pd.interval_range(0, 3, closed='left')\n >>> index\n IntervalIndex([[0, 1), [1, 2), [2, 3)],\n dtype='interval[int64, left]')\n >>> index.is_overlapping\n False\n \"\"\"\n # GH 23309\n return self._engine.is_overlapping\n\n def _needs_i8_conversion(self, key) -> bool:\n \"\"\"\n Check if a given key needs i8 conversion. Conversion is necessary for\n Timestamp, Timedelta, DatetimeIndex, and TimedeltaIndex keys. An\n Interval-like requires conversion if its endpoints are one of the\n aforementioned types.\n\n Assumes that any list-like data has already been cast to an Index.\n\n Parameters\n ----------\n key : scalar or Index-like\n The key that should be checked for i8 conversion\n\n Returns\n -------\n bool\n \"\"\"\n if is_interval_dtype(key) or isinstance(key, Interval):\n return self._needs_i8_conversion(key.left)\n\n i8_types = (Timestamp, Timedelta, DatetimeIndex, TimedeltaIndex)\n return isinstance(key, i8_types)\n\n def _maybe_convert_i8(self, key):\n \"\"\"\n Maybe convert a given key to its equivalent i8 value(s). Used as a\n preprocessing step prior to IntervalTree queries (self._engine), which\n expects numeric data.\n\n Parameters\n ----------\n key : scalar or list-like\n The key that should maybe be converted to i8.\n\n Returns\n -------\n scalar or list-like\n The original key if no conversion occurred, int if converted scalar,\n Int64Index if converted list-like.\n \"\"\"\n original = key\n if is_list_like(key):\n key = ensure_index(key)\n\n if not self._needs_i8_conversion(key):\n return original\n\n scalar = is_scalar(key)\n if is_interval_dtype(key) or isinstance(key, Interval):\n # convert left/right and reconstruct\n left = self._maybe_convert_i8(key.left)\n right = self._maybe_convert_i8(key.right)\n constructor = Interval if scalar else IntervalIndex.from_arrays\n return constructor(left, right, closed=self.closed)\n\n if scalar:\n # Timestamp/Timedelta\n key_dtype, key_i8 = infer_dtype_from_scalar(key, pandas_dtype=True)\n if lib.is_period(key):\n key_i8 = key.ordinal\n else:\n # DatetimeIndex/TimedeltaIndex\n key_dtype, key_i8 = key.dtype, Index(key.asi8)\n if key.hasnans:\n # convert NaT from its i8 value to np.nan so it's not viewed\n # as a valid value, maybe causing errors (e.g. is_overlapping)\n key_i8 = key_i8.where(~key._isnan)\n\n # ensure consistency with IntervalIndex subtype\n subtype = self.dtype.subtype\n\n if not is_dtype_equal(subtype, key_dtype):\n raise ValueError(\n f\"Cannot index an IntervalIndex of subtype {subtype} with \"\n f\"values of dtype {key_dtype}\"\n )\n\n return key_i8\n\n def _searchsorted_monotonic(self, label, side, exclude_label=False):\n if not self.is_non_overlapping_monotonic:\n raise KeyError(\n \"can only get slices from an IntervalIndex if bounds are \"\n \"non-overlapping and all monotonic increasing or decreasing\"\n )\n\n if isinstance(label, IntervalMixin):\n raise NotImplementedError(\"Interval objects are not currently supported\")\n\n # GH 20921: \"not is_monotonic_increasing\" for the second condition\n # instead of \"is_monotonic_decreasing\" to account for single element\n # indexes being both increasing and decreasing\n if (side == \"left\" and self.left.is_monotonic_increasing) or (\n side == \"right\" and not self.left.is_monotonic_increasing\n ):\n sub_idx = self.right\n if self.open_right or exclude_label:\n label = _get_next_label(label)\n else:\n sub_idx = self.left\n if self.open_left or exclude_label:\n label = _get_prev_label(label)\n\n return sub_idx._searchsorted_monotonic(label, side)\n\n # --------------------------------------------------------------------\n # Indexing Methods\n\n def get_loc(\n self, key, method: Optional[str] = None, tolerance=None\n ) -> Union[int, slice, np.ndarray]:\n \"\"\"\n Get integer location, slice or boolean mask for requested label.\n\n Parameters\n ----------\n key : label\n method : {None}, optional\n * default: matches where the label is within an interval only.\n\n Returns\n -------\n int if unique index, slice if monotonic index, else mask\n\n Examples\n --------\n >>> i1, i2 = pd.Interval(0, 1), pd.Interval(1, 2)\n >>> index = pd.IntervalIndex([i1, i2])\n >>> index.get_loc(1)\n 0\n\n You can also supply a point inside an interval.\n\n >>> index.get_loc(1.5)\n 1\n\n If a label is in several intervals, you get the locations of all the\n relevant intervals.\n\n >>> i3 = pd.Interval(0, 2)\n >>> overlapping_index = pd.IntervalIndex([i1, i2, i3])\n >>> overlapping_index.get_loc(0.5)\n array([ True, False, True])\n\n Only exact matches will be returned if an interval is provided.\n\n >>> index.get_loc(pd.Interval(0, 1))\n 0\n \"\"\"\n self._check_indexing_method(method)\n\n if not is_scalar(key):\n raise InvalidIndexError(key)\n\n if isinstance(key, Interval):\n if self.closed != key.closed:\n raise KeyError(key)\n mask = (self.left == key.left) & (self.right == key.right)\n else:\n # assume scalar\n op_left = le if self.closed_left else lt\n op_right = le if self.closed_right else lt\n try:\n mask = op_left(self.left, key) & op_right(key, self.right)\n except TypeError as err:\n # scalar is not comparable to II subtype --> invalid label\n raise KeyError(key) from err\n\n matches = mask.sum()\n if matches == 0:\n raise KeyError(key)\n elif matches == 1:\n return mask.argmax()\n return lib.maybe_booleans_to_slice(mask.view(\"u1\"))\n\n def _get_indexer(\n self,\n target: Index,\n method: Optional[str] = None,\n limit: Optional[int] = None,\n tolerance: Optional[Any] = None,\n ) -> np.ndarray:\n\n if isinstance(target, IntervalIndex):\n # equal indexes -> 1:1 positional match\n if self.equals(target):\n return np.arange(len(self), dtype=\"intp\")\n\n if not self._should_compare(target):\n return self._get_indexer_non_comparable(target, method, unique=True)\n\n # non-overlapping -> at most one match per interval in target\n # want exact matches -> need both left/right to match, so defer to\n # left/right get_indexer, compare elementwise, equality -> match\n left_indexer = self.left.get_indexer(target.left)\n right_indexer = self.right.get_indexer(target.right)\n indexer = np.where(left_indexer == right_indexer, left_indexer, -1)\n elif is_categorical_dtype(target.dtype):\n target = cast(\"CategoricalIndex\", target)\n # get an indexer for unique categories then propagate to codes via take_1d\n categories_indexer = self.get_indexer(target.categories)\n indexer = take_1d(categories_indexer, target.codes, fill_value=-1)\n elif not is_object_dtype(target):\n # homogeneous scalar index: use IntervalTree\n target = self._maybe_convert_i8(target)\n indexer = self._engine.get_indexer(target.values)\n else:\n # heterogeneous scalar index: defer elementwise to get_loc\n return self._get_indexer_pointwise(target)[0]\n\n return ensure_platform_int(indexer)\n\n @Appender(_index_shared_docs[\"get_indexer_non_unique\"] % _index_doc_kwargs)\n def get_indexer_non_unique(self, target: Index) -> Tuple[np.ndarray, np.ndarray]:\n target = ensure_index(target)\n\n if isinstance(target, IntervalIndex) and not self._should_compare(target):\n # different closed or incompatible subtype -> no matches\n return self._get_indexer_non_comparable(target, None, unique=False)\n\n elif is_object_dtype(target.dtype) or isinstance(target, IntervalIndex):\n # target might contain intervals: defer elementwise to get_loc\n return self._get_indexer_pointwise(target)\n\n else:\n # Note: this case behaves differently from other Index subclasses\n # because IntervalIndex does partial-int indexing\n target = self._maybe_convert_i8(target)\n indexer, missing = self._engine.get_indexer_non_unique(target.values)\n\n return ensure_platform_int(indexer), ensure_platform_int(missing)\n\n def _get_indexer_pointwise(self, target: Index) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n pointwise implementation for get_indexer and get_indexer_non_unique.\n \"\"\"\n indexer, missing = [], []\n for i, key in enumerate(target):\n try:\n locs = self.get_loc(key)\n if isinstance(locs, slice):\n # Only needed for get_indexer_non_unique\n locs = np.arange(locs.start, locs.stop, locs.step, dtype=\"intp\")\n locs = np.array(locs, ndmin=1)\n except KeyError:\n missing.append(i)\n locs = np.array([-1])\n except InvalidIndexError as err:\n # i.e. non-scalar key\n raise TypeError(key) from err\n\n indexer.append(locs)\n\n indexer = np.concatenate(indexer)\n return ensure_platform_int(indexer), ensure_platform_int(missing)\n\n @property\n def _index_as_unique(self):\n return not self.is_overlapping\n\n _requires_unique_msg = (\n \"cannot handle overlapping indices; use IntervalIndex.get_indexer_non_unique\"\n )\n\n def _convert_slice_indexer(self, key: slice, kind: str):\n if not (key.step is None or key.step == 1):\n # GH#31658 if label-based, we require step == 1,\n # if positional, we disallow float start/stop\n msg = \"label-based slicing with step!=1 is not supported for IntervalIndex\"\n if kind == \"loc\":\n raise ValueError(msg)\n elif kind == \"getitem\":\n if not is_valid_positional_slice(key):\n # i.e. this cannot be interpreted as a positional slice\n raise ValueError(msg)\n\n return super()._convert_slice_indexer(key, kind)\n\n def _should_fallback_to_positional(self) -> bool:\n # integer lookups in Series.__getitem__ are unambiguously\n # positional in this case\n return self.dtype.subtype.kind in [\"m\", \"M\"]\n\n def _maybe_cast_slice_bound(self, label, side: str, kind):\n return getattr(self, side)._maybe_cast_slice_bound(label, side, kind)\n\n @Appender(Index._convert_list_indexer.__doc__)\n def _convert_list_indexer(self, keyarr):\n \"\"\"\n we are passed a list-like indexer. Return the\n indexer for matching intervals.\n \"\"\"\n locs = self.get_indexer_for(keyarr)\n\n # we have missing values\n if (locs == -1).any():\n raise KeyError(keyarr[locs == -1].tolist())\n\n return locs\n\n def _is_comparable_dtype(self, dtype: DtypeObj) -> bool:\n if not isinstance(dtype, IntervalDtype):\n return False\n if self.closed != dtype.closed:\n return False\n common_subtype = find_common_type([self.dtype.subtype, dtype.subtype])\n return not is_object_dtype(common_subtype)\n\n # --------------------------------------------------------------------\n\n @cache_readonly\n def left(self) -> Index:\n return Index(self._data.left, copy=False)\n\n @cache_readonly\n def right(self) -> Index:\n return Index(self._data.right, copy=False)\n\n @cache_readonly\n def mid(self):\n return Index(self._data.mid, copy=False)\n\n @property\n def length(self):\n return Index(self._data.length, copy=False)\n\n def putmask(self, mask, value):\n arr = self._data.copy()\n try:\n value_left, value_right = arr._validate_setitem_value(value)\n except (ValueError, TypeError):\n return self.astype(object).putmask(mask, value)\n\n if isinstance(self._data._left, np.ndarray):\n np.putmask(arr._left, mask, value_left)\n np.putmask(arr._right, mask, value_right)\n else:\n # TODO: special case not needed with __array_function__\n arr._left.putmask(mask, value_left)\n arr._right.putmask(mask, value_right)\n return type(self)._simple_new(arr, name=self.name)\n\n @Appender(Index.where.__doc__)\n def where(self, cond, other=None):\n if other is None:\n other = self._na_value\n values = np.where(cond, self._values, other)\n result = IntervalArray(values)\n return type(self)._simple_new(result, name=self.name)\n\n def delete(self, loc):\n \"\"\"\n Return a new IntervalIndex with passed location(-s) deleted\n\n Returns\n -------\n IntervalIndex\n \"\"\"\n new_left = self.left.delete(loc)\n new_right = self.right.delete(loc)\n result = self._data._shallow_copy(new_left, new_right)\n return type(self)._simple_new(result, name=self.name)\n\n def insert(self, loc, item):\n \"\"\"\n Return a new IntervalIndex inserting new item at location. Follows\n Python list.append semantics for negative values. Only Interval\n objects and NA can be inserted into an IntervalIndex\n\n Parameters\n ----------\n loc : int\n item : object\n\n Returns\n -------\n IntervalIndex\n \"\"\"\n left_insert, right_insert = self._data._validate_scalar(item)\n\n new_left = self.left.insert(loc, left_insert)\n new_right = self.right.insert(loc, right_insert)\n result = self._data._shallow_copy(new_left, new_right)\n return type(self)._simple_new(result, name=self.name)\n\n # --------------------------------------------------------------------\n # Rendering Methods\n # __repr__ associated methods are based on MultiIndex\n\n def _format_with_header(self, header: List[str], na_rep: str = \"NaN\") -> List[str]:\n return header + list(self._format_native_types(na_rep=na_rep))\n\n def _format_native_types(self, na_rep=\"NaN\", quoting=None, **kwargs):\n # GH 28210: use base method but with different default na_rep\n return super()._format_native_types(na_rep=na_rep, quoting=quoting, **kwargs)\n\n def _format_data(self, name=None):\n\n # TODO: integrate with categorical and make generic\n # name argument is unused here; just for compat with base / categorical\n n = len(self)\n max_seq_items = min((get_option(\"display.max_seq_items\") or n) // 10, 10)\n\n formatter = str\n\n if n == 0:\n summary = \"[]\"\n elif n == 1:\n first = formatter(self[0])\n summary = f\"[{first}]\"\n elif n == 2:\n first = formatter(self[0])\n last = formatter(self[-1])\n summary = f\"[{first}, {last}]\"\n else:\n\n if n > max_seq_items:\n n = min(max_seq_items // 2, 10)\n head = [formatter(x) for x in self[:n]]\n tail = [formatter(x) for x in self[-n:]]\n head_joined = \", \".join(head)\n tail_joined = \", \".join(tail)\n summary = f\"[{head_joined} ... {tail_joined}]\"\n else:\n tail = [formatter(x) for x in self]\n joined = \", \".join(tail)\n summary = f\"[{joined}]\"\n\n return summary + \",\" + self._format_space()\n\n def _format_attrs(self):\n attrs = []\n if self.name is not None:\n attrs.append((\"name\", default_pprint(self.name)))\n attrs.append((\"dtype\", f\"'{self.dtype}'\"))\n return attrs\n\n def _format_space(self) -> str:\n space = \" \" * (len(type(self).__name__) + 1)\n return f\"\\n{space}\"\n\n # --------------------------------------------------------------------\n # Set Operations\n\n def _intersection(self, other, sort):\n \"\"\"\n intersection specialized to the case with matching dtypes.\n \"\"\"\n # For IntervalIndex we also know other.closed == self.closed\n if self.left.is_unique and self.right.is_unique:\n taken = self._intersection_unique(other)\n elif other.left.is_unique and other.right.is_unique and self.isna().sum() <= 1:\n # Swap other/self if other is unique and self does not have\n # multiple NaNs\n taken = other._intersection_unique(self)\n else:\n # duplicates\n taken = self._intersection_non_unique(other)\n\n if sort is None:\n taken = taken.sort_values()\n\n return taken\n\n def _intersection_unique(self, other: IntervalIndex) -> IntervalIndex:\n \"\"\"\n Used when the IntervalIndex does not have any common endpoint,\n no matter left or right.\n Return the intersection with another IntervalIndex.\n\n Parameters\n ----------\n other : IntervalIndex\n\n Returns\n -------\n IntervalIndex\n \"\"\"\n lindexer = self.left.get_indexer(other.left)\n rindexer = self.right.get_indexer(other.right)\n\n match = (lindexer == rindexer) & (lindexer != -1)\n indexer = lindexer.take(match.nonzero()[0])\n indexer = unique(indexer)\n\n return self.take(indexer)\n\n def _intersection_non_unique(self, other: IntervalIndex) -> IntervalIndex:\n \"\"\"\n Used when the IntervalIndex does have some common endpoints,\n on either sides.\n Return the intersection with another IntervalIndex.\n\n Parameters\n ----------\n other : IntervalIndex\n\n Returns\n -------\n IntervalIndex\n \"\"\"\n mask = np.zeros(len(self), dtype=bool)\n\n if self.hasnans and other.hasnans:\n first_nan_loc = np.arange(len(self))[self.isna()][0]\n mask[first_nan_loc] = True\n\n other_tups = set(zip(other.left, other.right))\n for i, tup in enumerate(zip(self.left, self.right)):\n if tup in other_tups:\n mask[i] = True\n\n return self[mask]\n\n def _setop(op_name: str, sort=None):\n def func(self, other, sort=sort):\n # At this point we are assured\n # isinstance(other, IntervalIndex)\n # other.closed == self.closed\n\n result = getattr(self._multiindex, op_name)(other._multiindex, sort=sort)\n result_name = get_op_result_name(self, other)\n\n # GH 19101: ensure empty results have correct dtype\n if result.empty:\n result = result._values.astype(self.dtype.subtype)\n else:\n result = result._values\n\n return type(self).from_tuples(result, closed=self.closed, name=result_name)\n\n func.__name__ = op_name\n return setop_check(func)\n\n _union = _setop(\"union\")\n _difference = _setop(\"difference\")\n\n # --------------------------------------------------------------------\n\n @property\n def _is_all_dates(self) -> bool:\n \"\"\"\n This is False even when left/right contain datetime-like objects,\n as the check is done on the Interval itself\n \"\"\"\n return False\n\n # TODO: arithmetic operations\n\n\ndef _is_valid_endpoint(endpoint) -> bool:\n \"\"\"\n Helper for interval_range to check if start/end are valid types.\n \"\"\"\n return any(\n [\n is_number(endpoint),\n isinstance(endpoint, Timestamp),\n isinstance(endpoint, Timedelta),\n endpoint is None,\n ]\n )\n\n\ndef _is_type_compatible(a, b) -> bool:\n \"\"\"\n Helper for interval_range to check type compat of start/end/freq.\n \"\"\"\n is_ts_compat = lambda x: isinstance(x, (Timestamp, BaseOffset))\n is_td_compat = lambda x: isinstance(x, (Timedelta, BaseOffset))\n return (\n (is_number(a) and is_number(b))\n or (is_ts_compat(a) and is_ts_compat(b))\n or (is_td_compat(a) and is_td_compat(b))\n or com.any_none(a, b)\n )\n\n\ndef interval_range(\n start=None, end=None, periods=None, freq=None, name=None, closed=\"right\"\n):\n \"\"\"\n Return a fixed frequency IntervalIndex.\n\n Parameters\n ----------\n start : numeric or datetime-like, default None\n Left bound for generating intervals.\n end : numeric or datetime-like, default None\n Right bound for generating intervals.\n periods : int, default None\n Number of periods to generate.\n freq : numeric, str, or DateOffset, default None\n The length of each interval. Must be consistent with the type of start\n and end, e.g. 2 for numeric, or '5H' for datetime-like. Default is 1\n for numeric and 'D' for datetime-like.\n name : str, default None\n Name of the resulting IntervalIndex.\n closed : {'left', 'right', 'both', 'neither'}, default 'right'\n Whether the intervals are closed on the left-side, right-side, both\n or neither.\n\n Returns\n -------\n IntervalIndex\n\n See Also\n --------\n IntervalIndex : An Index of intervals that are all closed on the same side.\n\n Notes\n -----\n Of the four parameters ``start``, ``end``, ``periods``, and ``freq``,\n exactly three must be specified. If ``freq`` is omitted, the resulting\n ``IntervalIndex`` will have ``periods`` linearly spaced elements between\n ``start`` and ``end``, inclusively.\n\n To learn more about datetime-like frequency strings, please see `this link\n <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.\n\n Examples\n --------\n Numeric ``start`` and ``end`` is supported.\n\n >>> pd.interval_range(start=0, end=5)\n IntervalIndex([(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]],\n dtype='interval[int64, right]')\n\n Additionally, datetime-like input is also supported.\n\n >>> pd.interval_range(start=pd.Timestamp('2017-01-01'),\n ... end=pd.Timestamp('2017-01-04'))\n IntervalIndex([(2017-01-01, 2017-01-02], (2017-01-02, 2017-01-03],\n (2017-01-03, 2017-01-04]],\n dtype='interval[datetime64[ns], right]')\n\n The ``freq`` parameter specifies the frequency between the left and right.\n endpoints of the individual intervals within the ``IntervalIndex``. For\n numeric ``start`` and ``end``, the frequency must also be numeric.\n\n >>> pd.interval_range(start=0, periods=4, freq=1.5)\n IntervalIndex([(0.0, 1.5], (1.5, 3.0], (3.0, 4.5], (4.5, 6.0]],\n dtype='interval[float64, right]')\n\n Similarly, for datetime-like ``start`` and ``end``, the frequency must be\n convertible to a DateOffset.\n\n >>> pd.interval_range(start=pd.Timestamp('2017-01-01'),\n ... periods=3, freq='MS')\n IntervalIndex([(2017-01-01, 2017-02-01], (2017-02-01, 2017-03-01],\n (2017-03-01, 2017-04-01]],\n dtype='interval[datetime64[ns], right]')\n\n Specify ``start``, ``end``, and ``periods``; the frequency is generated\n automatically (linearly spaced).\n\n >>> pd.interval_range(start=0, end=6, periods=4)\n IntervalIndex([(0.0, 1.5], (1.5, 3.0], (3.0, 4.5], (4.5, 6.0]],\n dtype='interval[float64, right]')\n\n The ``closed`` parameter specifies which endpoints of the individual\n intervals within the ``IntervalIndex`` are closed.\n\n >>> pd.interval_range(end=5, periods=4, closed='both')\n IntervalIndex([[1, 2], [2, 3], [3, 4], [4, 5]],\n dtype='interval[int64, both]')\n \"\"\"\n start = maybe_box_datetimelike(start)\n end = maybe_box_datetimelike(end)\n endpoint = start if start is not None else end\n\n if freq is None and com.any_none(periods, start, end):\n freq = 1 if is_number(endpoint) else \"D\"\n\n if com.count_not_none(start, end, periods, freq) != 3:\n raise ValueError(\n \"Of the four parameters: start, end, periods, and \"\n \"freq, exactly three must be specified\"\n )\n\n if not _is_valid_endpoint(start):\n raise ValueError(f\"start must be numeric or datetime-like, got {start}\")\n elif not _is_valid_endpoint(end):\n raise ValueError(f\"end must be numeric or datetime-like, got {end}\")\n\n if is_float(periods):\n periods = int(periods)\n elif not is_integer(periods) and periods is not None:\n raise TypeError(f\"periods must be a number, got {periods}\")\n\n if freq is not None and not is_number(freq):\n try:\n freq = to_offset(freq)\n except ValueError as err:\n raise ValueError(\n f\"freq must be numeric or convertible to DateOffset, got {freq}\"\n ) from err\n\n # verify type compatibility\n if not all(\n [\n _is_type_compatible(start, end),\n _is_type_compatible(start, freq),\n _is_type_compatible(end, freq),\n ]\n ):\n raise TypeError(\"start, end, freq need to be type compatible\")\n\n # +1 to convert interval count to breaks count (n breaks = n-1 intervals)\n if periods is not None:\n periods += 1\n\n if is_number(endpoint):\n # force consistency between start/end/freq (lower end if freq skips it)\n if com.all_not_none(start, end, freq):\n end -= (end - start) % freq\n\n # compute the period/start/end if unspecified (at most one)\n if periods is None:\n periods = int((end - start) // freq) + 1\n elif start is None:\n start = end - (periods - 1) * freq\n elif end is None:\n end = start + (periods - 1) * freq\n\n breaks = np.linspace(start, end, periods)\n if all(is_integer(x) for x in com.not_none(start, end, freq)):\n # np.linspace always produces float output\n breaks = maybe_downcast_numeric(breaks, np.dtype(\"int64\"))\n else:\n # delegate to the appropriate range function\n if isinstance(endpoint, Timestamp):\n breaks = date_range(start=start, end=end, periods=periods, freq=freq)\n else:\n breaks = timedelta_range(start=start, end=end, periods=periods, freq=freq)\n\n return IntervalIndex.from_breaks(breaks, name=name, closed=closed)\n" ]
[ [ "numpy.linspace", "pandas.core.dtypes.common.is_dtype_equal", "pandas.core.dtypes.cast.maybe_box_datetimelike", "pandas.core.dtypes.common.is_datetime64tz_dtype", "pandas._libs.interval.IntervalTree", "pandas.core.indexes.base.Index", "numpy.concatenate", "numpy.dtype", "pandas.core.indexes.datetimes.date_range", "pandas._config.get_option", "pandas.core.indexes.timedeltas.timedelta_range", "numpy.where", "numpy.nextafter", "pandas.core.indexes.extension.inherit_names", "pandas._libs.tslibs.to_offset", "pandas.core.dtypes.common.is_interval_dtype", "pandas.core.algorithms.unique", "pandas.core.common.all_not_none", "numpy.arange", "pandas.core.common.not_none", "pandas.core.common.any_none", "pandas.core.indexes.base.maybe_extract_name", "pandas.core.dtypes.common.is_number", "pandas.core.ops.get_op_result_name", "pandas.core.dtypes.common.is_float_dtype", "pandas.core.dtypes.common.is_float", "pandas.core.arrays.interval.IntervalArray", "pandas.util._exceptions.rewrite_exception", "pandas.core.dtypes.common.is_categorical_dtype", "pandas.core.indexes.base.default_pprint", "pandas.core.indexers.is_valid_positional_slice", "pandas.core.dtypes.common.is_integer_dtype", "pandas.core.dtypes.common.is_list_like", "pandas.util._decorators.Appender", "pandas.errors.InvalidIndexError", "numpy.putmask", "pandas.core.dtypes.cast.infer_dtype_from_scalar", "pandas.core.indexes.base.ensure_index", "numpy.timedelta64", "pandas.core.dtypes.common.ensure_platform_int", "pandas.core.arrays.interval.IntervalArray.from_tuples", "numpy.array", "pandas.core.arrays.interval.IntervalArray.from_arrays", "pandas.core.common.count_not_none", "pandas._libs.lib.is_period", "pandas.core.algorithms.take_1d", "pandas.core.dtypes.common.is_scalar", "pandas.core.dtypes.common.is_integer", "pandas.core.dtypes.cast.find_common_type", "pandas.core.indexes.multi.MultiIndex.from_arrays", "pandas.core.dtypes.common.is_object_dtype", "pandas.core.dtypes.common.is_datetime_or_timedelta_dtype", "pandas._libs.interval.IntervalMixin.__new__", "pandas.core.arrays.interval.IntervalArray.from_breaks" ] ]
adamkudrnaty/Sudoku-solver
[ "df9b8be16c21e56125ff9ddbf7b1ec2821f803f8" ]
[ "sudoku-solver.py" ]
[ "import pygame\r\nimport numpy as np\r\n\r\n# Drawing the sudoku grid\r\ndef draw_the_grid():\r\n for row in range(9):\r\n for column in range(9):\r\n color = BLACK\r\n for numbers in range(1,10):\r\n if grid[row][column] == numbers:\r\n number[row][column] = myfont.render(str(numbers), False, (255, 255, 255))\r\n pygame.draw.rect(screen, color,[(MARGIN + WIDTH) * column + MARGIN,(MARGIN + HEIGHT) * row + MARGIN,WIDTH,HEIGHT])\r\n\r\ndef init(array):\r\n sudoku_array = array\r\n class END(Exception): pass\r\n\r\n def xy_to_number(x, y): return sudoku_array[(9*(8-y)+x)]\r\n def xy_to_location(x, y): return (9*(8-y)+x)\r\n def xy_to_location2(y, x): return (9*(y)+x)\r\n\r\n #CHECK IF THE X LINE MEETS THE RULES\r\n def is_in_my_line(x, y, number):\r\n for columns in range(9):\r\n if(columns != y):\r\n if (xy_to_number(x, columns) == number): return True\r\n for rows in range(9):\r\n if(rows != x):\r\n if (xy_to_number(rows, y) == number): return True\r\n return False\r\n\r\n #CHECK IF THE SQUARE MEETS THE RULES\r\n def my_square(puvodx, puvody, number):\r\n if (puvodx/3 < 1): square_x = 0\r\n elif (puvodx/3 >= 2): square_x = 2\r\n else: square_x = 1\r\n\r\n if (puvody/3 < 1): square_y = 0\r\n elif (puvody/3 >= 2): square_y = 2\r\n else: square_y = 1\r\n\r\n for x in range(3*square_x, 3*square_x+3):\r\n for y in range(3*square_y, 3*square_y+3):\r\n if(xy_to_number(x, y) == number): return True\r\n return False\r\n\r\n\r\n #CREATE OPTIONS\r\n def create_options(array):\r\n options = []\r\n alloptions = [1,2,3,4,5,6,7,8,9]\r\n for x in range(len(array)):\r\n if array[x] == 0: options.append(alloptions)\r\n else: options.append(array[x])\r\n return options\r\n\r\n def odstran(number, array):\r\n custom_array = array\r\n if(isinstance(custom_array, list)):\r\n for i in range(len(custom_array)):\r\n if len(custom_array) == 0: return 0\r\n if custom_array[i] == number:\r\n index = [i]\r\n custom_array = np.delete(custom_array, index)\r\n return list(custom_array)\r\n return list(array)\r\n\r\n def check(sudoku_array):\r\n counter = 0\r\n for i in range(len(sudoku_array)):\r\n if(sudoku_array[i] == 0): counter = counter + 1\r\n return counter\r\n\r\n def check_duplicates(array):\r\n if len(array) == len(set(array)): return False \r\n else: return True\r\n\r\n def check_lines(array):\r\n numbers_in_line = []\r\n count_numbers_in_line = 9\r\n for line in range(81):\r\n if array[line] != 0 and len(numbers_in_line) != count_numbers_in_line: numbers_in_line.append(array[line])\r\n elif array[line] == 0 and len(numbers_in_line) != count_numbers_in_line: count_numbers_in_line = count_numbers_in_line - 1\r\n if len(numbers_in_line) == count_numbers_in_line:\r\n if check_duplicates(numbers_in_line) == True: return False\r\n count_numbers_in_line = 9\r\n numbers_in_line = []\r\n return True\r\n\r\n def check_rows(array):\r\n numbers__in_columns = []\r\n amount_of_numbers_in_columns = 9\r\n for line in range(9):\r\n for row in range(9):\r\n if array[9*row+line] != 0 and len(numbers__in_columns) != amount_of_numbers_in_columns: numbers__in_columns.append(array[9*row+line])\r\n elif array[9*row+line] == 0 and len(numbers__in_columns) != amount_of_numbers_in_columns: amount_of_numbers_in_columns = amount_of_numbers_in_columns - 1\r\n if len(numbers__in_columns) == amount_of_numbers_in_columns:\r\n if check_duplicates(numbers__in_columns) == True: return False\r\n amount_of_numbers_in_columns = 9\r\n numbers__in_columns = []\r\n return True\r\n\r\n def check_squares(array):\r\n numbers__in_columns = []\r\n amount_of_numbers_in_columns = 9\r\n for y in range(3):\r\n for x in range(3):\r\n for a in range(3):\r\n for b in range(3):\r\n if array[xy_to_location(a + x*3, b + y*3)] != 0 and len(numbers__in_columns) != amount_of_numbers_in_columns: numbers__in_columns.append(array[xy_to_location(a + x*3, b + y*3)])\r\n elif array[xy_to_location(a + x*3, b + y*3)] == 0 and len(numbers__in_columns) != amount_of_numbers_in_columns: amount_of_numbers_in_columns = amount_of_numbers_in_columns - 1\r\n if len(numbers__in_columns) == amount_of_numbers_in_columns:\r\n if check_duplicates(numbers__in_columns) == True: return False\r\n amount_of_numbers_in_columns = 9\r\n numbers__in_columns = []\r\n return True\r\n\r\n #CHECK IF THE SUDOKU ARRAY DOESN´T BREAK ANY RULES\r\n def check2(array):\r\n if check_rows(array) == True and check_lines(array) == True and check_squares(array) == True: return True\r\n return False\r\n\r\n #DELETE ALL FALSE OPTIONS FOR INDIVIDUAL BOXES\r\n def delete_options(options):\r\n for a in range(9):\r\n for b in range(9):\r\n for c in range(10):\r\n if(xy_to_number(a, b) == 0):\r\n if(is_in_my_line(a,b,c) == True):\r\n position = xy_to_location(a, b)\r\n options[position] = odstran(c, options[position])\r\n elif(my_square(a,b,c) == True):\r\n position = xy_to_location(a, b)\r\n options[position] = odstran(c, options[position])\r\n return options\r\n\r\n def vykresleni_do_sudoku_array(options, sudoku_array):\r\n for a in range(81):\r\n if(isinstance(options[a], list) == True):\r\n if(len(options[a]) == 1): \r\n styl = options[a]\r\n sudoku_array[a] = styl[0]\r\n return sudoku_array\r\n \r\n def draw_sudoku_array(array):\r\n for row in range(9):\r\n for column in range(9):\r\n if array[xy_to_location2(row, column)] != 0:\r\n number[row][column] = myfont.render(str(array[xy_to_location2(row, column)]), False, YELLOW)\r\n screen.blit(number[row][column],(column*50 + 20 + MARGIN*column,row*50 + 10 + MARGIN*row))\r\n pygame.display.flip()\r\n \r\n\r\n predchozi_vysledek = 0\r\n options = create_options(sudoku_array)\r\n\r\n while(check(sudoku_array) > 1):\r\n if predchozi_vysledek == check(sudoku_array): break\r\n predchozi_vysledek = check(sudoku_array)\r\n options = delete_options(options)\r\n sudoku_array = vykresleni_do_sudoku_array(options, sudoku_array)\r\n print(sudoku_array)\r\n draw_the_grid()\r\n draw_sudoku_array(sudoku_array)\r\n\r\n if check(sudoku_array) == 0: print(sudoku_array) #done\r\n else: #backtracking\r\n print(\"NOT COMPLETED YET -> backtracking\")\r\n backtracking_sudoku_array, backup_sudoku_array = (sudoku_array for i in range(2))\r\n backtracking_options, location_backtracking_options, my_options = ([] for i in range(3))\r\n my_position = 0\r\n for i in range(len(options)):\r\n if(isinstance(options[i], list) and len(options[i]) > 1): backtracking_options.append(options[i])\r\n\r\n for i in range(len(backtracking_options)):\r\n backtracking_options[i] = [0] + backtracking_options[i]\r\n my_options.append(0)\r\n \r\n for i in range(len(sudoku_array)):\r\n if(sudoku_array[i] == 0): location_backtracking_options.append(i)\r\n\r\n def backtracking(my_position):\r\n print(backtracking_sudoku_array)\r\n draw_the_grid()\r\n draw_sudoku_array(backtracking_sudoku_array)\r\n if check2(backtracking_sudoku_array) == False:\r\n if my_options[my_position] < len(backtracking_options[my_position]) - 1:\r\n my_options[my_position] += 1\r\n backtracking_sudoku_array[location_backtracking_options[my_position]] = backtracking_options[my_position][my_options[my_position]]\r\n elif my_options[my_position] == len(backtracking_options[my_position]) - 1:\r\n backtracking_sudoku_array[location_backtracking_options[my_position]] = 0\r\n my_options[my_position] = 0\r\n backtracking_sudoku_array[location_backtracking_options[my_position]] = backtracking_options[my_position][my_options[my_position]]\r\n my_position -= 1\r\n is_done = False\r\n while(is_done == False):\r\n if my_options[my_position] < len(backtracking_options[my_position]) - 1:\r\n my_options[my_position] += 1\r\n backtracking_sudoku_array[location_backtracking_options[my_position]] = backtracking_options[my_position][my_options[my_position]]\r\n is_done = True\r\n else:\r\n my_options[my_position] = 0\r\n backtracking_sudoku_array[location_backtracking_options[my_position]] = backtracking_options[my_position][my_options[my_position]]\r\n my_position -= 1\r\n return my_position\r\n else:\r\n if my_options[my_position] == 0:\r\n my_options[my_position] += 1\r\n backtracking_sudoku_array[location_backtracking_options[my_position]] = backtracking_options[my_position][my_options[my_position]]\r\n elif my_position < len(my_options) - 1:\r\n my_position += 1\r\n my_options[my_position] += 1\r\n backtracking_sudoku_array[location_backtracking_options[my_position]] = backtracking_options[my_position][my_options[my_position]]\r\n else:\r\n raise END\r\n return my_position\r\n\r\n try:\r\n while True:\r\n backup_sudoku_array = backtracking_sudoku_array\r\n my_position = backtracking(my_position)\r\n except END: pass\r\n\r\nsudoku_array = []\r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\nYELLOW = (244,175,27)\r\nWIDTH = 50 # WIDTH of each square\r\nHEIGHT = 50 # HEIGHT of each square\r\nMARGIN = 2 # Margin between each cell\r\n \r\n# Create a 2 dimensional array(grid) that we´ll later fill with sudoku numbers #\r\ngrid, number = ([] for i in range(2))\r\n\r\nfor row in range(10):\r\n grid.append([])\r\n number.append([])\r\n for column in range(10):\r\n grid[row].append(0)\r\n number[row].append(0)\r\n\r\ndef erase():\r\n for row in range(10):\r\n for column in range(10):\r\n grid[row][column] = 0\r\n number[row][column] = 0\r\n\r\npygame.init() # Initialize pygame (gui)\r\n\r\npygame.font.init()\r\nmyfont = pygame.font.SysFont('Arial', 30)\r\n\r\nWINDOW_SIZE = [900, 475]\r\nscreen = pygame.display.set_mode(WINDOW_SIZE)\r\npygame.display.set_caption(\"Sudoku solver\")\r\n\r\ndone = False\r\n\r\n# -------- Main Loop until the user clicks the close button----------- #\r\nwhile not done:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT: done = True # Flag that we are done -> we exit this loop\r\n elif event.type == pygame.MOUSEBUTTONDOWN:\r\n # Get the mouse position\r\n pos = pygame.mouse.get_pos()\r\n # Change the x/y screen coordinates to grid coordinates\r\n column = pos[0] // (WIDTH + MARGIN)\r\n row = pos[1] // (HEIGHT + MARGIN)\r\n if column > 9 or row > 9:\r\n if(pos[0] > 600 and pos[0] < 800 and pos[1] < 125 and pos[1] > 50):\r\n # Solve the sudoku\r\n for row in range(9):\r\n for column in range(9):\r\n sudoku_array.append(grid[row][column])\r\n init(sudoku_array)\r\n elif(pos[0] > 600 and pos[0] < 800 and pos[1] < 205 and pos[1] > 130):\r\n # Erase the sudoku board\r\n erase()\r\n sudoku_array = []\r\n elif grid[row][column] == 9:\r\n grid[row][column] = 0\r\n number[row][column] = myfont.render(\"\", False, (255, 255, 255))\r\n screen.blit(number[row][column],(column*50 + 20 + MARGIN*column,row*50 + 10 + MARGIN*row))\r\n else: grid[row][column] += 1\r\n \r\n # Set the screen background\r\n screen.fill(WHITE)\r\n draw_the_grid()\r\n \r\n # Displaying sudoku numbers that we chose\r\n for row in range(9):\r\n for column in range(9):\r\n if number[row][column] != 0: screen.blit(number[row][column],(column*50 + 20 + MARGIN*column,row*50 + 10 + MARGIN*row))\r\n\r\n pygame.draw.rect(screen, BLACK,[600,50,200,75])\r\n pygame.draw.rect(screen, BLACK,[600,130,200,75])\r\n SOLVE = myfont.render(\"SOLVE\", False, YELLOW)\r\n ERASE = myfont.render(\"ERASE\", False, YELLOW)\r\n screen.blit(SOLVE,(650,75))\r\n screen.blit(ERASE,(650,150))\r\n \r\n # Updates the screen\r\n pygame.display.flip()\r\n\r\npygame.quit()\r\n" ]
[ [ "numpy.delete" ] ]
SamuelSchmidgall/RodentNavigation
[ "2ec49c5f43aa456ba648d1117a1b76241ad7a946" ]
[ "gym/gym/envs/mujoco/half_cheetah_hierarchy.py" ]
[ "import numpy as np\nfrom gym import utils\nfrom gym import spaces\nfrom copy import deepcopy\nfrom gym.envs.mujoco import mujoco_env\n\nclass HalfCheetahHierEnv(mujoco_env.MujocoEnv, utils.EzPickle):\n def __init__(self, layer=1, ll_agent=None):\n self.timestep = 0\n self.layer = layer\n self.layer2_itr = 5\n if self.layer == 1:\n self.target_velocity = np.random.uniform(low=-1.0, high=2.5)\n elif self.layer == 2:\n self.ll_agent = ll_agent\n self.target_delta_x_pos = np.random.uniform(low=-20.0, high=50.0)\n self.original_tdxp = deepcopy(self.target_delta_x_pos)\n mujoco_env.MujocoEnv.__init__(self, 'half_cheetah.xml', 1)\n utils.EzPickle.__init__(self)\n\n if self.layer == 2:\n self.action_space = spaces.Box(low=np.array([-1.0]), high=np.array([2.5]), dtype=np.float32)\n\n\n def step(self, action):\n if self.layer == 1:\n x_position_before = self.sim.data.qpos[0]\n self.do_simulation(action, self.frame_skip)\n x_position_after = self.sim.data.qpos[0]\n x_velocity = ((x_position_after - x_position_before)\n / self.dt)\n ob = self._get_obs()\n\n reward_ctrl = - 0.1 * np.square(action).sum()\n reward_vel = -np.abs(x_velocity - self.target_velocity)\n reward = reward_ctrl + reward_vel\n #reward_run = (xposafter - xposbefore)/self.dt\n #reward = reward_ctrl + reward_run\n done = False\n self.timestep += 1\n return ob, reward, done, dict()\n elif self.layer == 2:\n target_v = action\n dist_travelled = -1*self.data.qpos[0]\n for _k in range(self.layer2_itr):\n ll_action = self.ll_agent.select_action(self._get_obs(layer=1, t_vel=np.array([target_v[-1]])))\n self.do_simulation(ll_action, self.frame_skip)\n dist_travelled += self.data.qpos[0]\n self.target_delta_x_pos = self.target_delta_x_pos - dist_travelled\n #reward_ctrl = - 0.1 * np.square(action).sum()\n #reward_vel = -np.abs(x_velocity - self.target_velocity)\n if np.abs(self.original_tdxp) < 0.1:\n surr = 0.1\n else:\n surr = self.original_tdxp\n reward_pos = -np.abs(self.target_delta_x_pos/surr)\n reward = reward_pos #reward_vel\n #reward_run = (xposafter - xposbefore)/self.dt\n #reward = reward_ctrl + reward_run\n ob = self._get_obs(layer=2)\n done = False\n self.timestep += 1\n return ob, reward, done, dict()\n\n def _get_obs(self, layer=None, t_vel=None):\n if layer is None:\n layer = self.layer\n\n if layer == 1:\n if t_vel is not None:\n return np.concatenate([\n self.sim.data.qpos.flat[1:],\n self.sim.data.qvel.flat,\n t_vel\n ])\n return np.concatenate([\n self.sim.data.qpos.flat[1:],\n self.sim.data.qvel.flat,\n np.array([self.target_velocity])\n ])\n elif layer == 2:\n return np.concatenate([\n self.sim.data.qpos.flat[1:],\n self.sim.data.qvel.flat,\n np.array([self.target_delta_x_pos])\n ])\n\n def reset_model(self):\n self.timestep = 0\n if self.layer == 1:\n self.target_velocity = np.random.uniform(low=-1.0, high=2.5)\n elif self.layer == 2:\n self.target_delta_x_pos = np.random.uniform(low=-20.0, high=50.0)\n self.original_tdxp = deepcopy(self.target_delta_x_pos)\n\n qpos = self.init_qpos + self.np_random.uniform(low=-.1, high=.1, size=self.model.nq)\n qvel = self.init_qvel + self.np_random.randn(self.model.nv) * .1\n self.set_state(qpos, qvel)\n obs = self._get_obs()\n return obs\n\n def viewer_setup(self):\n self.viewer.cam.distance = self.model.stat.extent * 0.5\n" ]
[ [ "numpy.square", "numpy.abs", "numpy.concatenate", "numpy.random.uniform", "numpy.array" ] ]
kuldeepbrd1/dopamine
[ "1cbed6c7c35163e73b0ee2f2d2bf032b057570dd" ]
[ "tests/dopamine/jax/agents/rainbow/rainbow_agent_test.py" ]
[ "# coding=utf-8\n# Copyright 2018 The Dopamine Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for dopamine.jax.agents.rainbow.rainbow_agent.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\n\nfrom absl.testing import absltest\nfrom dopamine.discrete_domains import atari_lib\nfrom dopamine.jax.agents.dqn import dqn_agent\nfrom dopamine.jax.agents.rainbow import rainbow_agent\nfrom dopamine.utils import test_utils\nfrom flax import linen\nimport gin\nimport jax\nimport jax.numpy as jnp\nimport numpy as onp\n\n\nclass ProjectDistributionTest(absltest.TestCase):\n\n def _vmapped_projection(self, supports, weights, target_support):\n return jax.vmap(rainbow_agent.project_distribution, in_axes=(0, 0, None))(\n supports, weights, target_support)\n\n def testProjectSingleIdenticalDistribution(self):\n supports = jnp.array([[0, 1, 2, 3, 4]], dtype=jnp.float32)\n expected_weights = [0.1, 0.2, 0.1, 0.3, 0.3]\n weights = jnp.array([expected_weights], dtype=jnp.float32)\n target_support = jnp.array([0, 1, 2, 3, 4], dtype=jnp.float32)\n projection = self._vmapped_projection(supports, weights, target_support)\n onp.testing.assert_allclose([expected_weights], projection)\n\n def testProjectSingleDifferentDistribution(self):\n supports = jnp.array([[0, 1, 2, 3, 4]], dtype=jnp.float32)\n weights = jnp.array([[0.1, 0.2, 0.1, 0.3, 0.3]], dtype=jnp.float32)\n target_support = jnp.array([3, 4, 5, 6, 7], dtype=jnp.float32)\n projection = self._vmapped_projection(supports, weights, target_support)\n expected_projection = [[0.7, 0.3, 0.0, 0.0, 0.0]]\n onp.testing.assert_allclose(expected_projection, projection)\n\n def testProjectFromNonMonotonicSupport(self):\n supports = jnp.array([[4, 3, 2, 1, 0]], dtype=jnp.float32)\n weights = jnp.array([[0.1, 0.2, 0.1, 0.3, 0.3]], dtype=jnp.float32)\n target_support = jnp.array([3, 4, 5, 6, 7], dtype=jnp.float32)\n projection = self._vmapped_projection(supports, weights, target_support)\n expected_projection = [[0.9, 0.1, 0.0, 0.0, 0.0]]\n onp.testing.assert_allclose(expected_projection, projection)\n\n def testExampleFromCodeComments(self):\n supports = jnp.array([[0, 2, 4, 6, 8], [1, 3, 4, 5, 6]], dtype=jnp.float32)\n weights = jnp.array(\n [[0.1, 0.6, 0.1, 0.1, 0.1], [0.1, 0.2, 0.5, 0.1, 0.1]],\n dtype=jnp.float32)\n target_support = jnp.array([4, 5, 6, 7, 8], dtype=jnp.float32)\n projection = self._vmapped_projection(supports, weights, target_support)\n expected_projections = [[0.8, 0.0, 0.1, 0.0, 0.1],\n [0.8, 0.1, 0.1, 0.0, 0.0]]\n onp.testing.assert_allclose(expected_projections, projection)\n\n def testProjectBatchOfDifferentDistributions(self):\n supports = jnp.array(\n [[0, 2, 4, 6, 8], [0, 1, 2, 3, 4], [3, 4, 5, 6, 7]], dtype=jnp.float32)\n weights = jnp.array(\n [[0.1, 0.2, 0.3, 0.2, 0.2], [0.1, 0.2, 0.1, 0.3, 0.3],\n [0.1, 0.2, 0.3, 0.2, 0.2]],\n dtype=jnp.float32)\n target_support = jnp.array([3, 4, 5, 6, 7], dtype=jnp.float32)\n projection = self._vmapped_projection(supports, weights, target_support)\n expected_projections = [[0.3, 0.3, 0.0, 0.2,\n 0.2], [0.7, 0.3, 0.0, 0.0, 0.0],\n [0.1, 0.2, 0.3, 0.2, 0.2]]\n onp.testing.assert_allclose(expected_projections, projection)\n\n def testUsingPlaceholders(self):\n supports = jnp.array([[0, 2, 4, 6, 8], [0, 1, 2, 3, 4], [3, 4, 5, 6, 7]])\n weights = jnp.array([[0.1, 0.2, 0.3, 0.2, 0.2], [0.1, 0.2, 0.1, 0.3, 0.3],\n [0.1, 0.2, 0.3, 0.2, 0.2]])\n target_support = jnp.array([3, 4, 5, 6, 7])\n projection = self._vmapped_projection(supports, weights, target_support)\n expected_projections = [[0.3, 0.3, 0.0, 0.2,\n 0.2], [0.7, 0.3, 0.0, 0.0, 0.0],\n [0.1, 0.2, 0.3, 0.2, 0.2]]\n onp.testing.assert_allclose(expected_projections, projection)\n\n def testProjectBatchOfDifferentDistributionsWithLargerDelta(self):\n supports = jnp.array(\n [[0, 2, 4, 6, 8], [8, 9, 10, 12, 14]], dtype=jnp.float32)\n weights = jnp.array(\n [[0.1, 0.2, 0.2, 0.2, 0.3], [0.1, 0.2, 0.4, 0.1, 0.2]],\n dtype=jnp.float32)\n target_support = jnp.array([0, 4, 8, 12, 16], dtype=jnp.float32)\n projection = self._vmapped_projection(supports, weights, target_support)\n expected_projections = [[0.2, 0.4, 0.4, 0.0, 0.0],\n [0.0, 0.0, 0.45, 0.45, 0.1]]\n onp.testing.assert_allclose(expected_projections, projection)\n\n\nclass RainbowAgentTest(absltest.TestCase):\n\n def setUp(self):\n super(RainbowAgentTest, self).setUp()\n self._num_actions = 4\n self._num_atoms = 5\n self._vmax = 7.\n self._min_replay_history = 32\n self._epsilon_decay_period = 90\n self.observation_shape = dqn_agent.NATURE_DQN_OBSERVATION_SHAPE\n self.observation_dtype = dqn_agent.NATURE_DQN_DTYPE\n self.stack_size = dqn_agent.NATURE_DQN_STACK_SIZE\n self.zero_state = onp.zeros(\n (1,) + self.observation_shape + (self.stack_size,))\n gin.bind_parameter('OutOfGraphPrioritizedReplayBuffer.replay_capacity', 100)\n gin.bind_parameter('OutOfGraphPrioritizedReplayBuffer.batch_size', 2)\n\n def _create_test_agent(self):\n # This dummy network allows us to deterministically anticipate that\n # action 0 will be selected by an argmax.\n\n # In Rainbow we are dealing with a distribution over Q-values,\n # which are represented as num_atoms bins, ranging from -vmax to vmax.\n # The output layer will have num_actions * num_atoms elements,\n # so each group of num_atoms weights represent the logits for a\n # particular action. By setting 1s everywhere, except for the first\n # num_atoms (representing the logits for the first action), which are\n # set to onp.arange(num_atoms), we are ensuring that the first action\n # places higher weight on higher Q-values; this results in the first\n # action being chosen.\n class MockRainbowNetwork(linen.Module):\n \"\"\"Custom Jax network used in tests.\"\"\"\n num_actions: int\n num_atoms: int\n inputs_preprocessed: bool = False\n\n @linen.compact\n def __call__(self, x, support):\n def custom_init(key, shape, dtype=jnp.float32):\n del key\n to_pick_first_action = onp.ones(shape, dtype)\n to_pick_first_action[:, :self.num_atoms] = onp.arange(\n 1, self.num_atoms + 1)\n return to_pick_first_action\n x = x.astype(jnp.float32)\n x = x.reshape((-1)) # flatten\n x = linen.Dense(features=self.num_actions * self.num_atoms,\n kernel_init=custom_init,\n bias_init=linen.initializers.ones)(x)\n logits = x.reshape((self.num_actions, self.num_atoms))\n probabilities = linen.softmax(logits)\n qs = jnp.sum(support * probabilities, axis=1)\n return atari_lib.RainbowNetworkType(qs, logits, probabilities)\n\n agent = rainbow_agent.JaxRainbowAgent(\n network=MockRainbowNetwork,\n num_actions=self._num_actions,\n num_atoms=self._num_atoms,\n vmax=self._vmax,\n min_replay_history=self._min_replay_history,\n epsilon_fn=lambda w, x, y, z: 0.0, # No exploration.\n epsilon_eval=0.0,\n epsilon_decay_period=self._epsilon_decay_period)\n # This ensures non-random action choices (since epsilon_eval = 0.0) and\n # skips the train_step.\n agent.eval_mode = True\n return agent\n\n def testCreateAgentWithDefaults(self):\n # Verifies that we can create and train an agent with the default values.\n agent = rainbow_agent.JaxRainbowAgent(num_actions=4)\n observation = onp.ones([84, 84, 1])\n agent.begin_episode(observation)\n agent.step(reward=1, observation=observation)\n agent.end_episode(reward=1)\n\n def testShapesAndValues(self):\n agent = self._create_test_agent()\n self.assertEqual(agent._support.shape[0], self._num_atoms)\n self.assertEqual(jnp.min(agent._support), -self._vmax)\n self.assertEqual(jnp.max(agent._support), self._vmax)\n state = onp.ones((1, 28224))\n net_output = agent.network_def.apply(agent.online_params, state,\n agent._support)\n self.assertEqual(net_output.logits.shape,\n (self._num_actions, self._num_atoms))\n self.assertEqual(net_output.probabilities.shape,\n net_output.logits.shape)\n self.assertEqual(net_output.logits.shape[0],\n self._num_actions)\n self.assertEqual(net_output.logits.shape[1],\n self._num_atoms)\n self.assertEqual(net_output.q_values.shape,\n (self._num_actions,))\n\n def testBeginEpisode(self):\n \"\"\"Tests the functionality of agent.begin_episode.\n\n Specifically, the action returned and its effect on the state.\n \"\"\"\n agent = self._create_test_agent()\n # We fill up the state with 9s. On calling agent.begin_episode the state\n # should be reset to all 0s.\n agent.state.fill(9)\n first_observation = onp.ones(self.observation_shape + (1,))\n self.assertEqual(agent.begin_episode(first_observation), 0)\n # When the all-1s observation is received, it will be placed at the end of\n # the state.\n expected_state = self.zero_state\n expected_state[:, :, :, -1] = onp.ones((1,) + self.observation_shape)\n onp.array_equal(agent.state, expected_state)\n onp.array_equal(agent._observation, first_observation[:, :, 0])\n # No training happens in eval mode.\n self.assertEqual(agent.training_steps, 0)\n\n # This will now cause training to happen.\n agent.eval_mode = False\n # Having a low replay memory add_count will prevent any of the\n # train/prefetch/sync ops from being called.\n agent._replay.add_count = 0\n second_observation = onp.ones(self.observation_shape + (1,)) * 2\n agent.begin_episode(second_observation)\n # The agent's state will be reset, so we will only be left with the all-2s\n # observation.\n expected_state[:, :, :, -1] = onp.full((1,) + self.observation_shape, 2)\n onp.array_equal(agent.state, expected_state)\n onp.array_equal(agent._observation, second_observation[:, :, 0])\n # training_steps is incremented since we set eval_mode to False.\n self.assertEqual(agent.training_steps, 1)\n\n def testStepEval(self):\n \"\"\"Tests the functionality of agent.step() in eval mode.\n\n Specifically, the action returned, and confirms that no training happens.\n \"\"\"\n agent = self._create_test_agent()\n base_observation = onp.ones(self.observation_shape + (1,))\n # This will reset state and choose a first action.\n agent.begin_episode(base_observation)\n # We mock the replay buffer to verify how the agent interacts with it.\n agent._replay = test_utils.MockReplayBuffer()\n\n expected_state = self.zero_state\n num_steps = 10\n for step in range(1, num_steps + 1):\n # We make observation a multiple of step for testing purposes (to\n # uniquely identify each observation).\n observation = base_observation * step\n self.assertEqual(agent.step(reward=1, observation=observation), 0)\n stack_pos = step - num_steps - 1\n if stack_pos >= -self.stack_size:\n expected_state[:, :, :, stack_pos] = onp.full(\n (1,) + self.observation_shape, step)\n onp.array_equal(agent.state, expected_state)\n onp.array_equal(\n agent._last_observation,\n onp.ones(self.observation_shape) * (num_steps - 1))\n onp.array_equal(agent._observation, observation[:, :, 0])\n # No training happens in eval mode.\n self.assertEqual(agent.training_steps, 0)\n # No transitions are added in eval mode.\n self.assertEqual(agent._replay.add.call_count, 0)\n\n def testStepTrain(self):\n \"\"\"Test the functionality of agent.step() in train mode.\n\n Specifically, the action returned, and confirms training is happening.\n \"\"\"\n agent = self._create_test_agent()\n agent.eval_mode = False\n base_observation = onp.ones(self.observation_shape + (1,))\n # We mock the replay buffer to verify how the agent interacts with it.\n agent._replay = test_utils.MockReplayBuffer(is_jax=True)\n # This will reset state and choose a first action.\n agent.begin_episode(base_observation)\n expected_state = self.zero_state\n num_steps = 10\n for step in range(1, num_steps + 1):\n # We make observation a multiple of step for testing purposes (to\n # uniquely identify each observation).\n observation = base_observation * step\n self.assertEqual(agent.step(reward=1, observation=observation), 0)\n stack_pos = step - num_steps - 1\n if stack_pos >= -self.stack_size:\n expected_state[:, :, :, stack_pos] = onp.full(\n (1,) + self.observation_shape, step)\n onp.array_equal(agent.state, expected_state)\n onp.array_equal(\n agent._last_observation,\n onp.full(self.observation_shape, num_steps - 1))\n onp.array_equal(agent._observation, observation[:, :, 0])\n # We expect one more than num_steps because of the call to begin_episode.\n self.assertEqual(agent.training_steps, num_steps + 1)\n self.assertEqual(agent._replay.add.call_count, num_steps)\n agent.end_episode(reward=1)\n self.assertEqual(agent._replay.add.call_count, num_steps + 1)\n\n def testStoreTransitionWithUniformSampling(self):\n agent = rainbow_agent.JaxRainbowAgent(\n num_actions=4, replay_scheme='uniform')\n dummy_frame = onp.zeros((84, 84))\n # Adding transitions with default, 10., default priorities.\n agent._store_transition(dummy_frame, 0, 0, False)\n agent._store_transition(dummy_frame, 0, 0, False, priority=10.)\n agent._store_transition(dummy_frame, 0, 0, False)\n returned_priorities = agent._replay.get_priority(\n onp.arange(self.stack_size - 1, self.stack_size + 2, dtype=onp.int32))\n expected_priorities = [1., 10., 1.]\n onp.array_equal(returned_priorities, expected_priorities)\n\n def testStoreTransitionWithPrioritizedSamplingy(self):\n agent = rainbow_agent.JaxRainbowAgent(\n num_actions=4, replay_scheme='prioritized')\n dummy_frame = onp.zeros((84, 84))\n # Adding transitions with default, 10., default priorities.\n agent._store_transition(dummy_frame, 0, 0, False)\n agent._store_transition(dummy_frame, 0, 0, False, priority=10.)\n agent._store_transition(dummy_frame, 0, 0, False)\n returned_priorities = agent._replay.get_priority(\n onp.arange(self.stack_size - 1, self.stack_size + 2, dtype=onp.int32))\n expected_priorities = [1., 10., 10.]\n onp.array_equal(returned_priorities, expected_priorities)\n\n\nif __name__ == '__main__':\n absltest.main()\n" ]
[ [ "numpy.array_equal", "numpy.arange", "numpy.ones", "numpy.full", "numpy.testing.assert_allclose", "numpy.zeros" ] ]
kantologist/multiagent-sac
[ "212e04b19f2becf2e37d9270242b1c59542d8d9f" ]
[ "agents/dqn_agent.py" ]
[ "\"\"\" Packaged MASAC\"\"\"\nfrom typing import Dict, List, Tuple\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom unityagents import UnityEnvironment\nfrom buffers.buffer import ReplayBuffer\nfrom models.network import Network\nfrom torch.nn.utils.clip_grad import clip_grad_norm_\n\nclass DQNAgent:\n\n def __init__(\n self,\n env: UnityEnvironment,\n memory_size: int,\n batch_size: int,\n target_update: int,\n epsilon_decay: float = 1 / 2000,\n max_epsilon: float = 1.0,\n min_epsilon: float = 0.1,\n gamma: float = 0.99,\n ):\n self.brain_name = env.brain_names[0]\n self.brain = env.brains[self.brain_name]\n env_info = env.reset(train_mode=True)[self.brain_name]\n self.env = env\n action_size = self.brain.vector_action_space_size\n state = env_info.vector_observations[0]\n state_size = len(state)\n \n self.obs_dim = state_size\n self.action_dim = 1\n\n self.memory = ReplayBuffer(self.obs_dim, self.action_dim, memory_size, batch_size)\n\n\n self.batch_size = batch_size\n self.target_update = target_update\n self.epsilon_decay = epsilon_decay\n self.max_epsilon = max_epsilon\n self.min_epsilon = min_epsilon\n self.gamma = gamma\n self.epsilon = max_epsilon\n\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n \n self.dqn = Network(self.obs_dim, self.action_dim)\n self.dqn_target = Network(self.obs_dim, self.action_dim)\n self.dqn_target.load_state_dict(self.dqn.state_dict())\n self.dqn_target.eval()\n\n self.optimizer = optim.Adam(self.dqn.parameters(), lr=5e-5)\n\n self.transition = list()\n\n self.is_test = False\n\n def select_action(self, state: np.ndarray) -> np.int64:\n \"\"\" Select an action given input \"\"\"\n if self.epsilon > np.random.random():\n selected_action = np.random.random_integers(0, self.action_dim-1)\n else:\n selected_action = self.dqn(\n torch.FloatTensor(state).to(self.device)\n )\n selected_action = np.argmax(selected_action.detach().cpu().numpy())\n\n \n if not self.is_test:\n self.transition = [state, selected_action]\n \n return selected_action\n\n def step(self, action: np.int64) -> Tuple[np.ndarray, np.float64, bool]:\n \"Take an action and return environment response\"\n env_info = self.env.step(action)[self.brain_name]\n next_state = env_info.vector_observations[0] \n reward = env_info.rewards[0] \n done = env_info.local_done[0]\n \n if not self.is_test:\n self.transition += [reward, next_state, done]\n self.memory.store(*self.transition)\n\n return next_state, reward, done\n\n def update_model(self) -> torch.Tensor:\n \"\"\" Update model by gradient descent\"\"\"\n samples = self.memory.sample_batch()\n loss = self._compute_dqn_loss(samples)\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n return loss.item()\n\n def train(self, num_episode: int, max_iteration: int=1000, plotting_interval: int=400):\n \"\"\" train the agent \"\"\"\n self.is_test = False\n\n env_info = self.env.reset(train_mode=True)[self.brain_name]\n state = env_info.vector_observations[0]\n\n update_cnt = 0\n epsilons = []\n losses = []\n avg_losses= []\n scores = []\n avg_scores = []\n\n for episode in range(num_episode):\n env_info = self.env.reset(train_mode=True)[self.brain_name]\n state = env_info.vector_observations[0]\n score = 0\n for iter in range(max_iteration):\n action = self.select_action(state)\n next_state, reward, done = self.step(action)\n state = next_state\n score += reward\n if done:\n break\n\n if len(self.memory) > self.batch_size:\n loss = self.update_model()\n losses.append(loss)\n update_cnt += 1\n\n avg_losses.append(np.mean(losses))\n losses = []\n self.epsilon = max(\n self.min_epsilon, self.epsilon - (\n self.max_epsilon - self.min_epsilon\n ) * self.epsilon_decay\n )\n epsilons.append(self.epsilon)\n \n if update_cnt % self.target_update == 0:\n self._target_hard_update()\n scores.append(score)\n epsilons.append(self.epsilon)\n\n if episode >= 100:\n avg_scores.append(np.mean(scores[-100:]))\n self._plot(episode, scores, avg_scores, avg_losses, epsilons)\n torch.save(self.dqn.state_dict(), \"model_weight/dqn.pt\")\n\n\n\n def test(self):\n \"\"\" Test agent \"\"\"\n self.is_test = True\n env_info = self.env.reset(train_mode=False)[self.brain_name]\n state = env_info.vector_observations[0]\n done = False\n score = 0\n\n while not done:\n action = self.select_action(state)\n next_state, reward, done = self.step(action)\n\n state = next_state\n score += reward\n\n print(\"score: \", score)\n self.env.close()\n\n\n def _compute_dqn_loss(self, samples: Dict[str, np.ndarray], gamma: float=0.99) -> torch.Tensor:\n \"\"\" Compute and return DQN loss\"\"\"\n gamma = self.gamma\n device = self.device\n state = torch.FloatTensor(samples[\"obs\"]).to(device)\n next_state = torch.FloatTensor(samples[\"next_obs\"]).to(device)\n action = torch.LongTensor(samples[\"acts\"]).reshape(-1, 1).to(device)\n reward = torch.FloatTensor(samples[\"rews\"]).reshape(-1, 1).to(device)\n done = torch.FloatTensor(samples[\"done\"]).reshape(-1, 1).to(device)\n \n curr_q_value = self.dqn(state).gather(1, action)\n \n next_q_value = self.dqn_target(next_state).max(dim=1, keepdim=True)[0].detach()\n mask = 1 - done\n target = (reward + gamma * next_q_value * mask).to(device)\n loss = F.smooth_l1_loss(curr_q_value, target)\n\n return loss\n\n\n def _target_hard_update(self):\n \"\"\" update target network \"\"\"\n self.dqn_target.load_state_dict(self.dqn.state_dict())\n\n def _plot(\n self,\n episode :int,\n scores: List[float],\n avg_scores: List[float],\n losses: List[float],\n epsilons: List[float]\n ):\n \"\"\" Plot the training process\"\"\"\n plt.figure(figsize=(20, 5))\n plt.subplot(141)\n if len(avg_scores) > 0:\n plt.title(\"Average reward per 100 episodes. Score: %s\" % (avg_scores[-1]))\n else:\n plt.title(\"Average reward over 100 episodes.\")\n plt.plot([100 + i for i in range(len(avg_scores))], avg_scores)\n plt.subplot(142)\n plt.title(\"episode %s. Score: %s\" % (episode, np.mean(scores[-10:])))\n plt.plot(scores)\n plt.subplot(143)\n plt.title('Loss')\n plt.plot(losses)\n plt.subplot(144)\n plt.title('epsilons')\n plt.plot(epsilons)\n plt.savefig('plots/dqn_result.png')\n" ]
[ [ "torch.LongTensor", "numpy.random.random", "matplotlib.pyplot.title", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "matplotlib.pyplot.subplot", "numpy.random.random_integers", "numpy.mean", "torch.nn.functional.smooth_l1_loss", "torch.cuda.is_available", "torch.FloatTensor", "matplotlib.pyplot.figure" ] ]
kun-1010/1
[ "c7f251bd254c29e3cb53bb915e69f4e00f00cb30" ]
[ "CNN/trained_model_test.py" ]
[ "import torch\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader\nfrom model import CNN\nfrom my_dataset import MyMnistDataset\n\ntransform = transforms.Compose([\n transforms.Resize([28, 28]),\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n])\n\n# 载入自己的数据集\ndataset = MyMnistDataset(root='../my_mnist_dateset', transform=transform)\ntest_loader = DataLoader(dataset=dataset, shuffle=False)\n\n# 生成卷积神经网络并载入训练好的模型\nmodel = CNN()\nmodel.load_state_dict(torch.load(\"cnn_trained_model.pth\"))\n\n\ndef test():\n correct = 0\n total = 0\n print(\"label predicted\")\n with torch.no_grad():\n for data in test_loader:\n images, labels = data\n outputs = model(images)\n _, predicted = torch.max(outputs.data, dim=1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n print(\"{} {}\".format(int(labels.item()), predicted.data.item()))\n\n print('CNN trained model: accuracy on my_mnist_dataset set:%d %%' % (100 * correct / total))\n\n\nif __name__ == '__main__':\n test()\n" ]
[ [ "torch.no_grad", "torch.utils.data.DataLoader", "torch.max", "torch.load" ] ]
AvivSham/SRGAN-Keras_Implementation
[ "f4a9dc15d34575245e28b693ac5db9faf7b6aa08" ]
[ "models/SRGAN.py" ]
[ "from tqdm import tqdm as tqdm\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.models import Input, Model\nfrom keras.layers import BatchNormalization, LeakyReLU, Conv2D, Dense, \\\n Flatten, Add, PReLU, Conv2DTranspose, Lambda, UpSampling2D\nfrom keras.optimizers import Adam\nfrom keras.applications import VGG19\nfrom keras.callbacks import ReduceLROnPlateau\nimport tensorflow as tf\n\n\nclass SRGAN():\n # Implementation of SRGAN from paper:\n # https://arxiv.org/abs/1609.04802\n def __init__(self, high_reso_imgs, low_reso_imgs, lr_height=64, lr_width=64, channels=3,\n upscale_factor=4, generator_lr=1e-4, discriminator_lr=1e-4, gan_lr=1e-4):\n self.high_reso_imgs = high_reso_imgs\n self.low_reso_imgs = low_reso_imgs\n self.height_low_reso = lr_height\n self.width_low_reso = lr_width\n\n if upscale_factor % 2 != 0:\n raise ValueError('Upscale factor is invalid, must be product of 2')\n\n self.upscale_factor = upscale_factor\n self.height_high_reso = self.height_low_reso * self.upscale_factor\n self.width_high_reso = self.width_low_reso * self.upscale_factor\n\n self.channels = channels\n self.shape_low_reso = (self.height_low_reso, self.width_low_reso, self.channels)\n self.shape_high_reso = (self.height_high_reso, self.width_high_reso, self.channels)\n\n self.samples = high_reso_imgs.shape[0]\n\n opti_generator = Adam(generator_lr, 0.9)\n opti_discriminator = Adam(discriminator_lr, 0.9)\n opti_gan = Adam(gan_lr, 0.9)\n\n self.vgg = self.bulid_vgg()\n\n self.discriminator = self.build_discriminator(opti_discriminator)\n self.discriminator.trainable = False\n self.generator = self.build_generator(opti_generator)\n self.srgan = self.build_srgan(opti_gan)\n\n def save_GAN_Model(self, epoch):\n self.srgan.save_weights('srgan_weights_epoch_%d.h5' % epoch)\n\n def plotLosses(self, dlosses, glosses, epo):\n fig, ax1 = plt.subplots(figsize=(10, 12))\n color = 'tab:blue'\n ax1.plot(dlosses, color=color, label='Dis loss')\n ax1.set_xlabel('Epoch')\n ax1.set_ylabel('Dis loss', color=color)\n ax1.tick_params('y', color=color)\n color = 'tab:green'\n ax2 = ax1.twinx()\n ax2.plot(glosses, color=color, label='Gen loss')\n ax2.set_ylabel('Gen loss', color=color)\n ax2.tick_params('y', color=color)\n plt.title('Discriminator & Generator Losses')\n plt.savefig('Losses_%d.png' % epo)\n plt.show()\n\n def gen_pipeline(self, batch_size=16):\n while (1):\n indx_high = np.random.randint(0, self.high_reso_imgs.shape[0] - 1, batch_size)\n\n indx_low = np.random.randint(0, self.low_reso_imgs.shape[0] - 1, batch_size)\n\n real = np.ones((batch_size,) + self.discriminator.output_shape[1:])\n\n fake = np.zeros((batch_size,) + self.discriminator.output_shape[1:])\n\n norm_hr = self.high_reso_imgs[indx_high] / 127.5 - 1\n norm_lr = self.low_reso_imgs[indx_low] / 127.5 - 1\n yield (norm_hr, real, norm_lr, fake)\n\n def vgg_pipeline(self, batch_size=16):\n while (1):\n indx = np.random.randint(0, self.high_reso_imgs.shape[0] - 1, batch_size)\n real = np.ones((batch_size,) + self.discriminator.output_shape[1:])\n norm_hr = self.high_reso_imgs[indx] / 127.5 - 1\n norm_lr = self.low_reso_imgs[indx] / 127.5 - 1\n yield (norm_hr, norm_lr, real)\n\n def bulid_vgg(self):\n vgg = VGG19(weights=\"imagenet\")\n # vgg.summary()\n vgg.outputs = [vgg.layers[9].output]\n img = Input(shape=self.shape_high_reso)\n img_features = vgg(img)\n vgg_model = Model(img, img_features)\n # for layer in vgg_model.layers:\n # layer.trainable = False\n vgg_model.compile(loss='mse', optimizer=Adam(0.0002, 0.5),\n metrics=['acc'])\n return vgg_model\n\n def residual_block(self, input_layer):\n x = Conv2D(filters=64, kernel_size=3, padding='same')(input_layer)\n x = BatchNormalization(momentum=0.8)(x)\n x = PReLU()(x)\n x = Conv2D(filters=64, kernel_size=3, padding='same')(x)\n x = BatchNormalization(momentum=0.8)(x)\n return Add()([input_layer, x])\n\n def disc_block(self, layer, n_filters, batch_norm=True):\n x = Conv2D(filters=n_filters, kernel_size=3, padding='same')(layer)\n if batch_norm:\n x = BatchNormalization(momentum=0.8)(x)\n x = LeakyReLU(alpha=0.2)(x)\n x = Conv2D(filters=n_filters, kernel_size=3,\n strides=2, padding='same')(x)\n x = BatchNormalization(momentum=0.8)(x)\n x = LeakyReLU(alpha=0.2)(x)\n return x\n\n def Upsample_Block(self, x_in):\n x = Conv2D(filters=256, kernel_size=3, padding='same')(x_in)\n x = self.SubpixelConv2D(2)(x)\n return PReLU()(x)\n\n def SubpixelConv2D(self, scale):\n return Lambda(lambda x: tf.depth_to_space(x, scale))\n\n def build_generator(self, opti_generator, n_blocks=16):\n input_layer = Input(self.shape_low_reso)\n\n first_layer = Conv2D(filters=64, kernel_size=9,\n padding='same')(input_layer)\n\n first_layer = PReLU()(first_layer)\n\n residual_blocks = self.residual_block(first_layer)\n\n for _ in range(n_blocks - 1):\n residual_blocks = self.residual_block(residual_blocks)\n\n output_residual = Conv2D(filters=64, kernel_size=3,\n padding='same')(residual_blocks)\n\n output_residual = BatchNormalization(momentum=0.8)(output_residual)\n\n output_residual = Add()([output_residual, first_layer])\n\n upsample_layer = self.Upsample_Block(output_residual)\n\n for _ in range(self.upscale_factor // 2 - 1):\n upsample_layer = self.Upsample_Block(upsample_layer)\n\n gen_output = Conv2D(filters=3, kernel_size=9,\n padding='same', activation='tanh')(upsample_layer)\n\n gen_model = Model(inputs=input_layer, outputs=gen_output)\n gen_model.compile(loss='binary_crossentropy', optimizer=opti_generator)\n\n return gen_model\n\n def build_discriminator(self, opti_discriminator, n_blocks=3, n_filters=64):\n input_layer = Input(self.shape_high_reso)\n discriminator_blocks = self.disc_block(input_layer, n_filters, False)\n for i in range(n_blocks):\n discriminator_blocks = self.disc_block(discriminator_blocks,\n n_filters=(i + 1) * 2 * n_filters)\n\n # f_layer = GlobalAveragePooling2D()(discriminator_blocks)\n f_layer = Dense(units=1024)(discriminator_blocks)\n f_layer = LeakyReLU(alpha=0.2)(f_layer)\n dis_output = Dense(units=1, activation='sigmoid')(f_layer)\n disc_model = Model(inputs=input_layer, outputs=dis_output)\n disc_model.compile(loss='mse', optimizer=opti_discriminator,\n metrics=['accuracy'])\n\n return disc_model\n\n def build_srgan(self, optimizer):\n dis_input = Input(self.shape_high_reso)\n gen_input = Input(self.shape_low_reso)\n\n generated_high_reso = self.generator(gen_input)\n generated_features = self.vgg(generated_high_reso)\n generator_valid = self.discriminator(generated_high_reso)\n\n gan_model = Model(inputs=[gen_input, dis_input],\n outputs=[generator_valid, generated_features])\n\n for l in gan_model.layers[-1].layers[-1].layers:\n l.trainable = False\n\n gan_model.compile(loss=['binary_crossentropy', 'mse'], loss_weights=[1e-2, 1], optimizer='adam')\n gan_model.summary()\n\n return gan_model\n\n def train(self, epochs, save_interval=100, batch_size=16):\n pipeline = self.gen_pipeline(batch_size)\n vgg_pipeline = self.vgg_pipeline(batch_size)\n\n batch_count = self.samples // batch_size\n dlosses = []\n glosses = []\n for epo in range(1, epochs + 1):\n print('-' * 15, 'Epoch %d' % epo, '-' * 15)\n for _ in tqdm(range(batch_count)):\n ##########################\n\n # Train the Discriminator\n\n ##########################\n\n # Generate Batch\n hr_imgs, real, lr_imgs, fake = next(pipeline)\n\n # Generate high resolution photos from low resolution photos\n generated_hr_imags = self.generator.predict(lr_imgs)\n\n # Train the discriminator \n real_dis_loss = self.discriminator.train_on_batch(hr_imgs, real)\n fake_dis_loss = self.discriminator.train_on_batch(generated_hr_imags, fake)\n dis_loss = (0.5 * np.add(real_dis_loss, fake_dis_loss))\n\n ##########################\n\n # Train the Generator\n\n ##########################\n\n # Generate Batch\n hr_imgs, lr_imgs, real = next(vgg_pipeline)\n\n # Extract ground truth using VGG model\n img_features = self.vgg.predict(hr_imgs)\n\n gan_loss = self.srgan.train_on_batch([lr_imgs, hr_imgs], [real, img_features])\n\n if epo % save_interval == 0:\n self.save_GAN_Model(epo)\n self.plotLosses(dlosses, glosses, epo)\n dlosses.append(gan_loss[1])\n glosses.append(gan_loss[0])\n print('\\n', dlosses[-1], glosses[-1])\n" ]
[ [ "tensorflow.depth_to_space", "matplotlib.pyplot.title", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig", "numpy.ones", "numpy.add", "matplotlib.pyplot.show", "numpy.zeros", "numpy.random.randint" ] ]
huguesdevimeux/trytravis-manim
[ "40498759efc089246b6c46717223e55757488d03" ]
[ "manim/scene/scene.py" ]
[ "import inspect\nimport random\nimport warnings\nimport platform\n\nfrom tqdm import tqdm as ProgressDisplay\nimport numpy as np\n\nfrom ..animation.animation import Animation\nfrom ..animation.transform import MoveToTarget, ApplyMethod\nfrom ..camera.camera import Camera\nfrom ..constants import *\nfrom ..config import camera_config, file_writer_config\nfrom ..container.container import Container\nfrom ..logger import logger\nfrom ..mobject.mobject import Mobject\nfrom ..scene.scene_file_writer import SceneFileWriter\nfrom ..utils.iterables import list_update\n\n\nclass Scene(Container):\n \"\"\"\n A Scene can be thought of as the Canvas of your animation.\n All of your own named Scenes will be subclasses of this Scene, or\n other named scenes.\n\n Use a construct() function to tell Manim what should go on in the Scene.\n\n E.G:\n\n class MyScene(Scene):\n def construct(self):\n self.play(\n Write(Text(\"Hello World!\"))\n )\n\n Some important variables to note are:\n camera: The camera object to be used for the scene.\n file_writer : The object that writes the animations in the scene to a video file.\n mobjects : The list of mobjects present in the scene.\n foreground_mobjects : List of mobjects explicitly in the foreground.\n num_plays : Number of play() functions in the scene.\n time: time elapsed since initialisation of scene.\n random_seed: The seed with which all random operations are done.\n \"\"\"\n CONFIG = {\n \"camera_class\": Camera,\n \"skip_animations\": False,\n \"always_update_mobjects\": False,\n \"random_seed\": 0,\n }\n\n def __init__(self, **kwargs):\n Container.__init__(self, **kwargs)\n self.camera = self.camera_class(**camera_config)\n self.file_writer = SceneFileWriter(\n self, **file_writer_config,\n )\n\n self.mobjects = []\n # TODO, remove need for foreground mobjects\n self.foreground_mobjects = []\n self.num_plays = 0\n self.time = 0\n self.original_skipping_status = file_writer_config['skip_animations']\n if self.random_seed is not None:\n random.seed(self.random_seed)\n np.random.seed(self.random_seed)\n\n self.setup()\n try:\n self.construct()\n except EndSceneEarlyException:\n pass\n self.tear_down()\n self.file_writer.finish()\n self.print_end_message()\n\n def setup(self):\n \"\"\"\n This is meant to be implemented by any scenes which\n are comonly subclassed, and have some common setup\n involved before the construct method is called.\n \"\"\"\n pass\n\n def tear_down(self):\n \"\"\"\n This is meant to be implemented by any scenes which\n are comonly subclassed, and have some common method\n to be invoked before the scene ends.\n \"\"\"\n pass\n\n def construct(self):\n \"\"\"\n The primary method for constructing (i.e adding content to)\n the Scene.\n \"\"\"\n pass # To be implemented in subclasses\n\n def __str__(self):\n return self.__class__.__name__\n\n def print_end_message(self):\n \"\"\"\n Used internally to print the number of\n animations played after the scene ends.\n \"\"\"\n logger.info(\"Played {} animations\".format(self.num_plays))\n\n def set_variables_as_attrs(self, *objects, **newly_named_objects):\n \"\"\"\n This method is slightly hacky, making it a little easier\n for certain methods (typically subroutines of construct)\n to share local variables.\n \"\"\"\n caller_locals = inspect.currentframe().f_back.f_locals\n for key, value in list(caller_locals.items()):\n for o in objects:\n if value is o:\n setattr(self, key, value)\n for key, value in list(newly_named_objects.items()):\n setattr(self, key, value)\n return self\n\n def get_attrs(self, *keys):\n \"\"\"\n Gets attributes of a scene given the attribute's identifier/name.\n\n Parameters\n ----------\n *keys : str\n Name(s) of the argument(s) to return the attribute of.\n\n Returns\n -------\n list\n List of attributes of the passed identifiers.\n \"\"\"\n return [getattr(self, key) for key in keys]\n\n # Only these methods should touch the camera\n def set_camera(self, camera):\n \"\"\"\n Sets the scene's camera to be the passed Camera Object.\n\n Parameters\n ----------\n camera : Camera\n The camera object to use.\n \"\"\"\n self.camera = camera\n\n def get_frame(self):\n \"\"\"\n Gets the current frame as NumPy array.\n\n Returns\n -------\n np.array\n NumPy array of pixel values of each pixel in screen.\n The shape of the array is height x width x 3\n \"\"\"\n return np.array(self.camera.get_pixel_array())\n\n def get_image(self):\n \"\"\"\n Gets current frame as PIL Image\n\n Returns\n -------\n PIL.Image\n PIL Image object of current frame.\n \"\"\"\n return self.camera.get_image()\n\n def set_camera_pixel_array(self, pixel_array):\n \"\"\"\n Sets the camera's pixel array to the passed pixel\n array. Does not impact what the scene currently displays.\n\n Parameters\n ----------\n pixel_array: Union[np.ndarray,list,tuple]\n Pixel array\n \"\"\"\n self.camera.set_pixel_array(pixel_array)\n\n def set_camera_background(self, background):\n \"\"\"\n Sets the camera to display a Pixel Array\n in the background.\n\n Parameters\n ----------\n background: Union[np.ndarray,list,tuple]\n The Pixel Array of the background.\n \"\"\"\n self.camera.set_background(background)\n\n def reset_camera(self):\n \"\"\"\n Resets the Camera to its original configuration.\n \"\"\"\n self.camera.reset()\n\n def capture_mobjects_in_camera(self, mobjects, **kwargs): #TODO Add more detail to docstring.\n \"\"\"\n This method is used internally.\n \"\"\"\n self.camera.capture_mobjects(mobjects, **kwargs)\n\n def update_frame( #TODO Description in Docstring\n self,\n mobjects=None,\n background=None,\n include_submobjects=True,\n ignore_skipping=True,\n **kwargs):\n \"\"\"\n Parameters:\n -----------\n mobjects: list, optional\n list of mobjects\n\n background: np.ndarray, optional\n Pixel Array for Background.\n\n include_submobjects: bool, optional\n\n ignore_skipping : bool, optional\n\n **kwargs\n\n \"\"\"\n if file_writer_config['skip_animations'] and not ignore_skipping:\n return\n if mobjects is None:\n mobjects = list_update(\n self.mobjects,\n self.foreground_mobjects,\n )\n if background is not None:\n self.set_camera_pixel_array(background)\n else:\n self.reset_camera()\n\n kwargs[\"include_submobjects\"] = include_submobjects\n self.capture_mobjects_in_camera(mobjects, **kwargs)\n\n def freeze_background(self):\n self.update_frame()\n self.set_camera(Camera(self.get_frame()))\n self.clear()\n ###\n\n def update_mobjects(self, dt):\n \"\"\"\n Begins updating all mobjects in the Scene.\n\n Parameters\n ----------\n dt: int or float\n Change in time between updates. Defaults (mostly) to 1/frames_per_second\n \"\"\"\n for mobject in self.mobjects:\n mobject.update(dt)\n\n def should_update_mobjects(self):\n \"\"\"\n Returns True if any mobject in Scene is being updated\n or if the scene has always_update_mobjects set to true.\n\n Returns\n -------\n bool\n \"\"\"\n return self.always_update_mobjects or any([\n mob.has_time_based_updater()\n for mob in self.get_mobject_family_members()\n ])\n\n ###\n\n def get_time(self):\n \"\"\"\n Returns time in seconds elapsed after initialisation of scene\n\n Returns\n -------\n self.time : float\n Returns time in seconds elapsed after initialisation of scene\n \"\"\"\n return self.time\n\n def increment_time(self, d_time):\n \"\"\"\n Increments the time elapsed after intialisation of scene by\n passed \"d_time\".\n\n Parameters\n ----------\n d_time : int or float\n Time in seconds to increment by.\n \"\"\"\n self.time += d_time\n\n ###\n\n def get_top_level_mobjects(self):\n \"\"\"\n Returns all mobjects which are not submobjects.\n\n Returns\n -------\n list\n List of top level mobjects.\n \"\"\"\n # Return only those which are not in the family\n # of another mobject from the scene\n mobjects = self.get_mobjects()\n families = [m.get_family() for m in mobjects]\n\n def is_top_level(mobject):\n num_families = sum([\n (mobject in family)\n for family in families\n ])\n return num_families == 1\n return list(filter(is_top_level, mobjects))\n\n def get_mobject_family_members(self):\n \"\"\"\n Returns list of family-members of all mobjects in scene.\n If a Circle() and a VGroup(Rectangle(),Triangle()) were added,\n it returns not only the Circle(), Rectangle() and Triangle(), but\n also the VGroup() object.\n\n Returns\n -------\n list\n List of mobject family members.\n \"\"\"\n return self.camera.extract_mobject_family_members(self.mobjects)\n\n def add(self, *mobjects):\n \"\"\"\n Mobjects will be displayed, from background to\n foreground in the order with which they are added.\n\n Parameters\n ---------\n *mobjects : Mobject\n Mobjects to add.\n\n Returns\n -------\n Scene\n The same scene after adding the Mobjects in.\n\n \"\"\"\n mobjects = [*mobjects, *self.foreground_mobjects]\n self.restructure_mobjects(to_remove=mobjects)\n self.mobjects += mobjects\n return self\n\n def add_mobjects_among(self, values):\n \"\"\"\n This is meant mostly for quick prototyping,\n e.g. to add all mobjects defined up to a point,\n call self.add_mobjects_among(locals().values())\n \"\"\"\n self.add(*filter(\n lambda m: isinstance(m, Mobject),\n values\n ))\n return self\n\n def remove(self, *mobjects):\n \"\"\"\n Removes mobjects in the passed list of mobjects\n from the scene and the foreground, by removing them\n from \"mobjects\" and \"foreground_mobjects\"\n\n Parameters\n ----------\n *mobjects : Mobject\n The mobjects to remove.\n \"\"\"\n for list_name in \"mobjects\", \"foreground_mobjects\":\n self.restructure_mobjects(mobjects, list_name, False)\n return self\n\n def restructure_mobjects(self, to_remove,\n mobject_list_name=\"mobjects\",\n extract_families=True):\n \"\"\"\n tl:wr\n If your scene has a Group(), and you removed a mobject from the Group,\n this dissolves the group and puts the rest of the mobjects directly\n in self.mobjects or self.foreground_mobjects.\n\n In cases where the scene contains a group, e.g. Group(m1, m2, m3), but one\n of its submobjects is removed, e.g. scene.remove(m1), the list of mobjects\n will be edited to contain other submobjects, but not m1, e.g. it will now\n insert m2 and m3 to where the group once was.\n\n Parameters\n ----------\n to_remove : Mobject\n The Mobject to remove.\n\n mobject_list_name : str, optional\n The list of mobjects (\"mobjects\", \"foreground_mobjects\" etc) to remove from.\n\n extract_families : bool, optional\n Whether the mobject's families should be recursively extracted.\n\n Returns\n -------\n Scene\n The Scene mobject with restructured Mobjects.\n \"\"\"\n if extract_families:\n to_remove = self.camera.extract_mobject_family_members(to_remove)\n _list = getattr(self, mobject_list_name)\n new_list = self.get_restructured_mobject_list(_list, to_remove)\n setattr(self, mobject_list_name, new_list)\n return self\n\n def get_restructured_mobject_list(self, mobjects, to_remove):\n \"\"\"\n Given a list of mobjects and a list of mobjects to be removed, this\n filters out the removable mobjects from the list of mobjects.\n\n Parameters\n ----------\n\n mobjects : list\n The Mobjects to check.\n\n to_remove : list\n The list of mobjects to remove.\n\n Returns\n -------\n list\n The list of mobjects with the mobjects to remove removed.\n \"\"\"\n\n new_mobjects = []\n\n def add_safe_mobjects_from_list(list_to_examine, set_to_remove):\n for mob in list_to_examine:\n if mob in set_to_remove:\n continue\n intersect = set_to_remove.intersection(mob.get_family())\n if intersect:\n add_safe_mobjects_from_list(mob.submobjects, intersect)\n else:\n new_mobjects.append(mob)\n add_safe_mobjects_from_list(mobjects, set(to_remove))\n return new_mobjects\n\n # TODO, remove this, and calls to this\n def add_foreground_mobjects(self, *mobjects):\n \"\"\"\n Adds mobjects to the foreground, and internally to the list\n foreground_mobjects, and mobjects.\n\n Parameters\n ----------\n *mobjects : Mobject\n The Mobjects to add to the foreground.\n\n Returns\n ------\n Scene\n The Scene, with the foreground mobjects added.\n \"\"\"\n self.foreground_mobjects = list_update(\n self.foreground_mobjects,\n mobjects\n )\n self.add(*mobjects)\n return self\n\n def add_foreground_mobject(self, mobject):\n \"\"\"\n Adds a single mobject to the foreground, and internally to the list\n foreground_mobjects, and mobjects.\n\n Parameters\n ----------\n mobject : Mobject\n The Mobject to add to the foreground.\n\n Returns\n ------\n Scene\n The Scene, with the foreground mobject added.\n \"\"\"\n return self.add_foreground_mobjects(mobject)\n\n def remove_foreground_mobjects(self, *to_remove):\n \"\"\"\n Removes mobjects from the foreground, and internally from the list\n foreground_mobjects.\n\n Parameters\n ----------\n *to_remove : Mobject\n The mobject(s) to remove from the foreground.\n\n Returns\n ------\n Scene\n The Scene, with the foreground mobjects removed.\n \"\"\"\n self.restructure_mobjects(to_remove, \"foreground_mobjects\")\n return self\n\n def remove_foreground_mobject(self, mobject):\n \"\"\"\n Removes a single mobject from the foreground, and internally from the list\n foreground_mobjects.\n\n Parameters\n ----------\n mobject : Mobject\n The mobject to remove from the foreground.\n\n Returns\n ------\n Scene\n The Scene, with the foreground mobject removed.\n \"\"\"\n return self.remove_foreground_mobjects(mobject)\n\n def bring_to_front(self, *mobjects):\n \"\"\"\n Adds the passed mobjects to the scene again,\n pushing them to he front of the scene.\n\n Parameters\n ----------\n *mobjects : Mobject\n The mobject(s) to bring to the front of the scene.\n\n Returns\n ------\n Scene\n The Scene, with the mobjects brought to the front\n of the scene.\n \"\"\"\n self.add(*mobjects)\n return self\n\n def bring_to_back(self, *mobjects):\n \"\"\"\n Removes the mobject from the scene and\n adds them to the back of the scene.\n\n Parameters\n ----------\n *mobjects : Mobject\n The mobject(s) to push to the back of the scene.\n\n Returns\n ------\n Scene\n The Scene, with the mobjects pushed to the back\n of the scene.\n \"\"\"\n self.remove(*mobjects)\n self.mobjects = list(mobjects) + self.mobjects\n return self\n\n def clear(self):\n \"\"\"\n Removes all mobjects present in self.mobjects\n and self.foreground_mobjects from the scene.\n\n Returns\n ------\n Scene\n The Scene, with all of its mobjects in\n self.mobjects and self.foreground_mobjects\n removed.\n \"\"\"\n self.mobjects = []\n self.foreground_mobjects = []\n return self\n\n def get_mobjects(self):\n \"\"\"\n Returns all the mobjects in self.mobjects\n\n Returns\n ------\n list\n The list of self.mobjects .\n \"\"\"\n return list(self.mobjects)\n\n def get_mobject_copies(self):\n \"\"\"\n Returns a copy of all mobjects present in\n self.mobjects .\n\n Returns\n ------\n list\n A list of the copies of all the mobjects\n in self.mobjects\n \"\"\"\n return [m.copy() for m in self.mobjects]\n\n def get_moving_mobjects(self, *animations):\n \"\"\"\n Gets all moving mobjects in the passed animation(s).\n\n Parameters\n ----------\n *animations : Animation\n The animations to check for moving mobjects.\n\n Returns\n ------\n list\n The list of mobjects that could be moving in\n the Animation(s)\n \"\"\"\n # Go through mobjects from start to end, and\n # as soon as there's one that needs updating of\n # some kind per frame, return the list from that\n # point forward.\n animation_mobjects = [anim.mobject for anim in animations]\n mobjects = self.get_mobject_family_members()\n for i, mob in enumerate(mobjects):\n update_possibilities = [\n mob in animation_mobjects,\n len(mob.get_family_updaters()) > 0,\n mob in self.foreground_mobjects\n ]\n if any(update_possibilities):\n return mobjects[i:]\n return []\n\n def get_time_progression(self, run_time, n_iterations=None, override_skip_animations=False):\n \"\"\"\n You will hardly use this when making your own animations.\n This method is for Manim's internal use.\n\n Returns a CommandLine ProgressBar whose fill_time\n is dependent on the run_time of an animation,\n the iterations to perform in that animation\n and a bool saying whether or not to consider\n the skipped animations.\n\n Parameters\n ----------\n run_time: float\n The run_time of the animation.\n\n n_iterations: int, optional\n The number of iterations in the animation.\n\n override_skip_animations: bool, optional\n Whether or not to show skipped animations in the progress bar.\n\n Returns\n ------\n ProgressDisplay\n The CommandLine Progress Bar.\n \"\"\"\n if file_writer_config['skip_animations'] and not override_skip_animations:\n times = [run_time]\n else:\n step = 1 / self.camera.frame_rate\n times = np.arange(0, run_time, step)\n time_progression = ProgressDisplay(\n times, total=n_iterations,\n leave=file_writer_config['leave_progress_bars'],\n ascii=False if platform.system() != 'Windows' else True\n )\n return time_progression\n\n def get_run_time(self, animations):\n \"\"\"\n Gets the total run time for a list of animations.\n\n Parameters\n ----------\n animations: list of Animation\n A list of the animations whose total\n run_time is to be calculated.\n\n Returns\n ------\n float\n The total run_time of all of the animations in the list.\n \"\"\"\n\n return np.max([animation.run_time for animation in animations])\n\n def get_animation_time_progression(self, animations):\n \"\"\"\n You will hardly use this when making your own animations.\n This method is for Manim's internal use.\n\n Uses get_time_progression to obtaina\n CommandLine ProgressBar whose fill_time is\n dependent on the qualities of the passed Animation,\n\n Parameters\n ----------\n animations : list of Animation\n The list of animations to get\n the time progression for.\n\n Returns\n ------\n ProgressDisplay\n The CommandLine Progress Bar.\n \"\"\"\n run_time = self.get_run_time(animations)\n time_progression = self.get_time_progression(run_time)\n time_progression.set_description(\"\".join([\n \"Animation {}: \".format(self.num_plays),\n str(animations[0]),\n (\", etc.\" if len(animations) > 1 else \"\"),\n ]))\n return time_progression\n\n def compile_play_args_to_animation_list(self, *args, **kwargs):\n \"\"\"\n Each arg can either be an animation, or a mobject method\n followed by that methods arguments (and potentially follow\n by a dict of kwargs for that method).\n This animation list is built by going through the args list,\n and each animation is simply added, but when a mobject method\n s hit, a MoveToTarget animation is built using the args that\n follow up until either another animation is hit, another method\n is hit, or the args list runs out.\n\n Parameters\n ----------\n *args : Animation or method of a mobject, which is followed by that method's arguments\n\n **kwargs : any named arguments like run_time or lag_ratio.\n\n Returns\n -------\n list : list of animations with the parameters applied to them.\n \"\"\"\n animations = []\n state = {\n \"curr_method\": None,\n \"last_method\": None,\n \"method_args\": [],\n }\n\n def compile_method(state):\n if state[\"curr_method\"] is None:\n return\n mobject = state[\"curr_method\"].__self__\n if state[\"last_method\"] and state[\"last_method\"].__self__ is mobject:\n animations.pop()\n # method should already have target then.\n else:\n mobject.generate_target()\n #\n if len(state[\"method_args\"]) > 0 and isinstance(state[\"method_args\"][-1], dict):\n method_kwargs = state[\"method_args\"].pop()\n else:\n method_kwargs = {}\n state[\"curr_method\"].__func__(\n mobject.target,\n *state[\"method_args\"],\n **method_kwargs\n )\n animations.append(MoveToTarget(mobject))\n state[\"last_method\"] = state[\"curr_method\"]\n state[\"curr_method\"] = None\n state[\"method_args\"] = []\n\n for arg in args:\n if isinstance(arg, Animation):\n compile_method(state)\n animations.append(arg)\n elif inspect.ismethod(arg):\n compile_method(state)\n state[\"curr_method\"] = arg\n elif state[\"curr_method\"] is not None:\n state[\"method_args\"].append(arg)\n elif isinstance(arg, Mobject):\n raise Exception(\"\"\"\n I think you may have invoked a method\n you meant to pass in as a Scene.play argument\n \"\"\")\n else:\n raise Exception(\"Invalid play arguments\")\n compile_method(state)\n\n for animation in animations:\n # This is where kwargs to play like run_time and rate_func\n # get applied to all animations\n animation.update_config(**kwargs)\n\n return animations\n\n def update_skipping_status(self):\n \"\"\"\n This method is used internally to check if the current\n animation needs to be skipped or not. It also checks if\n the number of animations that were played correspond to\n the number of animations that need to be played, and\n raises an EndSceneEarlyException if they don't correspond.\n \"\"\"\n\n if file_writer_config['from_animation_number']:\n if self.num_plays == file_writer_config['from_animation_number']:\n file_writer_config['skip_animations'] = False\n if file_writer_config['upto_animation_number']:\n if self.num_plays >= file_writer_config['upto_animation_number']:\n file_writer_config['skip_animations'] = True\n raise EndSceneEarlyException()\n\n def handle_play_like_call(func):\n \"\"\"\n This method is used internally to wrap the\n passed function, into a function that\n actually writes to the video stream.\n Simultaneously, it also adds to the number\n of animations played.\n\n Parameters\n ----------\n func : function\n The play() like function that has to be\n written to the video file stream.\n\n Returns\n -------\n function\n The play() like function that can now write\n to the video file stream.\n \"\"\"\n def wrapper(self, *args, **kwargs):\n self.update_skipping_status()\n allow_write = not file_writer_config['skip_animations']\n self.file_writer.begin_animation(allow_write)\n func(self, *args, **kwargs)\n self.file_writer.end_animation(allow_write)\n self.num_plays += 1\n return wrapper\n\n def begin_animations(self, animations):\n \"\"\"\n This method begins the list of animations that is passed,\n and adds any mobjects involved (if not already present)\n to the scene again.\n\n Parameters\n ----------\n animations : list\n List of involved animations.\n\n \"\"\"\n curr_mobjects = self.get_mobject_family_members()\n for animation in animations:\n # Begin animation\n animation.begin()\n # Anything animated that's not already in the\n # scene gets added to the scene\n mob = animation.mobject\n if mob not in curr_mobjects:\n self.add(mob)\n curr_mobjects += mob.get_family()\n\n def progress_through_animations(self, animations):\n \"\"\"\n This method progresses through each animation\n in the list passed and and updates the frames as required.\n\n Parameters\n ----------\n animations : list\n List of involved animations.\n \"\"\"\n # Paint all non-moving objects onto the screen, so they don't\n # have to be rendered every frame\n moving_mobjects = self.get_moving_mobjects(*animations)\n self.update_frame(excluded_mobjects=moving_mobjects)\n static_image = self.get_frame()\n last_t = 0\n for t in self.get_animation_time_progression(animations):\n dt = t - last_t\n last_t = t\n for animation in animations:\n animation.update_mobjects(dt)\n alpha = t / animation.run_time\n animation.interpolate(alpha)\n self.update_mobjects(dt)\n self.update_frame(moving_mobjects, static_image)\n self.add_frames(self.get_frame())\n\n def finish_animations(self, animations):\n \"\"\"\n This function cleans up after the end\n of each animation in the passed list.\n\n Parameters\n ----------\n animations : list\n list of animations to finish.\n \"\"\"\n for animation in animations:\n animation.finish()\n animation.clean_up_from_scene(self)\n self.mobjects_from_last_animation = [\n anim.mobject for anim in animations\n ]\n if file_writer_config['skip_animations']:\n # TODO, run this call in for each animation?\n self.update_mobjects(self.get_run_time(animations))\n else:\n self.update_mobjects(0)\n\n @handle_play_like_call\n def play(self, *args, **kwargs):\n \"\"\"\n This method is used to prep the animations for rendering,\n apply the arguments and parameters required to them,\n render them, and write them to the video file.\n\n Parameters\n ----------\n *args : Animation or mobject with mobject method and params\n **kwargs : named parameters affecting what was passed in *args e.g run_time, lag_ratio etc.\n \"\"\"\n if len(args) == 0:\n warnings.warn(\"Called Scene.play with no animations\")\n return\n animations = self.compile_play_args_to_animation_list(\n *args, **kwargs\n )\n self.begin_animations(animations)\n self.progress_through_animations(animations)\n self.finish_animations(animations)\n\n def idle_stream(self):\n \"\"\"\n This method is used internally to\n idle the video file_writer until an\n animation etc needs to be written\n to the video file.\n \"\"\"\n self.file_writer.idle_stream()\n\n def clean_up_animations(self, *animations):\n \"\"\"\n This method cleans up and removes from the\n scene all the animations that were passed\n\n Parameters\n ----------\n *animations : Animation\n Animation to clean up.\n\n Returns\n -------\n Scene\n The scene with the animations\n cleaned up.\n\n \"\"\"\n for animation in animations:\n animation.clean_up_from_scene(self)\n return self\n\n def get_mobjects_from_last_animation(self):\n \"\"\"\n This method returns the mobjects from the previous\n played animation, if any exist, and returns an empty\n list if not.\n\n Returns\n --------\n list\n The list of mobjects from the previous animation.\n\n \"\"\"\n if hasattr(self, \"mobjects_from_last_animation\"):\n return self.mobjects_from_last_animation\n return []\n\n def get_wait_time_progression(self, duration, stop_condition):\n \"\"\"\n This method is used internally to obtain the CommandLine\n Progressbar for when self.wait() is called in a scene.\n\n Parameters\n ----------\n duration: int or float\n duration of wait time\n\n stop_condition : function\n The function which determines whether to continue waiting.\n\n Returns\n -------\n ProgressBar\n The CommandLine ProgressBar of the wait time\n\n \"\"\"\n if stop_condition is not None:\n time_progression = self.get_time_progression(\n duration,\n n_iterations=-1, # So it doesn't show % progress\n override_skip_animations=True\n )\n time_progression.set_description(\n \"Waiting for {}\".format(stop_condition.__name__)\n )\n else:\n time_progression = self.get_time_progression(duration)\n time_progression.set_description(\n \"Waiting {}\".format(self.num_plays)\n )\n return time_progression\n\n @handle_play_like_call\n def wait(self, duration=DEFAULT_WAIT_TIME, stop_condition=None):\n \"\"\"\n This method is used to wait, and do nothing to the scene, for some\n duration.\n Updaters stop updating, nothing happens.\n\n Parameters\n ----------\n duration : float or int, optional\n The duration of wait time.\n stop_condition :\n A function that determines whether to stop waiting or not.\n\n Returns\n -------\n Scene\n The scene, after waiting.\n \"\"\"\n self.update_mobjects(dt=0) # Any problems with this?\n if self.should_update_mobjects():\n time_progression = self.get_wait_time_progression(duration, stop_condition)\n # TODO, be smart about setting a static image\n # the same way Scene.play does\n last_t = 0\n for t in time_progression:\n dt = t - last_t\n last_t = t\n self.update_mobjects(dt)\n self.update_frame()\n self.add_frames(self.get_frame())\n if stop_condition is not None and stop_condition():\n time_progression.close()\n break\n elif file_writer_config['skip_animations']:\n # Do nothing\n return self\n else:\n self.update_frame()\n dt = 1 / self.camera.frame_rate\n n_frames = int(duration / dt)\n frame = self.get_frame()\n self.add_frames(*[frame] * n_frames)\n return self\n\n def wait_until(self, stop_condition, max_time=60):\n \"\"\"\n Like a wrapper for wait().\n You pass a function that determines whether to continue waiting,\n and a max wait time if that is never fulfilled.\n\n Parameters\n ----------\n stop_condition : function\n The function whose boolean return value determines whether to continue waiting\n\n max_time : int or float, optional\n The maximum wait time in seconds, if the stop_condition is never fulfilled.\n \"\"\"\n self.wait(max_time, stop_condition=stop_condition)\n\n def force_skipping(self):\n \"\"\"\n This forces the skipping of animations,\n by setting original_skipping_status to\n whatever skip_animations was, and setting\n skip_animations to True.\n\n Returns\n -------\n Scene\n The Scene, with skipping turned on.\n \"\"\"\n self.original_skipping_status = self.SKIP_ANIMATIONS\n self.SKIP_ANIMATIONS = True\n return self\n\n def revert_to_original_skipping_status(self):\n \"\"\"\n Forces the scene to go back to its original skipping status,\n by setting skip_animations to whatever it reads\n from original_skipping_status.\n\n Returns\n -------\n Scene\n The Scene, with the original skipping status.\n \"\"\"\n if hasattr(self, \"original_skipping_status\"):\n self.SKIP_ANIMATIONS = self.original_skipping_status\n return self\n\n def add_frames(self, *frames):\n \"\"\"\n Adds a frame to the video_file_stream\n\n Parameters\n ----------\n *frames : numpy.ndarray\n The frames to add, as pixel arrays.\n \"\"\"\n dt = 1 / self.camera.frame_rate\n self.increment_time(len(frames) * dt)\n if file_writer_config['skip_animations']:\n return\n for frame in frames:\n self.file_writer.write_frame(frame)\n\n def add_sound(self, sound_file, time_offset=0, gain=None, **kwargs):\n \"\"\"\n This method is used to add a sound to the animation.\n\n Parameters\n ----------\n sound_file : str\n The path to the sound file.\n\n time_offset : int,float, optional\n The offset in the sound file after which\n the sound can be played.\n\n gain :\n\n \"\"\"\n if self.SKIP_ANIMATIONS:\n return\n time = self.get_time() + time_offset\n self.file_writer.add_sound(sound_file, time, gain, **kwargs)\n\n def show_frame(self):\n \"\"\"\n Opens the current frame in the Default Image Viewer\n of your system.\n \"\"\"\n self.update_frame(ignore_skipping=True)\n self.get_image().show()\n\n\nclass EndSceneEarlyException(Exception):\n pass\n" ]
[ [ "numpy.max", "numpy.arange", "numpy.random.seed" ] ]
VijayReddy119/small_obstacle_discovery
[ "0f1324c7591e433a7ffc69832c4421f4cc9a77ad" ]
[ "normalization_metrics.py" ]
[ "import sys\nimport numpy as np\nfrom tqdm import tqdm\nfrom torch.utils.data import DataLoader\nimport utils.helpers as HLP\nfrom mypath import Path\n\ndataset = 'lnf'\ntrain_imgs, train_disp, train_labels = HLP.get_ImagesAndLabels_mergenet(Path.db_root_dir(dataset))\ntest_imgs, test_disp, test_labels = HLP.get_ImagesAndLabels_mergenet(Path.db_root_dir(dataset),\n data_type='test')\ntrain_loader = DataLoader(HLP.LNFGeneratorTorch(rgb_path=train_imgs,disparity_path=train_disp,\n mask_path=train_labels, flag = 'merge',\n split='train'), batch_size = 2, shuffle=True)\nval_loader = DataLoader(HLP.LNFGeneratorTorch(rgb_path=test_imgs,disparity_path=test_disp,\n mask_path=test_labels, flag = 'merge',\n split='val'), batch_size=2, shuffle=True)\ntotal_mean = []\ntotal_std = []\nfor sample in tqdm(train_loader):\n image = sample['image']\n image = np.asarray(image)\n batch_mean = np.mean(image, axis=(0,2,3))\n total_mean.append(batch_mean/255)\n batch_std = np.std(image, axis=(0,2,3))\n total_std.append(batch_std/255)\nfor sample in tqdm(val_loader):\n image = sample['image']\n image = np.asarray(image)\n batch_mean = np.mean(image, axis=(0,2,3))\n total_mean.append(batch_mean/255)\n batch_std = np.std(image, axis=(0,2,3))\n total_std.append(batch_std/255)\n\nmean = np.asarray(total_mean).mean(axis=0)\nstd = np.asarray(total_std).mean(axis=0)\nprint('mean: ', mean)\nprint('std: ', std)\n" ]
[ [ "numpy.asarray", "numpy.std", "numpy.mean" ] ]
tzhern/COMP30027-Project-2
[ "c8a9a1d216dae6b7b7b30bb8e53a2a084db73b36" ]
[ "test/load_data.py" ]
[ "import pandas as pd\nimport scipy\nimport pickle\n\n# load csv files\n\"\"\"\nname, n_steps, n_ingredients, steps, ingredients\n\"\"\"\ndf_train = pd.read_csv(\"datasets/recipe_train.csv\")\ndf_test = pd.read_csv(\"datasets/recipe_test.csv\")\n\n\"\"\"\n# load CountVectorizer (pkl) files\n\"\"\"\n#This file contains the CountVectorizer extracted using the text of the recipe \"name\", \"ingr\" and \"steps\" in the training set.\n\"\"\"\nvocab_name_train = pickle.load(open(\"datasets/recipe_text_features_countvec/train_name_countvectorizer.pkl\", \"rb\"))\nvocab_steps_train = pickle.load(open(\"datasets/recipe_text_features_countvec/train_steps_countvectorizer.pkl\", \"rb\"))\nvocab_ingr_train = pickle.load(open(\"datasets/recipe_text_features_countvec/train_ingr_countvectorizer.pkl\", \"rb\"))\nvocab_name_dict_train = vocab_name_train.vocabulary_\nvocab_steps_dict_train = vocab_steps_train.vocabulary_\nvocab_ingr_dict_train = vocab_ingr_train.vocabulary_\n\n\n# load sparse matrix (npz) files\n\"\"\"\n#This file contains a sparse matrix of the Bag-of-Word representation of the recipe names for test data. \n\"\"\"\n## train\n### The dense version of this matrix should be [40000 * size of vocabulary], and \n### the element (i,j) in the matrix is the count of each vocabulary term j in instance i. \n### The vocabulary corresponds to the vocabulary_ attribute of vocab (which can be checked as detailed in (1))\narr_name_vec_train = scipy.sparse.load_npz(\"datasets/recipe_text_features_countvec/train_name_vec.npz\").toarray()\narr_steps_vec_train = scipy.sparse.load_npz(\"datasets/recipe_text_features_countvec/train_steps_vec.npz\").toarray()\narr_ingr_vec_train = scipy.sparse.load_npz('datasets/recipe_text_features_countvec/train_ingr_vec.npz').toarray()\n## test\n### The dense version of this matrix should be [10000 * size of vocabulary]. \n### The vocabulary is the one that has been extracted from training, but \n### the elements in this matrix are the counts for each recipe in the test set.\narr_name_vec_test = scipy.sparse.load_npz(\"datasets/recipe_text_features_countvec/test_name_vec.npz\").toarray()\narr_steps_vec_test = scipy.sparse.load_npz(\"datasets/recipe_text_features_countvec/test_steps_vec.npz\").toarray()\narr_ingr_vec_test = scipy.sparse.load_npz(\"datasets/recipe_text_features_countvec/test_ingr_vec.npz\").toarray()\n\n\n# load Doc2Vec50 matrix files\n\"\"\" \n#This file contains a matrix of Doc2Vec representation of the recipe names for training data, with 50 features.\n#The element (i,j) in the matrix is a numeric value for feature j of an instance i. \n\"\"\"\n## train\n### The dimension of this matrix is [40000 * 50]\ndf_name_doc2vec50_train = pd.read_csv(r\"datasets/recipe_text_features_doc2vec50/train_name_doc2vec50.csv\", index_col = False, delimiter = ',', header=None)\ndf_steps_doc2vec50_train = pd.read_csv(r\"datasets/recipe_text_features_doc2vec50/train_steps_doc2vec50.csv\", index_col = False, delimiter = ',', header=None)\ndf_ingr_doc2vec50_train = pd.read_csv(r\"datasets/recipe_text_features_doc2vec50/train_ingr_doc2vec50.csv\", index_col = False, delimiter = ',', header=None)\n## test\n### The dimension of this matrix is [10000 * 50]\ndf_name_doc2vec50_test = pd.read_csv(r\"datasets/recipe_text_features_doc2vec50/test_name_doc2vec50.csv\", index_col = False, delimiter = ',', header=None)\ndf_steps_doc2vec50_test = pd.read_csv(r\"datasets/recipe_text_features_doc2vec50/test_steps_doc2vec50.csv\", index_col = False, delimiter = ',', header=None)\ndf_ingr_doc2vec50_test = pd.read_csv(r\"datasets/recipe_text_features_doc2vec50/test_ingr_doc2vec50.csv\", index_col = False, delimiter = ',', header=None)\n\n\n# load Doc2Vec100 matrix files\n\"\"\"\n#Same as Doc2Vec50 but 100 features are used for each instance\n\"\"\"\n## train\ndf_name_doc2vec100_train = pd.read_csv(\"datasets/recipe_text_features_doc2vec100/train_name_doc2vec100.csv\", index_col = False, delimiter = ',', header=None)\ndf_steps_doc2vec100_train = pd.read_csv(\"datasets/recipe_text_features_doc2vec100/train_steps_doc2vec100.csv\", index_col = False, delimiter = ',', header=None)\ndf_ingr_doc2vec100_train = pd.read_csv(\"datasets/recipe_text_features_doc2vec100/train_ingr_doc2vec100.csv\", index_col = False, delimiter = ',', header=None)\n## test\ndf_name_doc2vec100_test = pd.read_csv(\"datasets/recipe_text_features_doc2vec100/test_name_doc2vec100.csv\", index_col = False, delimiter = ',', header=None)\ndf_steps_doc2vec100_test = pd.read_csv(\"datasets/recipe_text_features_doc2vec100/test_steps_doc2vec100.csv\", index_col = False, delimiter = ',', header=None)\ndf_ingr_doc2vec100_test = pd.read_csv(\"datasets/recipe_text_features_doc2vec100/test_ingr_doc2vec100.csv\", index_col = False, delimiter = ',', header=None)\n\n\"\"\"" ]
[ [ "pandas.read_csv" ] ]
jacekplocharczyk/a3c-pytorch
[ "bec7dc5ffb9081d79080e77e3cbdd1ad9380d72f" ]
[ "a3c_pytorch/common/basic_memory.py" ]
[ "from typing import Union\n\nimport torch\n\n\nclass Memory:\n def __init__(self, gamma: float, batch_size: int = 64):\n self.actions = []\n self.action_logprobs = []\n self.state_values = []\n self.returns = None\n\n self.rewards = None\n self.is_terminals = None\n self.batch = 0\n self.gamma = gamma\n self.batch_size = batch_size\n\n @staticmethod\n def _append(\n memory_variable: Union[None, torch.tensor], value: torch.tensor\n ) -> torch.tensor:\n value = torch.unsqueeze(value, dim=0)[None, :]\n if memory_variable is None:\n return value\n else:\n return torch.cat([memory_variable, value]) # WARN: cat loses grad_fn!\n\n def update_actions(self, value: torch.tensor):\n self.actions.append(value)\n\n def update_action_logprobs(self, value: torch.tensor):\n self.action_logprobs.append(value)\n\n def update_state_values(self, value: torch.tensor):\n self.state_values.append(value)\n\n def update_rewards(self, value: torch.tensor):\n self.rewards = self._append(self.rewards, value)\n\n def update_is_terminals(self, value: torch.tensor):\n self.is_terminals = self._append(self.is_terminals, value)\n\n def calculate_returns(self):\n returns = []\n discounted_return = 0\n\n for reward, is_terminal in zip(\n reversed(self.rewards), reversed(self.is_terminals)\n ):\n if is_terminal:\n discounted_return = 0\n discounted_return = reward + (self.gamma * discounted_return)\n returns.insert(0, discounted_return)\n\n self.returns = torch.tensor(returns)\n\n def __iter__(self):\n self.batch = 0\n return self\n\n def __next__(self): # Python 2: def next(self)\n start = self.batch_size * self.batch\n end = start + self.batch_size\n\n if start >= self.returns.shape[0]:\n raise StopIteration\n self.batch += 1\n return MemoryBatch(self, start, end)\n\n def get_summary_reward(self):\n return float(self.rewards.sum()) / float(sum(self.is_terminals))\n\n\nclass MemoryBatch:\n def __init__(self, memory: Memory, start: int, end: int):\n self.action_logprobs = memory.action_logprobs[start:end]\n self.state_values = memory.state_values[start:end]\n self.returns = memory.returns[start:end]\n" ]
[ [ "torch.cat", "torch.unsqueeze", "torch.tensor" ] ]
e2000y/eden
[ "d2751e0a2f8f859275212e55c2b101646cb2d8c2" ]
[ "modules/s3db/vulnerability.py" ]
[ "# -*- coding: utf-8 -*-\n\n\"\"\" Sahana Eden Vulnerability Model\n\n @copyright: 2012-2021 (c) Sahana Software Foundation\n @license: MIT\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation\n files (the \"Software\"), to deal in the Software without\n restriction, including without limitation the rights to use,\n copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following\n conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\n__all__ = (\"VulnerabilityModel\",\n \"HazardModel\",\n \"RiskModel\",\n \"vulnerability_aggregated_period\", # Used by Unit Tests\n \"vulnerability_pids\", # Used by Unit Tests\n #\"vulnerability_resilience\",\n \"vulnerability_resilience_id\", # Used by Unit Tests\n \"vulnerability_rheader\",\n \"vulnerability_rebuild_all_aggregates\",\n \"vulnerability_update_aggregates\",\n \"vulnerability_update_location_aggregate\",\n )\n\nimport json\n\nfrom datetime import date\n\nfrom gluon import *\nfrom gluon.storage import Storage\n\nfrom ..s3 import *\nfrom s3layouts import S3PopupLink\n\n# =============================================================================\nclass VulnerabilityModel(S3Model):\n \"\"\"\n Vulnerability Data\n\n @ToDo: Don't aggregate data for locations which don't exist in time window\n \"\"\"\n\n names = (\"vulnerability_indicator\",\n \"vulnerability_aggregated_indicator\",\n \"vulnerability_data\",\n \"vulnerability_document\",\n \"vulnerability_aggregate\",\n )\n\n resilience_pid = None # id of the resilience indicator\n indicator_pids = None # List of ids used to calculate the resilence indicator\n\n def model(self):\n\n settings = current.deployment_settings\n if not settings.has_module(\"stats\"):\n current.log.warning(\"Vulnerability Model needs Stats module enabling\")\n return None\n\n T = current.T\n db = current.db\n\n configure = self.configure\n crud_strings = current.response.s3.crud_strings\n define_table = self.define_table\n super_link = self.super_link\n\n location_id = self.gis_location_id\n\n UNKNOWN_OPT = current.messages.UNKNOWN_OPT\n\n # ---------------------------------------------------------------------\n # Vulnerability Indicators\n #\n hierarchical_indicators = settings.get_vulnerability_indicator_hierarchical()\n\n tablename = \"vulnerability_indicator\"\n define_table(tablename,\n # Instance\n super_link(\"parameter_id\", \"stats_parameter\"),\n Field(\"parent\", \"reference stats_parameter\",\n label = T(\"SubType of\"),\n ondelete = \"RESTRICT\",\n readable = hierarchical_indicators,\n writable = hierarchical_indicators,\n ),\n Field(\"posn\", \"integer\"),\n Field(\"name\",\n label = T(\"Name\"),\n ),\n s3_comments(\"description\",\n label = T(\"Description\"),\n ),\n *s3_meta_fields()\n )\n\n indicator_represent = S3Represent(lookup = \"stats_parameter\",\n translate = True,\n )\n if hierarchical_indicators:\n hierarchy = \"parent\"\n # Can't be defined in-line as otherwise get a circular reference\n parent = db[tablename].parent\n parent.represent = indicator_represent\n parent.requires = super_link(\"parameter_id\",\n \"stats_parameter\",\n empty = True,\n represent = indicator_represent,\n # If limiting to just 1 level of parent\n #filterby=\"parent\",\n #filter_opts=(None,),\n orderby=\"stats_parameter.name\",\n ).requires\n\n indicator_widget = S3HierarchyWidget(lookup = \"vulnerability_indicator\",\n represent = indicator_represent,\n multiple = False,\n leafonly = True,\n )\n else:\n hierarchy = None\n indicator_widget = None\n\n # CRUD Strings\n crud_strings[tablename] = Storage(\n label_create = T(\"Add Vulnerability Indicator\"),\n title_display = T(\"Vulnerability Indicator Details\"),\n title_list = T(\"Vulnerability Indicators\"),\n title_update = T(\"Edit Vulnerability Indicator\"),\n #title_upload = T(\"Import Vulnerability Indicators\"),\n label_list_button = T(\"List Vulnerability Indicators\"),\n msg_record_created = T(\"Vulnerability Indicator added\"),\n msg_record_modified = T(\"Vulnerability Indicator updated\"),\n msg_record_deleted = T(\"Vulnerability Indicator deleted\"),\n msg_list_empty = T(\"No vulnerability indicators currently defined\"),\n )\n\n configure(tablename,\n deduplicate = S3Duplicate(),\n hierarchy = hierarchy,\n super_entity = \"stats_parameter\",\n )\n\n # ---------------------------------------------------------------------\n # Vulnerability Aggregated Indicators\n #\n tablename = \"vulnerability_aggregated_indicator\"\n define_table(tablename,\n # Instance\n super_link(\"parameter_id\", \"stats_parameter\"),\n Field(\"name\",\n label = T(\"Name\"),\n ),\n s3_comments(\"description\",\n label = T(\"Description\"),\n ),\n *s3_meta_fields()\n )\n\n # CRUD Strings\n crud_strings[tablename] = Storage(\n label_create = T(\"Add Vulnerability Aggregated Indicator\"),\n title_display = T(\"Vulnerability Aggregated Indicator Details\"),\n title_list = T(\"Vulnerability Aggregated Indicators\"),\n title_update = T(\"Edit Vulnerability Aggregated Indicator\"),\n #title_upload = T(\"Import Vulnerability Aggregated Indicator\"),\n label_list_button = T(\"List Vulnerability Aggregated Indicators\"),\n msg_record_created = T(\"Vulnerability Aggregated Indicator added\"),\n msg_record_modified = T(\"Vulnerability Aggregated Indicator updated\"),\n msg_record_deleted = T(\"Vulnerability Aggregated Indicator deleted\"),\n msg_list_empty = T(\"No vulnerability aggregated indicators currently defined\"),\n )\n\n configure(tablename,\n deduplicate = S3Duplicate(),\n super_entity = \"stats_parameter\",\n )\n\n # ---------------------------------------------------------------------\n # Vulnerability Data\n #\n tablename = \"vulnerability_data\"\n define_table(tablename,\n # Instance\n super_link(\"data_id\", \"stats_data\"),\n # This is a component, so needs to be a super_link\n # - can't override field name, ondelete or requires\n super_link(\"parameter_id\", \"stats_parameter\",\n empty = False,\n instance_types = (\"vulnerability_indicator\",),\n label = T(\"Indicator\"),\n represent = indicator_represent,\n readable = True,\n writable = True,\n widget = indicator_widget,\n ),\n location_id(widget = S3LocationAutocompleteWidget(),\n empty = False,\n requires = IS_LOCATION(),\n ),\n Field(\"value\", \"double\",\n label = T(\"Value\"),\n represent = lambda v: \\\n IS_FLOAT_AMOUNT.represent(v, precision=2),\n requires = IS_NOT_EMPTY(),\n ),\n # Date = None => Modelled data which could occur at any time\n s3_date(label = T(\"Start Date\"),\n ),\n s3_date(\"end_date\",\n label = T(\"End Date\"),\n start_field = \"vulnerability_data_date\",\n default_interval = 12,\n ),\n Field(\"year\", \"list:integer\",\n compute = lambda row: \\\n self.stats_year(row, \"vulnerability_data\"),\n label = T(\"Year\"),\n ),\n # Link to Source\n self.stats_source_id(),\n s3_comments(),\n *s3_meta_fields()\n )\n\n # CRUD Strings\n ADD_DATA = T(\"Add Vulnerability Data\")\n crud_strings[tablename] = Storage(\n label_create = ADD_DATA,\n title_display = T(\"Vulnerability Data Details\"),\n title_list = T(\"Vulnerability Data\"),\n title_update = T(\"Edit Vulnerability Data\"),\n title_upload = T(\"Import Vulnerability Data\"),\n label_list_button = T(\"List Vulnerability Data\"),\n msg_record_created = T(\"Vulnerability Data added\"),\n msg_record_modified = T(\"Vulnerability Data updated\"),\n msg_record_deleted = T(\"Vulnerability Data deleted\"),\n msg_list_empty = T(\"No vulnerability data currently defined\"),\n )\n\n levels = current.gis.get_relevant_hierarchy_levels()\n\n location_fields = [\"location_id$%s\" % level for level in levels]\n\n list_fields = [\"parameter_id\"]\n list_fields.extend(location_fields)\n list_fields.extend(((\"value\",\n \"date\",\n \"source_id\",\n )))\n\n if hierarchical_indicators:\n parameter_filter = S3HierarchyFilter(\"parameter_id\",\n lookup=\"vulnerability_indicator\",\n multiple = False,\n leafonly = True,\n # Not translateable\n #represent = \"%(name)s\",\n )\n else:\n parameter_filter = S3OptionsFilter(\"parameter_id\",\n label = T(\"Indicator\"),\n multiple = False,\n # Not translateable\n #represent = \"%(name)s\",\n )\n\n filter_widgets = [parameter_filter,\n S3OptionsFilter(\"year\",\n #multiple = False,\n #none = True,\n operator = \"anyof\",\n options = lambda: \\\n self.stats_year_options(\"vulnerability_data\"),\n ),\n S3OptionsFilter(\"location_id$level\",\n label = T(\"Level\"),\n multiple = False,\n # Not translateable\n #represent = \"%(name)s\",\n ),\n S3LocationFilter(\"location_id\",\n levels = levels,\n ),\n ]\n\n report_options = Storage(rows = location_fields + [\"year\"],\n cols = [\"parameter_id\"],\n fact = [(T(\"Value\"), \"sum(value)\"),\n ],\n defaults = Storage(rows = \"location_id\",\n cols = \"parameter_id\",\n fact = \"sum(value)\",\n totals = True,\n chart = \"breakdown:rows\",\n table = \"collapse\",\n ),\n )\n\n configure(tablename,\n deduplicate = S3Duplicate(primary = (\"parameter_id\",\n \"location_id\",\n \"date\",\n ),\n ),\n filter_widgets = filter_widgets,\n list_fields = list_fields,\n # @ToDo: Wrapper function to call this for the record linked\n # to the relevant place depending on whether approval is\n # required or not. Disable when auth.override is True.\n #onaccept = self.vulnerability_update_aggregates,\n #onapprove = self.vulnerability_update_aggregates,\n report_options = report_options,\n # @ToDo: deployment_setting\n requires_approval = True,\n super_entity = \"stats_data\",\n )\n\n # ---------------------------------------------------------------------\n # Vulnerability Documents\n # - a common view of different sorts of document which can be uploaded\n # to the vulnerability application\n #\n doc_types = {\"vca\": T(\"VCA Reports\"),\n \"indicator\": T(\"Indicator ratings\"),\n \"demographic\": T(\"Demographic Data\"),\n \"map\": T(\"Map\"),\n \"image\": T(\"Image\"),\n \"other\": T(\"Other Reports\"),\n }\n\n tablename = \"vulnerability_document\"\n define_table(tablename,\n # Instance\n # - so that we can link to the doc_document or doc_image, if-appropriate\n super_link(\"doc_id\", \"doc_entity\"),\n Field(\"name\",\n label = T(\"Name\"),\n ),\n Field(\"document_type\",\n label = T(\"Type\"),\n represent = s3_options_represent(doc_types),\n requires=IS_IN_SET(doc_types),\n ),\n location_id(widget = S3LocationAutocompleteWidget(),\n requires = IS_LOCATION(),\n ),\n s3_date(label = T(\"Date Published\")),\n # Link to Source to be able to approve linked data records & trigger aggregates build\n self.stats_source_id(),\n *s3_meta_fields()\n )\n\n # Resource Configuration\n configure(\"vulnerability_document\",\n deduplicate = S3Duplicate(),\n requires_approval = True,\n super_entity = \"doc_entity\",\n )\n\n #----------------------------------------------------------------------\n # Vulnerability Aggregated data\n #\n # The data can be aggregated against:\n # location, all the aggregated values across a number of locations\n # thus for an L2 it will aggregate all the L3 values\n # time, all the vulnerability_data values for the same time period.\n # currently this is just the latest value in the time period\n # copy, this is a copy of the previous time aggregation because no\n # data is currently available for this time period\n\n aggregate_types = {1 : T(\"Time\"),\n 2 : T(\"Location\"),\n 3 : T(\"Copy\"),\n 4 : T(\"Indicator\"),\n }\n\n tablename = \"vulnerability_aggregate\"\n define_table(tablename,\n # This is a component, so needs to be a super_link\n # - can't override field name, ondelete or requires\n super_link(\"parameter_id\", \"stats_parameter\",\n label = T(\"Indicator\"),\n instance_types = (\"vulnerability_indicator\",\n \"vulnerability_aggregated_indicator\",\n ),\n represent = S3Represent(lookup = \"stats_parameter\"),\n readable = True,\n writable = True,\n empty = False,\n ),\n location_id(widget = S3LocationAutocompleteWidget(),\n requires = IS_LOCATION()\n ),\n Field(\"agg_type\", \"integer\",\n default = 1,\n represent = lambda opt: \\\n aggregate_types.get(opt, UNKNOWN_OPT),\n requires = IS_IN_SET(aggregate_types),\n ),\n Field(\"reported_count\", \"integer\",\n #label = T(\"The number of aggregated records\")\n ),\n Field(\"ward_count\", \"integer\",\n #label = T(\"The number of geographical units within the aggregation area\")\n ),\n Field(\"date\", \"date\",\n label = T(\"Start Date\"),\n ),\n Field(\"end_date\", \"date\",\n label = T(\"End Date\"),\n ),\n Field(\"sum\", \"double\",\n label = T(\"Sum\"),\n ),\n Field(\"min\", \"double\",\n label = T(\"Minimum\"),\n ),\n Field(\"max\", \"double\",\n label = T(\"Maximum\"),\n ),\n Field(\"mean\", \"double\",\n label = T(\"Mean\"),\n ),\n Field(\"median\", \"double\",\n label = T(\"Median\"),\n ),\n Field(\"mad\", \"double\",\n label = T(\"Median Absolute Deviation\"),\n default = 0.0,\n ),\n #Field(\"mean_ad\", \"double\",\n # label = T(\"Mean Absolute Deviation\"),\n # ),\n #Field(\"std\", \"double\",\n # label = T(\"Standard Deviation\"),\n # ),\n #Field(\"variance\", \"double\",\n # label = T(\"Variance\"),\n # ),\n *s3_meta_fields()\n )\n\n # ---------------------------------------------------------------------\n # Pass model-global names to response.s3\n #\n return None\n\n# =============================================================================\nclass HazardModel(S3Model):\n \"\"\"\n Hazard Model\n\n @ToDo: Unify with Project Hazard\n \"\"\"\n\n names = (\"vulnerability_hazard\",\n \"vulnerability_hazard_id\",\n )\n\n def model(self):\n\n T = current.T\n db = current.db\n\n # ---------------------------------------------------------------------\n # Hazards\n #\n tablename = \"vulnerability_hazard\"\n self.define_table(tablename,\n Field(\"name\", length=128, notnull=True, unique=True,\n label = T(\"Name\"),\n requires = [IS_NOT_EMPTY(),\n IS_LENGTH(128),\n IS_NOT_IN_DB(db,\n \"%s.name\" % tablename,\n ),\n ],\n ),\n s3_comments(),\n *s3_meta_fields())\n\n current.response.s3.crud_strings[tablename] = Storage(\n label_create = T(\"Create Hazard\"),\n title_display = T(\"Hazard Details\"),\n title_list = T(\"Hazards\"),\n title_update = T(\"Edit Hazard\"),\n label_list_button = T(\"List Hazards\"),\n label_delete_button = T(\"Remove Hazard\"),\n msg_record_created = T(\"Hazard added\"),\n msg_record_modified = T(\"Hazard updated\"),\n msg_record_deleted = T(\"Hazard removed\"),\n msg_list_empty = T(\"No Hazards currently recorded\"),\n )\n\n # Reusable Field\n represent = S3Represent(lookup = tablename)\n hazard_id = S3ReusableField(\"hazard_id\", \"reference %s\" % tablename,\n label = T(\"Hazard\"),\n ondelete = \"CASCADE\",\n represent = represent,\n requires = IS_EMPTY_OR(\n IS_ONE_OF(db, \"vulnerability_hazard.id\",\n represent,\n sort = True,\n )),\n sortby = \"name\",\n comment = S3PopupLink(c = \"vulnerability\",\n f = \"hazard\",\n title = T(\"Create Hazard\"),\n ),\n )\n\n self.configure(tablename,\n deduplicate = S3Duplicate(),\n )\n\n # ---------------------------------------------------------------------\n # Pass names back to global scope (s3.*)\n #\n return {\"vulnerability_hazard_id\": hazard_id,\n }\n\n # -------------------------------------------------------------------------\n @staticmethod\n def defaults():\n \"\"\"\n Return safe defaults for model globals, this will be called instead\n of model() in case the model has been deactivated in\n deployment_settings.\n \"\"\"\n\n return {\"vulnerability_hazard_id\": S3ReusableField.dummy(\"hazard_id\"),\n }\n\n# =============================================================================\nclass RiskModel(S3Model):\n \"\"\"\n Risks\n \"\"\"\n\n names = (\"vulnerability_risk\",\n #\"vulnerability_risk_group\",\n \"vulnerability_risk_tag\",\n )\n\n def model(self):\n\n T = current.T\n\n add_components = self.add_components\n define_table = self.define_table\n\n # ---------------------------------------------------------------------\n # Risks\n #\n tablename = \"vulnerability_risk\"\n define_table(tablename,\n self.super_link(\"doc_id\", \"doc_entity\"),\n Field(\"name\", notnull=True,\n label = T(\"Name\"),\n requires = IS_NOT_EMPTY(),\n ),\n self.vulnerability_hazard_id(),\n self.gis_location_id(\n widget = S3LocationSelector(#catalog_layers=True,\n points = False,\n polygons = True,\n ),\n ),\n s3_comments(),\n *s3_meta_fields())\n\n ADD_RISK = T(\"Create Risk\")\n current.response.s3.crud_strings[tablename] = Storage(\n label_create = ADD_RISK,\n title_display = T(\"Risk Details\"),\n title_list = T(\"Risks\"),\n title_update = T(\"Edit Risk\"),\n label_list_button = T(\"List Risks\"),\n label_delete_button = T(\"Delete Risk\"),\n msg_record_created = T(\"Risk added\"),\n msg_record_modified = T(\"Risk updated\"),\n msg_record_deleted = T(\"Risk deleted\"),\n msg_list_empty = T(\"No Risks currently registered\"),\n )\n\n self.configure(tablename,\n super_entity = \"doc_entity\",\n )\n\n # Reusable Field\n represent = S3Represent(lookup = tablename)\n risk_id = S3ReusableField(\"risk_id\", \"reference %s\" % tablename,\n label = T(\"Risk\"),\n ondelete = \"CASCADE\",\n represent = represent,\n requires = IS_EMPTY_OR(\n IS_ONE_OF(current.db, \"vulnerability_risk.id\",\n represent,\n sort = True,\n )),\n sortby = \"name\",\n comment = S3PopupLink(c = \"vulnerability\",\n f = \"risk\",\n title = ADD_RISK,\n ),\n )\n\n # Components\n add_components(tablename,\n # Tags\n vulnerability_risk_tag = {\"name\": \"tag\",\n \"joinby\": \"risk_id\",\n },\n ## Coalitions\n #org_group = {\"link\": \"vulnerability_risk_group\",\n # \"joinby\": \"risk_id\",\n # \"key\": \"group_id\",\n # \"actuate\": \"hide\",\n # },\n ## Format for InlineComponent/filter_widget\n #vulnerability_risk_group = \"risk_id\",\n )\n\n # ---------------------------------------------------------------------\n # Risk Tags\n # - Key-Value extensions\n # - can be used to identify a Source\n # - can be used to add extra attributes for filtering &/or styling\n # - can link Risks to other Systems\n # - can be a Triple Store for Semantic Web support\n #\n tablename = \"vulnerability_risk_tag\"\n define_table(tablename,\n risk_id(),\n # key is a reserved word in MySQL\n Field(\"tag\",\n label = T(\"Key\"),\n ),\n Field(\"value\",\n label = T(\"Value\"),\n ),\n s3_comments(),\n *s3_meta_fields())\n\n # ---------------------------------------------------------------------\n # Risks <> Coalitions link table\n #\n #tablename = \"vulnerability_risk_group\"\n #define_table(tablename,\n # risk_id(),\n # self.org_group_id(empty = False),\n # *s3_meta_fields())\n\n # Pass names back to global scope (s3.*)\n return None\n\n# =============================================================================\ndef vulnerability_aggregated_period(data_date=None):\n \"\"\"\n This will return the start and end dates of the aggregated time\n period.\n\n Currently the time period is annually so it will return the start\n and end of the current year.\n \"\"\"\n\n if data_date is None:\n data_date = date.today()\n year = data_date.year\n soap = date(year, 1, 1)\n eoap = date(year, 12, 31)\n return (soap, eoap)\n\n# =============================================================================\ndef vulnerability_resilience_id():\n \"\"\"\n Return the parameter_id of the resilience indicator\n \"\"\"\n\n if VulnerabilityModel.resilience_pid is None:\n # Get the parameter_id of the aggregated_indicator\n db = current.db\n table = db.vulnerability_aggregated_indicator\n row = db(table.uuid == \"Resilience\").select(table.parameter_id,\n limitby = (0, 1),\n ).first()\n try:\n VulnerabilityModel.resilience_pid = row.parameter_id\n except:\n # DB not initialised\n pass\n\n return VulnerabilityModel.resilience_pid\n\n# =============================================================================\ndef vulnerability_pids():\n \"\"\"\n Return a list of the parameter_id's that are to be used when\n calculating the resilience indicator\n \"\"\"\n\n if VulnerabilityModel.indicator_pids is None:\n db = current.db\n table = db.vulnerability_indicator\n rows = db(table.deleted == False).select(table.parameter_id)\n VulnerabilityModel.indicator_pids = [i.parameter_id for i in rows]\n\n return VulnerabilityModel.indicator_pids\n\n# =============================================================================\ndef vulnerability_rheader(r, tabs=None):\n \"\"\" Vulnerability Resource Headers \"\"\"\n\n if r.representation != \"html\":\n # RHeaders only used in interactive views\n return None\n record = r.record\n if record is None:\n # List or Create form: rheader makes no sense here\n return None\n\n table = r.table\n resourcename = r.name\n T = current.T\n\n if resourcename == \"risk\":\n # Tabs\n tabs = [(T(\"Basic Details\"), None),\n (T(\"Tags\"), \"tag\"),\n ]\n rheader_tabs = s3_rheader_tabs(r, tabs)\n rheader = DIV(TABLE(TR(TH(\"%s: \" % table.name.label),\n record.name\n ),\n ),\n rheader_tabs,\n )\n\n return rheader\n\n# =============================================================================\ndef vulnerability_resilience(#location_level,\n location_id,\n resilience_pid,\n indicator_pids,\n date_period_start,\n date_period_end,\n use_location,\n ):\n \"\"\"\n Calculates the resilience held in the vulnerability_data table\n for a specific location and time period.\n\n This is run async within vulnerability_update_aggregates\n\n Where appropriate add test cases to modules/unit_tests/s3db/vulnerability.py\n \"\"\"\n\n # @ToDo: Make this configurable\n location_level = \"L3\"\n\n db = current.db\n s3db = current.s3db\n vtable = s3db.vulnerability_data\n atable = db.vulnerability_aggregate\n\n # Get the approved data from the vulnerability_data table\n query = (vtable.deleted != True) & \\\n (vtable.approved_by != None) & \\\n (vtable.parameter_id.belongs(indicator_pids))\n ward_count = 1\n if use_location:\n query &= (vtable.location_id == location_id)\n else:\n # Get all the child locations\n child_locations = current.gis.get_children(location_id, location_level)\n child_ids = [row.id for row in child_locations]\n ward_count = len(child_ids)\n query &= (vtable.location_id.belongs(child_ids))\n\n if date_period_end is None:\n pass\n elif date_period_end == \"None\":\n date_period_end = None\n else:\n query &= (vtable.date <= date_period_end)\n rows = db(query).select(vtable.parameter_id,\n vtable.location_id,\n vtable.value,\n vtable.date,\n orderby = (vtable.location_id,\n vtable.parameter_id,\n ~vtable.date,\n ),\n )\n\n # The query may return duplicate records for the same\n # location+parameter: use the most recent, which because\n # of the ordering will be the first\n values = []\n append = values.append\n locations = []\n new_location = locations.append\n last_record = (0, 0)\n for row in rows:\n value = row.value\n if not value:\n continue\n l = row.location_id\n key = (l, row.parameter_id)\n if last_record != key:\n last_record = key\n append(value)\n if l not in locations:\n new_location(l)\n\n # Aggregate the values\n values_len = len(values)\n if not values_len:\n return\n\n values_sum = sum(values)\n values_min = min(values)\n values_max = max(values)\n values_avg = float(values_sum) / values_len\n\n from numpy import median\n values_med = median(values)\n values_mad = median([abs(v - values_med) for v in values])\n\n reported_count = len(locations)\n\n # Store Resilience value in the vulnerability_aggregate table\n query = (atable.location_id == location_id) & \\\n (atable.date == date_period_start) & \\\n (atable.parameter_id == resilience_pid)\n record = db(query).select(atable.id,\n limitby = (0, 1),\n ).first()\n\n if record:\n # Update\n db(query).update(date = date_period_start,\n end_date = date_period_end,\n reported_count = reported_count,\n ward_count = ward_count,\n min = values_min,\n max = values_max,\n mean = values_avg,\n median = values_med,\n mad = values_mad,\n )\n else:\n # Insert new\n atable.insert(agg_type = 4, # indicator\n parameter_id = resilience_pid,\n location_id = location_id,\n date = date_period_start,\n end_date = date_period_end,\n reported_count = reported_count,\n ward_count = ward_count,\n min = values_min,\n max = values_max,\n mean = values_avg,\n median = values_med,\n mad = values_mad,\n )\n\n# =============================================================================\ndef vulnerability_rebuild_all_aggregates():\n \"\"\"\n This will delete all the vulnerability_aggregate records and then\n rebuild them by triggering off a request for each\n\n vulnerability_data record.\n\n This function is normally only run during prepop or postpop so we\n don't need to worry about the aggregate data being unavailable for\n any length of time\n \"\"\"\n\n # Check to see whether an existing task is running and if it is then kill it\n db = current.db\n ttable = db.scheduler_task\n rtable = db.scheduler_run\n wtable = db.scheduler_worker\n query = (ttable.task_name == \"vulnerability_update_aggregates\") & \\\n (rtable.task_id == ttable.id) & \\\n (rtable.status == \"RUNNING\")\n rows = db(query).select(rtable.id,\n rtable.task_id,\n rtable.worker_name,\n )\n now = current.request.utcnow\n for row in rows:\n db(wtable.worker_name == row.worker_name).update(status = \"KILL\")\n db(rtable.id == row.id).update(stop_time = now,\n status = \"STOPPED\")\n db(ttable.id == row.task_id).update(stop_time = now,\n status = \"STOPPED\",\n )\n\n # Delete the existing aggregates\n current.s3db.vulnerability_aggregate.truncate()\n\n # Read all the approved vulnerability_data records\n dtable = db.vulnerability_data\n query = (dtable.deleted != True) & \\\n (dtable.approved_by != None)\n records = db(query).select(dtable.data_id,\n dtable.parameter_id,\n dtable.date,\n dtable.location_id,\n dtable.value,\n )\n\n # Fire off a rebuild task\n current.s3task.run_async(\"vulnerability_update_aggregates\",\n vars = {\"records\": records.json()},\n timeout = 21600 # 6 hours\n )\n\n# =============================================================================\ndef vulnerability_update_aggregates(records=None):\n \"\"\"\n This will calculate the vulnerability_aggregates for the specified\n records. Either all (when rebuild_all is invoked) or for the\n individual parameter(s) at the specified location(s) when run\n onapprove - which currently happens inside the approve_report()\n controller.\n\n This will get the raw data from vulnerability_data and generate a\n vulnerability_aggregate record for the given time period.\n\n The reason for doing this is so that all aggregated data can be\n obtained from a single table. So when displaying data for a\n particular location it will not be necessary to try the aggregate\n table, and if it's not there then try the data table. Rather just\n look at the aggregate table.\n\n Once this has run then a complete set of aggregate records should\n exists for this parameter_id and location for every time period from\n the first data item until the current time period.\n\n Where appropriate add test cases to modules/unit_tests/s3db/vulnerability.py\n \"\"\"\n\n if isinstance(records, str) and records:\n records = json.loads(records)\n if not records:\n return\n\n import datetime\n from dateutil.rrule import rrule, YEARLY\n\n db = current.db\n s3db = current.s3db\n dtable = s3db.vulnerability_data\n atable = db.vulnerability_aggregate\n gtable = db.gis_location\n\n # Data Structures used for the OPTIMISATION steps\n param_location_dict = {} # a list of locations for each parameter\n location_dict = {} # a list of locations\n #loc_level_list = {} # a list of levels for each location\n\n vulnerability_pids = vulnerability_pids()\n\n if isinstance(records[0][\"date\"], (datetime.date, datetime.datetime)):\n from_json = False\n else:\n from_json = True\n from dateutil.parser import parse\n\n for record in records:\n data_id = record[\"data_id\"]\n location_id = record[\"location_id\"]\n parameter_id = record[\"parameter_id\"]\n # Skip if either the location or the parameter is not valid\n if not location_id or not parameter_id:\n current.log.warning(\"Skipping bad vulnerability_data record with data_id %s \" % data_id)\n continue\n if from_json:\n date = parse(record[\"date\"])\n else:\n date = record[\"date\"]\n (start_date, end_date) = vulnerability_aggregated_period(date)\n\n # Get all the approved vulnerability_data records for this location and parameter\n query = (dtable.location_id == location_id) & \\\n (dtable.parameter_id == parameter_id) & \\\n (dtable.deleted != True) & \\\n (dtable.approved_by != None)\n data_rows = db(query).select(dtable.data_id,\n dtable.date,\n dtable.value,\n )\n\n # Get each record and store them in a dict keyed on the start date\n # of the aggregated period. If a record already exists for the\n # reporting period then the most recent value will be stored.\n earliest_period = start_date\n (last_period, end_date) = vulnerability_aggregated_period(None)\n data = {}\n data[start_date] = Storage(date = date,\n id = data_id,\n value = record[\"value\"],\n )\n for row in data_rows:\n if row.data_id == data_id:\n # This is the record we started with, so skip\n continue\n row_date = row.date\n (start_date, end_date) = vulnerability_aggregated_period(row_date)\n if start_date in data:\n if row_date <= data[start_date][\"date\"]:\n # The indicator in the row is of the same time period as\n # another which is already stored in data but it is earlier\n # so ignore this particular record\n continue\n elif start_date < earliest_period:\n earliest_period = start_date\n # Store the record from the db in the data storage\n data[start_date] = Storage(date = row_date,\n id = row.data_id,\n value = row.value)\n\n # Get all the aggregate records for this parameter and location\n query = (atable.location_id == location_id) & \\\n (atable.parameter_id == parameter_id)\n aggr_rows = db(query).select(atable.id,\n atable.agg_type,\n atable.date,\n atable.end_date,\n atable.mean,\n )\n\n aggr = {}\n for row in aggr_rows:\n (start_date, end_date) = vulnerability_aggregated_period(row.date)\n aggr[start_date] = Storage(id = row.id,\n type = row.agg_type,\n end_date = row.end_date,\n mean = row.mean,\n )\n\n # Step through each period and check that aggr is correct\n last_data_period = earliest_period\n last_type_agg = False # Whether the type of previous non-copy record was aggr\n last_data_value = None # The value of the previous aggr record\n # Keep track of which periods the aggr record has been changed in\n # the database\n changed_periods = []\n for dt in rrule(YEARLY, dtstart=earliest_period, until=last_period):\n # Calculate the end of the dt period.\n # - it will be None if this is the last period\n dt = dt.date()\n if dt != last_period:\n (start_date, end_date) = vulnerability_aggregated_period(dt)\n else:\n start_date = dt\n end_date = None\n if dt in aggr:\n # Check that the stored aggr data is correct\n agg_type = aggr[dt][\"type\"]\n if agg_type == 2:\n # This is built using other location aggregates\n # so it can be ignored because only time or copy aggregates\n # are being calculated in this function\n last_type_agg = True\n last_data_value = aggr[dt][\"mean\"]\n continue\n # Query to use to update aggr records\n query = (atable.id == aggr[dt][\"id\"])\n if agg_type == 3:\n # This is a copy aggregate\n if dt in data:\n # There is data in the data dictionary for this period\n # so aggregate record needs to be changed\n value = data[dt][\"value\"]\n last_data_value = value\n db(query).update(agg_type = 1, # time\n reported_count = 1, # one record\n ward_count = 1, # one ward\n end_date = end_date,\n sum = value,\n min = value,\n max = value,\n mean = value,\n median = value,\n )\n changed_periods.append((start_date, end_date))\n elif last_type_agg:\n # No data in the data dictionary and the last type was aggr\n continue\n # Check that the data currently stored is correct\n elif aggr[dt][\"mean\"] != last_data_value:\n value = last_data_value\n db(query).update(agg_type = 3, # copy\n reported_count = 1, # one record\n ward_count = 1, # one ward\n end_date = end_date,\n sum = value,\n min = value,\n max = value,\n mean = value,\n median = value,\n )\n changed_periods.append((start_date, end_date))\n elif agg_type == 1:\n if dt in data:\n # The value in the aggr should match the value in data\n value = data[dt][\"value\"]\n last_data_value = value\n if aggr[dt][\"mean\"] != value:\n db(query).update(agg_type = 1, # time\n reported_count = 1, # one record\n ward_count = 1, # one ward\n end_date = end_date,\n sum = value,\n min = value,\n max = value,\n mean = value,\n median = value,\n )\n changed_periods.append((start_date, end_date))\n else:\n # The data is not there so it must have been deleted\n # Copy the value from the previous record\n value = last_data_value\n db(query).update(agg_type = 3, # copy\n reported_count = 1, # one record\n ward_count = 1, # one ward\n end_date = end_date,\n sum = value,\n min = value,\n max = value,\n mean = value,\n median = value,\n )\n changed_periods.append((start_date, end_date))\n # No aggregate record for this time period exists\n # So one needs to be inserted\n else:\n if dt in data:\n value = data[dt][\"value\"]\n agg_type = 1 # time\n last_data_value = value\n else:\n value = last_data_value\n agg_type = 3 # copy\n atable.insert(parameter_id = parameter_id,\n location_id = location_id,\n agg_type = agg_type,\n reported_count = 1, # one record\n ward_count = 1, # one ward\n date = start_date,\n end_date = end_date,\n sum = value,\n min = value,\n max = value,\n mean = value,\n median = value,\n )\n changed_periods.append((start_date, end_date))\n # End of loop through each time period\n\n if changed_periods == []:\n continue\n # The following structures are used in the OPTIMISATION steps later\n #location = db(gtable.id == location_id).select(gtable.level,\n # limitby=(0, 1)\n # ).first()\n #loc_level_list[location_id] = location.level\n if parameter_id not in param_location_dict:\n param_location_dict[parameter_id] = {location_id : changed_periods}\n elif location_id not in param_location_dict[parameter_id]:\n param_location_dict[parameter_id][location_id] = changed_periods\n else:\n # Store the older of the changed periods (the end will always be None)\n # Only need to check the start date of the first period\n if changed_periods[0][0] < param_location_dict[parameter_id][location_id][0][0]:\n param_location_dict[parameter_id][location_id] = changed_periods\n if parameter_id in vulnerability_pids:\n if location_id not in location_dict:\n location_dict[location_id] = changed_periods\n else:\n # Store the older of the changed periods (the end will always be None)\n # Only need to check the start date of the first period\n if changed_periods[0][0] < location_dict[location_id][0][0]:\n location_dict[location_id] = changed_periods\n\n # End of loop through each vulnerability_data record\n\n # OPTIMISATION step 1\n # The following code will get all the locations for which a parameter\n # has been changed. This will remove duplicates which will occur when\n # items are being imported for many communes in the same district.\n # Take an import of 12 communes in the same district, without this the\n # district will be updated 12 times, the province will be updated 12\n # times and the country will be updated 12 times that is 33 unnecessary\n # updates (for each time period) (i.e. 15 updates rather than 48)\n\n # Get all the parents\n # @ToDo: Optimise by rewriting as custom routine rather than using this wrapper\n # - we only need immediate children not descendants, so can use parent not path\n # - look at disease_stats_update_aggregates()\n parents = {}\n get_parents = current.gis.get_parents\n for loc_id in location_dict.keys():\n parents[loc_id] = get_parents(loc_id)\n # Expand the list of locations for each parameter\n parents_data = {}\n for (param_id, loc_dict) in param_location_dict.items():\n for (loc_id, periods) in loc_dict.items():\n if loc_id in parents: # There won't be a parent if this is a L0\n for p_loc_row in parents[loc_id]:\n p_loc_id = p_loc_row.id\n if param_id in parents_data:\n if p_loc_id in parents_data[param_id]:\n # Store the older of the changed periods (the end will always be None)\n # Only need to check the start date of the first period\n if periods[0][0] < parents_data[param_id][p_loc_id][0][0][0]:\n parents_data[param_id][p_loc_id][0] = periods\n else:\n parents_data[param_id][p_loc_id] = [periods,\n #loc_level_list[loc_id]\n ]\n else:\n parents_data[param_id] = {p_loc_id : [periods,\n #loc_level_list[loc_id]\n ]\n }\n\n # Now that the time aggregate types have been set up correctly,\n # fire off requests for the location aggregates to be calculated\n run_async = current.s3task.run_async\n for (param_id, loc_dict) in parents_data.items():\n #for (loc_id, (changed_periods, loc_level)) in loc_dict.items():\n for (loc_id, (changed_periods,)) in loc_dict.items():\n for (start_date, end_date) in changed_periods:\n s, e = str(start_date), str(end_date)\n run_async(\"vulnerability_update_location_aggregate\",\n args = [#loc_level,\n loc_id, param_id, s, e],\n timeout = 1800 # 30m\n )\n\n # OPTIMISATION step 2\n # Get all the locations for which the resilence indicator needs to be\n # recalculated. Without this the calculations will be triggered for\n # each parameter and for each location unnecessarily.\n # For example an import of 12 communes in the same district with data\n # for the 10 parameters that make up the resilence calculation will trigger\n # 480 updates, rather than the optimal 15, for each time period.\n resilence_parents = {}\n for (loc_id, periods) in location_dict.items():\n #resilence_parents[loc_id] = (periods, loc_level_list[loc_id], True)\n resilence_parents[loc_id] = (periods, True)\n for p_loc_row in parents[loc_id]:\n p_loc_id = p_loc_row.id\n if p_loc_id in resilence_parents:\n # Store the older of the changed periods (the end will always be None)\n # Only need to check the start date of the first period\n if periods[0][0] < resilence_parents[p_loc_id][0][0][0]:\n resilence_parents[p_loc_id][0] = periods\n else:\n #resilence_parents[p_loc_id] = [periods, loc_level_list[loc_id], False]\n resilence_parents[p_loc_id] = [periods, False]\n\n # Now calculate the resilience indicators\n resilience_pid = vulnerability_resilience_id()\n #for (location_id, (period, loc_level, use_location)) in resilence_parents.items():\n for (location_id, (period, use_location)) in resilence_parents.items():\n for (start_date, end_date) in changed_periods:\n vulnerability_resilience(#loc_level,\n location_id,\n resilience_pid,\n vulnerability_pids,\n start_date,\n end_date,\n use_location,\n )\n\n# =============================================================================\ndef vulnerability_update_location_aggregate(#location_level,\n location_id,\n parameter_id,\n start_date,\n end_date\n ):\n \"\"\"\n Calculates the vulnerability_aggregate for a specific parameter at a\n specific location and time.\n\n Args:\n location_id: the location record ID\n parameter_id: the parameter record ID\n start_date: the start date of the time period (as string)\n end_date: the end date of the time period (as string)\n \"\"\"\n\n # @ToDo: Make this configurable\n location_level = \"L3\"\n\n db = current.db\n\n dtable = current.s3db.vulnerability_data\n atable = db.vulnerability_aggregate\n\n # Get all the child locations (immediate children only, not all descendants)\n child_locations = current.gis.get_children(location_id, location_level)\n child_ids = [row.id for row in child_locations]\n\n # Get the most recent vulnerability_data record for all child locations\n query = (dtable.parameter_id == parameter_id) & \\\n (dtable.deleted != True) & \\\n (dtable.approved_by != None) & \\\n (dtable.location_id.belongs(child_ids))\n if end_date == \"None\": # converted to string as async parameter\n end_date = None\n else:\n query &= (dtable.date <= end_date)\n rows = db(query).select(dtable.value,\n dtable.date,\n dtable.location_id,\n orderby = (dtable.location_id, ~dtable.date),\n # groupby avoids duplicate records for the same\n # location, but is slightly slower than just\n # skipping the duplicates in the loop below\n #groupby=(dtable.location_id)\n )\n\n # Collect the values, skip duplicate records for the\n # same location => use the most recent one, which is\n # the first row for each location as per the orderby\n # in the query above\n last_location = None\n values = []\n append = values.append\n for row in rows:\n new_location_id = row.location_id\n if new_location_id != last_location:\n last_location = new_location_id\n append(row.value)\n\n # Aggregate the values\n values_len = len(values)\n if not values_len:\n return\n\n values_sum = sum(values)\n values_min = min(values)\n values_max = max(values)\n values_avg = float(values_sum) / values_len\n\n from numpy import median\n values_med = median(values)\n values_mad = median([abs(v - values_med) for v in values])\n\n # Add or update the aggregated values in the database\n\n # Do we already have a record?\n query = (atable.location_id == location_id) & \\\n (atable.parameter_id == parameter_id) & \\\n (atable.date == start_date) & \\\n (atable.end_date == end_date)\n exists = db(query).select(atable.id, \n limitby = (0, 1),\n ).first()\n\n attr = {\"agg_type\": 2, # Location\n \"reported_count\": values_len,\n \"ward_count\": len(child_ids),\n \"min\": values_min,\n \"max\": values_max,\n \"mean\": values_avg,\n \"median\": values_med,\n \"mad\": values_mad,\n \"sum\": values_sum,\n }\n if exists:\n # Update\n db(query).update(**attr)\n else:\n # Insert new\n atable.insert(parameter_id = parameter_id,\n location_id = location_id,\n date = start_date,\n end_date = end_date,\n **attr\n )\n\n# END =========================================================================\n" ]
[ [ "numpy.median" ] ]
nahanoo/black_queen_hypothesis
[ "3b358457a0ea068b0f75c1bfb91b29be7aa59758" ]
[ "scripts/trajectories.py" ]
[ "import vcfpy\nfrom samples import Samples\nfrom os.path import join, exists\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom Bio import SeqIO\nfrom colour import Color\n\ns = Samples()\n\n\nclass SNPs:\n def __init__(self, filter=20, parse=False):\n if parse:\n self.snps = {strain: [] for strain in s.strains}\n for strain, samples in s.strains.items():\n for sample in samples:\n if sample['platform'] == 'illumina':\n snps = []\n f = join(sample['dir_name'], 'var.vcf')\n if exists(f):\n reader = vcfpy.Reader.from_path(f)\n for record in reader:\n snp = {}\n snp['chrom'] = record.CHROM\n snp['pos'] = record.POS\n snp['qual'] = record.QUAL\n snp['depth'] = record.INFO['DP']\n snp['freq_sum'] = sum(\n record.INFO['AO'])/record.INFO['DP']\n snp['alt_depth_sum'] = sum(record.INFO['AO'])\n snp['alt_depth'] = record.INFO['AO']\n snp['freq'] = [freq / record.INFO['DP']\n for freq in record.INFO['AO']]\n snp['alt'] = record.ALT\n snp['af'] = record.INFO['AF']\n if filter is None:\n snps.append(snp)\n else:\n if snp['qual'] >= filter:\n snps.append(snp)\n else:\n if strain == s.abbreviations['at']:\n print(f)\n sample['snps'] = snps\n self.snps[strain].append(sample)\n else:\n self.df = pd.read_csv(join(s.work, 'bulk', 'snps.csv'))\n\n def join_genbank(self):\n genbanks = {}\n for strain in s.strains:\n f = s.references[strain].replace('.fasta', '_stripped.gbk')\n contigs = [contig for contig in SeqIO.parse(\n f, 'genbank')]\n genbank = {contig.id: {} for contig in contigs}\n for contig in contigs:\n for feature in contig.features:\n # Some features don't have all desired keys\n try:\n start = feature.location.start\n end = feature.location.end\n product = feature.qualifiers['product']\n genbank[contig.id][(start, end)] = product[0]\n except KeyError:\n pass\n genbanks[strain] = genbank\n for strain, samples in self.snps.items():\n for sample in samples:\n for snp in sample['snps']:\n snp['product'] = 'intergenic'\n for (start, end), product in genbanks[strain][snp['chrom']].items():\n if (snp['pos'] >= start) & (snp['pos'] <= end):\n snp['product'] = product\n\n def get_data_frame(self, strain, filter_genes=False):\n self.df = pd.DataFrame(\n columns=['micro_treat', 'timepoint', 'freq', 'qual', 'color', 'product'])\n i = 0\n for sample in self.snps[strain]:\n for snp in sample['snps']:\n key = '.'.join([str(item) for item in [snp['chrom'],\n snp['pos'], sample['treatment'], sample['cosm']]])\n self.df.at[i, 'freq'] = snp['freq_sum']\n self.df.at[i, 'micro_treat'] = str(\n sample['treatment']) + '.' + str(sample['cosm'])\n self.df.at[i, 'timepoint'] = sample['timepoint']\n self.df.at[i, 'qual'] = snp['qual']\n self.df.at[i, 'color'] = key\n self.df.at[i, 'product'] = snp['product']\n i += 1\n\n if filter_genes:\n self.df = self.df.drop_duplicates(\n ['product', 'timepoint', 'micro_treat'])\n\n def plot_phred_score(self, out):\n fig = px.histogram(self.df, x='qual', facet_col='micro_treat', log_y=True,\n facet_col_wrap=5, title='SNP phred scores',\n category_orders={'micro_treat': list(sorted(self.df['micro_treat']))})\n fig.write_html(out + '_phred_score.html')\n\n def plot_trajectories(self, out):\n mask = []\n for snp in self.df['color']:\n if len(set(self.df[self.df['color'] == snp]['timepoint'])) > 1:\n mask.append(True)\n else:\n mask.append(False)\n df = self.df[mask]\n df = df.sort_values('product')\n\n products = {product: None for product in set(df['product'])}\n products = dict(sorted(products.items()))\n color_range = (Color(\"purple\"), Color(\"orange\"))\n spectrum = list(color_range[0].range_to(\n color_range[1], len(products.keys())))\n\n for product, color in zip(products, spectrum):\n products[product] = color.get_hex()\n\n colors = {}\n for snp, product in zip(df['color'], df['product']):\n colors[snp] = products[product]\n\n labels = {snp: product for snp, product in zip(\n df['color'], df['product'])}\n\n fig = px.line(df, x='timepoint', y='freq', line_group='color',color='product',\n facet_col='micro_treat', facet_col_wrap=5,\n hover_data=['product'],\n category_orders={'micro_treat': list(\n sorted(self.df['micro_treat']))},\n color_discrete_map=products)\n fig.update_xaxes(categoryorder='array', categoryarray=[\n 'T11', 'T22', 'T33', 'T44'])\n #fig.update_traces(showlegend=True)\n fig.write_html(out + '_trajectories.html')\n \"\"\"names = set()\n fig.for_each_trace(\n lambda trace:\n trace.update(showlegend=False)\n if (trace.name in names) else names.add(trace.name))\"\"\"\n return fig\n\n def plot_frequencies(self, out):\n fig = px.histogram(self.df, x='freq', facet_col='micro_treat', log_y=True,\n facet_col_wrap=4, title='SNP frequencies',\n category_orders={'micro_treat': list(sorted(self.df['micro_treat']))})\n fig.write_html(out + '_frequencies.html')\n\n def plot_products(self, out):\n fig = px.histogram(self.df, x='product', facet_col='micro_treat', log_y=True,\n facet_col_wrap=5, title='SNP frequencies',\n category_orders={'micro_treat': list(sorted(self.df['micro_treat']))})\n fig.update_xaxes(showticklabels=False)\n fig.update_xaxes(categoryorder='array',\n categoryarray=list(set(self.df['product'])))\n fig.write_html(out + '_products.html')\n\n\nsnps = SNPs(filter=0,parse=True)\nsnps.join_genbank()\nstrain = s.abbreviations['ms']\nout = s.abbreviations[strain]\nsnps.get_data_frame(strain)\n# snps.plot_products(out)\nfig = snps.plot_trajectories(out)\n# snps.plot_phred_score(out)\n# snps.plot_frequencies(out)\n# snps.plot_trajectories(out)\n# snps.get_data_frame(strain,filter_genes=True)\n#out = 'unique_genes_' + out\n# snps.plot_frequencies(out)\n# snps.plot_trajectories(out)\n\"\"\"freqs = snps.plot_trajectories()\ncosms = set(freqs['micro_treat'])\nfor cosm in cosms:\n tmp = freqs[freqs['micro_treat'] == cosm]\n print(cosm,len(tmp))\"\"\"\n" ]
[ [ "pandas.DataFrame" ] ]
danyfang/SourceCode
[ "8168f6058648f2a330a7354daf3a73a4d8a4e730" ]
[ "ml/morvan/sklearn/sk8_cross_validation.py" ]
[ "# View more python learning tutorial on my Youtube and Youku channel!!!\n\n# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg\n# Youku video tutorial: http://i.youku.com/pythontutorial\n\n\"\"\"\nPlease note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.\n\"\"\"\nfrom __future__ import print_function\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\n\niris = load_iris()\nX = iris.data\ny = iris.target\n\n# test train split #\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=4)\nknn = KNeighborsClassifier(n_neighbors=5)\nknn.fit(X_train, y_train)\ny_pred = knn.predict(X_test)\nprint(knn.score(X_test, y_test))\n\n# this is cross_val_score #\nfrom sklearn.model_selection import cross_val_score\nknn = KNeighborsClassifier(n_neighbors=5)\nscores = cross_val_score(knn, X, y, cv=5, scoring='accuracy')\nprint(scores)\n\n# this is how to use cross_val_score to choose model and configs #\nimport matplotlib.pyplot as plt\nk_range = range(1, 31)\nk_scores = []\nfor k in k_range:\n knn = KNeighborsClassifier(n_neighbors=k)\n## loss = -cross_val_score(knn, X, y, cv=10, scoring='mean_squared_error') # for regression\n scores = cross_val_score(knn, X, y, cv=10, scoring='accuracy') # for classification\n k_scores.append(scores.mean())\n\nplt.plot(k_range, k_scores)\nplt.xlabel('Value of K for KNN')\nplt.ylabel('Cross-Validated Accuracy')\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n" ]
[ [ "sklearn.model_selection.cross_val_score", "sklearn.datasets.load_iris", "sklearn.model_selection.train_test_split", "sklearn.neighbors.KNeighborsClassifier", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
ihmeuw/vivarium_gates_child_iv_iron
[ "dd89b2161c636e4d03669bd91ba49824dad27a1d" ]
[ "src/vivarium_gates_child_iv_iron/data/builder.py" ]
[ "\"\"\"Modularized functions for building project data artifacts.\n\nThis module is an abstraction around the load portion of our artifact building ETL pipeline.\nThe intent is to be declarative so it's easy to see what is put into the artifact and how.\nSome degree of verbosity/boilerplate is fine in the interest of transparency.\n\n.. admonition::\n\n Logging in this module should be done at the ``debug`` level.\n\n\"\"\"\nfrom pathlib import Path\n\nfrom loguru import logger\nimport pandas as pd\nfrom vivarium.framework.artifact import Artifact, EntityKey\n\nfrom vivarium_gates_child_iv_iron.constants import data_keys\nfrom vivarium_gates_child_iv_iron.data import loader\n\n\ndef open_artifact(output_path: Path, location: str) -> Artifact:\n \"\"\"Creates or opens an artifact at the output path.\n\n Parameters\n ----------\n output_path\n Fully resolved path to the artifact file.\n location\n Proper GBD location name represented by the artifact.\n\n Returns\n -------\n A new artifact.\n\n \"\"\"\n if not output_path.exists():\n logger.debug(f\"Creating artifact at {str(output_path)}.\")\n else:\n logger.debug(f\"Opening artifact at {str(output_path)} for appending.\")\n\n artifact = Artifact(output_path)\n\n key = data_keys.METADATA_LOCATIONS\n if key not in artifact:\n artifact.write(key, [location])\n\n return artifact\n\n\ndef load_and_write_data(artifact: Artifact, key: str, location: str, replace: bool):\n \"\"\"Loads data and writes it to the artifact if not already present.\n\n Parameters\n ----------\n artifact\n The artifact to write to.\n key\n The entity key associated with the data to write.\n location\n The location associated with the data to load and the artifact to\n write to.\n replace\n Flag which determines whether to overwrite existing data\n\n \"\"\"\n if key in artifact and not replace:\n logger.debug(f'Data for {key} already in artifact. Skipping...')\n else:\n logger.debug(f'Loading data for {key} for location {location}.')\n data = loader.get_data(key, location)\n if key not in artifact:\n logger.debug(f'Writing data for {key} to artifact.')\n artifact.write(key, data)\n else: # key is in artifact, but should be replaced\n logger.debug(f'Replacing data for {key} in artifact.')\n artifact.replace(key, data)\n return artifact.load(key)\n\n\ndef write_data(artifact: Artifact, key: str, data: pd.DataFrame):\n \"\"\"Writes data to the artifact if not already present.\n\n Parameters\n ----------\n artifact\n The artifact to write to.\n key\n The entity key associated with the data to write.\n data\n The data to write.\n\n \"\"\"\n if key in artifact:\n logger.debug(f'Data for {key} already in artifact. Skipping...')\n else:\n logger.debug(f'Writing data for {key} to artifact.')\n artifact.write(key, data)\n return artifact.load(key)\n\n\n# TODO - writing and reading by draw is necessary if you are using\n# LBWSG data. Find the read function in utilities.py\ndef write_data_by_draw(artifact: Artifact, key: str, data: pd.DataFrame):\n \"\"\"Writes data to the artifact on a per-draw basis. This is useful\n for large datasets like Low Birthweight Short Gestation (LBWSG).\n\n Parameters\n ----------\n artifact\n The artifact to write to.\n key\n The entity key associated with the data to write.\n data\n The data to write.\n\n \"\"\"\n with pd.HDFStore(artifact.path, complevel=9, mode='a') as store:\n key = EntityKey(key)\n artifact._keys.append(key)\n store.put(f'{key.path}/index', data.index.to_frame(index=False))\n data = data.reset_index(drop=True)\n for c in data.columns:\n store.put(f'{key.path}/{c}', data[c])\n" ]
[ [ "pandas.HDFStore" ] ]
hailusong/mrc-for-flat-nested-ner
[ "8e6f023c0d099f689f001817cf0644978c3ed22d" ]
[ "layers/loss_funcs.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*- \n\n\n\n# Author: Xiaoy LI \n# Last update: 2019.03.23 \n# First create: 2019.03.23 \n# Description:\n# loss_funcs_examples.py\n\n\n\nimport os \nimport sys \nimport numpy as np \n\n\n\nroot_path = \"/\".join(os.path.realpath(__file__).split(\"/\")[:-2])\nif root_path not in sys.path:\n sys.path.insert(0, root_path)\n\n\n\nimport torch \nimport torch.nn as nn \nfrom torch.nn import BCEWithLogitsLoss\n\n\ndef nll_loss():\n # input size if N x C = 3 x 5 \n input = torch.randn(3, 5, requires_grad=True)\n # each element in target has to have 0 <= value < C \n target = torch.tensor([1, 0, 4])\n output = F.nll_loss(F.log_softmax(input), target)\n output.backward()\n\n\n\ndef cross_entropy_loss():\n # loss \n loss = nn.CrossEntropyLoss()\n input = torch.randn(3, 5, requires_grad=True)\n target = torch.empty(3, dtype=torch.long).random_(5)\n output = loss(input, target)\n output.backward()\n\n\ndef bce_logits_loss():\n \"\"\"\n Desc:\n Input: math. (N, *) where * means, any number of additional dimensions \n Target: math, (N, *) where the same shape as the input. \n \"\"\"\n loss = nn.BCEWithLogitsLoss()\n input = torch.randn(3, requires_grad=True)\n target = torch.empty(3).random_(2)\n output = loss(input, target)\n output.backward()\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.empty", "torch.randn", "torch.tensor", "torch.nn.BCEWithLogitsLoss" ] ]