repo_name
stringclasses
6 values
pr_number
int64
99
20.3k
pr_title
stringlengths
8
158
pr_description
stringlengths
0
6.54k
author
stringlengths
4
18
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
37
6.57k
filepath
stringlengths
8
153
before_content
stringlengths
0
876M
after_content
stringlengths
0
876M
label
int64
-1
1
tensorflow/graphics
488
Gather barycentrics, triangle indices, mask, etc. into single structure - Framebuffer and use it in rasterization backend.
Gather barycentrics, triangle indices, mask, etc. into single structure - Framebuffer and use it in rasterization backend.
copybara-service[bot]
"2021-01-30T00:32:55Z"
"2021-02-02T20:48:00Z"
e539c142799936d76d84d0861951ed883a9b4673
9d257ad4a72ccf65e4349910b9fff7c0a5648073
Gather barycentrics, triangle indices, mask, etc. into single structure - Framebuffer and use it in rasterization backend.. Gather barycentrics, triangle indices, mask, etc. into single structure - Framebuffer and use it in rasterization backend.
./tensorflow_graphics/geometry/transformation/tests/rotation_matrix_3d_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for 3d rotation matrix.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.geometry.transformation.tests import test_data as td from tensorflow_graphics.geometry.transformation.tests import test_helpers from tensorflow_graphics.util import test_case class RotationMatrix3dTest(test_case.TestCase): @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_assert_rotation_matrix_normalized_passthrough(self): """Checks that the assert is a passthrough when the flag is False.""" angles = test_helpers.generate_preset_test_euler_angles() matrix_input = rotation_matrix_3d.from_euler(angles) matrix_output = rotation_matrix_3d.assert_rotation_matrix_normalized( matrix_input) self.assertTrue(matrix_input is matrix_output) # pylint: disable=g-generic-assert @parameterized.parameters((np.float32), (np.float64)) def test_assert_rotation_matrix_normalized_preset(self, dtype): """Checks that assert_normalized function works as expected.""" angles = test_helpers.generate_preset_test_euler_angles().astype(dtype) matrix = rotation_matrix_3d.from_euler(angles) matrix_rescaled = matrix * 1.01 matrix_normalized = rotation_matrix_3d.assert_rotation_matrix_normalized( matrix) self.evaluate(matrix_normalized) with self.assertRaises(tf.errors.InvalidArgumentError): # pylint: disable=g-error-prone-assert-raises self.evaluate(rotation_matrix_3d.assert_rotation_matrix_normalized( matrix_rescaled)) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ) def test_assert_rotation_matrix_normalized_exception_not_raised( self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( rotation_matrix_3d.assert_rotation_matrix_normalized, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -1", (3, None)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ) def test_assert_rotation_matrix_normalized_exception_raised( self, error_msg, *shapes): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised( rotation_matrix_3d.assert_rotation_matrix_normalized, error_msg, shapes) @parameterized.parameters( ((3,), (1,)), ((None, 3), (None, 1)), ((1, 3), (1, 1)), ((2, 3), (2, 1)), ((1, 3), (1,)), ((3,), (1, 1)), ) def test_from_axis_angle_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.from_axis_angle, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,), (1,)), ("must have exactly 1 dimensions in axis -1", (3,), (None,)), ) def test_from_axis_angle_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.from_axis_angle, error_msg, shapes) def test_from_axis_angle_normalized_preset(self): """Tests that axis-angles can be converted to rotation matrices.""" euler_angles = test_helpers.generate_preset_test_euler_angles() axis, angle = axis_angle.from_euler(euler_angles) matrix_axis_angle = rotation_matrix_3d.from_axis_angle(axis, angle) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_axis_angle), np.ones(euler_angles.shape[0:-1] + (1,))) def test_from_axis_angle_normalized_random(self): """Tests that axis-angles can be converted to rotation matrices.""" tensor_shape = np.random.randint(1, 10, size=np.random.randint(3)).tolist() random_axis = np.random.normal(size=tensor_shape + [3]) random_axis /= np.linalg.norm(random_axis, axis=-1, keepdims=True) random_angle = np.random.normal(size=tensor_shape + [1]) matrix_axis_angle = rotation_matrix_3d.from_axis_angle( random_axis, random_angle) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_axis_angle), np.ones(tensor_shape + [1])) @parameterized.parameters( ((td.AXIS_3D_X, td.ANGLE_45), (td.MAT_3D_X_45,)), ((td.AXIS_3D_Y, td.ANGLE_45), (td.MAT_3D_Y_45,)), ((td.AXIS_3D_Z, td.ANGLE_45), (td.MAT_3D_Z_45,)), ((td.AXIS_3D_X, td.ANGLE_90), (td.MAT_3D_X_90,)), ((td.AXIS_3D_Y, td.ANGLE_90), (td.MAT_3D_Y_90,)), ((td.AXIS_3D_Z, td.ANGLE_90), (td.MAT_3D_Z_90,)), ((td.AXIS_3D_X, td.ANGLE_180), (td.MAT_3D_X_180,)), ((td.AXIS_3D_Y, td.ANGLE_180), (td.MAT_3D_Y_180,)), ((td.AXIS_3D_Z, td.ANGLE_180), (td.MAT_3D_Z_180,)), ) def test_from_axis_angle_preset(self, test_inputs, test_outputs): """Tests that an axis-angle maps to correct matrix.""" self.assert_output_is_correct(rotation_matrix_3d.from_axis_angle, test_inputs, test_outputs) def test_from_axis_angle_random(self): """Tests conversion to matrix.""" tensor_shape = np.random.randint(1, 10, size=np.random.randint(3)).tolist() random_axis = np.random.normal(size=tensor_shape + [3]) random_axis /= np.linalg.norm(random_axis, axis=-1, keepdims=True) random_angle = np.random.normal(size=tensor_shape + [1]) matrix_axis_angle = rotation_matrix_3d.from_axis_angle( random_axis, random_angle) random_quaternion = quaternion.from_axis_angle(random_axis, random_angle) matrix_quaternion = rotation_matrix_3d.from_quaternion(random_quaternion) self.assertAllClose(matrix_axis_angle, matrix_quaternion, rtol=1e-3) # Checks that resulting rotation matrices are normalized. self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_axis_angle), np.ones(tensor_shape + [1])) @parameterized.parameters( ((td.AXIS_3D_X, td.ANGLE_90, td.AXIS_3D_X), (td.AXIS_3D_X,)), ((td.AXIS_3D_X, td.ANGLE_90, td.AXIS_3D_Y), (td.AXIS_3D_Z,)), ((td.AXIS_3D_X, -td.ANGLE_90, td.AXIS_3D_Z), (td.AXIS_3D_Y,)), ((td.AXIS_3D_Y, -td.ANGLE_90, td.AXIS_3D_X), (td.AXIS_3D_Z,)), ((td.AXIS_3D_Y, td.ANGLE_90, td.AXIS_3D_Y), (td.AXIS_3D_Y,)), ((td.AXIS_3D_Y, td.ANGLE_90, td.AXIS_3D_Z), (td.AXIS_3D_X,)), ((td.AXIS_3D_Z, td.ANGLE_90, td.AXIS_3D_X), (td.AXIS_3D_Y,)), ((td.AXIS_3D_Z, -td.ANGLE_90, td.AXIS_3D_Y), (td.AXIS_3D_X,)), ((td.AXIS_3D_Z, td.ANGLE_90, td.AXIS_3D_Z), (td.AXIS_3D_Z,)), ) def test_from_axis_angle_rotate_vector_preset(self, test_inputs, test_outputs): """Tests the directionality of axis-angle rotations.""" def func(axis, angle, point): matrix = rotation_matrix_3d.from_axis_angle(axis, angle) return rotation_matrix_3d.rotate(point, matrix) self.assert_output_is_correct(func, test_inputs, test_outputs) @parameterized.parameters( ((3,),), ((None, 3),), ((2, 3),), ) def test_from_euler_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.from_euler, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,)),) def test_from_euler_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.from_euler, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_jacobian_preset(self): """Test the Jacobian of the from_euler function.""" x_init = test_helpers.generate_preset_test_euler_angles() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_euler, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_jacobian_random(self): """Test the Jacobian of the from_euler function.""" x_init = test_helpers.generate_random_test_euler_angles() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_euler, [x_init]) def test_from_euler_normalized_preset(self): """Tests that euler angles can be converted to rotation matrices.""" euler_angles = test_helpers.generate_preset_test_euler_angles() matrix = rotation_matrix_3d.from_euler(euler_angles) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix), np.ones(euler_angles.shape[0:-1] + (1,))) def test_from_euler_normalized_random(self): """Tests that euler angles can be converted to rotation matrices.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() matrix = rotation_matrix_3d.from_euler(random_euler_angles) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix), np.ones(random_euler_angles.shape[0:-1] + (1,))) @parameterized.parameters( ((td.AXIS_3D_0,), (td.MAT_3D_ID,)), ((td.ANGLE_45 * td.AXIS_3D_X,), (td.MAT_3D_X_45,)), ((td.ANGLE_45 * td.AXIS_3D_Y,), (td.MAT_3D_Y_45,)), ((td.ANGLE_45 * td.AXIS_3D_Z,), (td.MAT_3D_Z_45,)), ((td.ANGLE_90 * td.AXIS_3D_X,), (td.MAT_3D_X_90,)), ((td.ANGLE_90 * td.AXIS_3D_Y,), (td.MAT_3D_Y_90,)), ((td.ANGLE_90 * td.AXIS_3D_Z,), (td.MAT_3D_Z_90,)), ((td.ANGLE_180 * td.AXIS_3D_X,), (td.MAT_3D_X_180,)), ((td.ANGLE_180 * td.AXIS_3D_Y,), (td.MAT_3D_Y_180,)), ((td.ANGLE_180 * td.AXIS_3D_Z,), (td.MAT_3D_Z_180,)), ) def test_from_euler_preset(self, test_inputs, test_outputs): """Tests that Euler angles create the expected matrix.""" self.assert_output_is_correct(rotation_matrix_3d.from_euler, test_inputs, test_outputs) def test_from_euler_random(self): """Tests that Euler angles produce the same result as axis-angle.""" angles = test_helpers.generate_random_test_euler_angles() matrix = rotation_matrix_3d.from_euler(angles) tensor_tile = angles.shape[:-1] x_axis = np.tile(td.AXIS_3D_X, tensor_tile + (1,)) y_axis = np.tile(td.AXIS_3D_Y, tensor_tile + (1,)) z_axis = np.tile(td.AXIS_3D_Z, tensor_tile + (1,)) x_angle = np.expand_dims(angles[..., 0], axis=-1) y_angle = np.expand_dims(angles[..., 1], axis=-1) z_angle = np.expand_dims(angles[..., 2], axis=-1) x_rotation = rotation_matrix_3d.from_axis_angle(x_axis, x_angle) y_rotation = rotation_matrix_3d.from_axis_angle(y_axis, y_angle) z_rotation = rotation_matrix_3d.from_axis_angle(z_axis, z_angle) expected_matrix = tf.matmul(z_rotation, tf.matmul(y_rotation, x_rotation)) self.assertAllClose(expected_matrix, matrix, rtol=1e-3) @parameterized.parameters( ((3,),), ((None, 3),), ) def test_from_euler_with_small_angles_approximation_exception_not_raised( self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( rotation_matrix_3d.from_euler_with_small_angles_approximation, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,)),) def test_from_euler_with_small_angles_approximation_exception_raised( self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised( rotation_matrix_3d.from_euler_with_small_angles_approximation, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_with_small_angles_approximation_jacobian_random(self): """Test the Jacobian of from_euler_with_small_angles_approximation.""" x_init = test_helpers.generate_random_test_euler_angles( min_angle=-0.17, max_angle=0.17) self.assert_jacobian_is_correct_fn( rotation_matrix_3d.from_euler_with_small_angles_approximation, [x_init]) def test_from_euler_with_small_angles_approximation_random(self): """Tests small_angles approximation by comparing to exact calculation.""" # Only generate small angles. For a test tolerance of 1e-3, 0.16 was found # empirically to be the range where the small angle approximation works. random_euler_angles = test_helpers.generate_random_test_euler_angles( min_angle=-0.16, max_angle=0.16) exact_matrix = rotation_matrix_3d.from_euler(random_euler_angles) approximate_matrix = ( rotation_matrix_3d.from_euler_with_small_angles_approximation( random_euler_angles)) self.assertAllClose(exact_matrix, approximate_matrix, atol=1e-3) @parameterized.parameters( ((4,),), ((None, 4),), ) def test_from_quaternion_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.from_quaternion, shapes) @parameterized.parameters( ("must have exactly 4 dimensions in axis -1", (None,)),) def test_from_quaternion_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.from_quaternion, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_quaternion_jacobian_preset(self): """Test the Jacobian of the from_quaternion function.""" x_init = test_helpers.generate_preset_test_quaternions() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_quaternion, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_quaternion_jacobian_random(self): """Test the Jacobian of the from_quaternion function.""" x_init = test_helpers.generate_random_test_quaternions() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_quaternion, [x_init]) def test_from_quaternion_normalized_preset(self): """Tests that quaternions can be converted to rotation matrices.""" euler_angles = test_helpers.generate_preset_test_euler_angles() quat = quaternion.from_euler(euler_angles) matrix_quat = rotation_matrix_3d.from_quaternion(quat) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_quat), np.ones(euler_angles.shape[0:-1] + (1,))) def test_from_quaternion_normalized_random(self): """Tests that random quaternions can be converted to rotation matrices.""" random_quaternion = test_helpers.generate_random_test_quaternions() tensor_shape = random_quaternion.shape[:-1] random_matrix = rotation_matrix_3d.from_quaternion(random_quaternion) self.assertAllEqual( rotation_matrix_3d.is_valid(random_matrix), np.ones(tensor_shape + (1,))) def test_from_quaternion_preset(self): """Tests that a quaternion maps to correct matrix.""" preset_quaternions = test_helpers.generate_preset_test_quaternions() preset_matrices = test_helpers.generate_preset_test_rotation_matrices_3d() self.assertAllClose(preset_matrices, rotation_matrix_3d.from_quaternion(preset_quaternions)) def test_from_quaternion_random(self): """Tests conversion to matrix.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_quaternions = quaternion.from_euler(random_euler_angles) random_rotation_matrices = rotation_matrix_3d.from_euler( random_euler_angles) self.assertAllClose(random_rotation_matrices, rotation_matrix_3d.from_quaternion(random_quaternions)) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ((2, 3, 3),), ) def test_inverse_exception_not_raised(self, *shapes): """Checks the inputs of the rotate function.""" self.assert_exception_is_not_raised(rotation_matrix_3d.inverse, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -1", (3, None)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ) def test_inverse_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.inverse, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_preset(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_preset_test_rotation_matrices_3d() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.inverse, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_random(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_random_test_rotation_matrix_3d() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.inverse, [x_init]) def test_inverse_normalized_random(self): """Checks that inverted rotation matrices are valid rotations.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] random_matrix = rotation_matrix_3d.from_euler(random_euler_angle) predicted_invert_random_matrix = rotation_matrix_3d.inverse(random_matrix) self.assertAllEqual( rotation_matrix_3d.is_valid(predicted_invert_random_matrix), np.ones(tensor_tile + (1,))) def test_inverse_random(self): """Checks that inverting rotated points results in no transformation.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] random_matrix = rotation_matrix_3d.from_euler(random_euler_angle) random_point = np.random.normal(size=tensor_tile + (3,)) rotated_random_points = rotation_matrix_3d.rotate(random_point, random_matrix) predicted_invert_random_matrix = rotation_matrix_3d.inverse(random_matrix) predicted_invert_rotated_random_points = rotation_matrix_3d.rotate( rotated_random_points, predicted_invert_random_matrix) self.assertAllClose( random_point, predicted_invert_rotated_random_points, rtol=1e-6) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ((2, 3, 3),), ) def test_is_valid_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.is_valid, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -1", (3, None)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ) def test_is_valid_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(rotation_matrix_3d.is_valid, error_msg, shape) def test_is_valid_random(self): """Tests that is_valid works as intended.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] rotation_matrix = rotation_matrix_3d.from_euler(random_euler_angle) pred_normalized = rotation_matrix_3d.is_valid(rotation_matrix) with self.subTest(name="all_normalized"): self.assertAllEqual(pred_normalized, np.ones(shape=tensor_tile + (1,), dtype=bool)) with self.subTest(name="non_orthonormal"): test_matrix = np.array([[2., 0., 0.], [0., 0.5, 0], [0., 0., 1.]]) pred_normalized = rotation_matrix_3d.is_valid(test_matrix) self.assertAllEqual(pred_normalized, np.zeros(shape=(1,), dtype=bool)) with self.subTest(name="negative_orthonormal"): test_matrix = np.array([[1., 0., 0.], [0., -1., 0.], [0., 0., 1.]]) pred_normalized = rotation_matrix_3d.is_valid(test_matrix) self.assertAllEqual(pred_normalized, np.zeros(shape=(1,), dtype=bool)) @parameterized.parameters( ((3,), (3, 3)), ((None, 3), (None, 3, 3)), ((1, 3), (1, 3, 3)), ((2, 3), (2, 3, 3)), ((3,), (1, 3, 3)), ((1, 3), (3, 3)), ) def test_rotate_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.rotate, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,), (3, 3)), ("must have a rank greater than 1", (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3, None)), ("must have exactly 3 dimensions in axis -2", (3,), (None, 3)), ) def test_rotate_exception_raised(self, error_msg, *shapes): """Checks the inputs of the rotate function.""" self.assert_exception_is_raised(rotation_matrix_3d.rotate, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_preset(self): """Test the Jacobian of the rotate function.""" x_matrix_init = test_helpers.generate_preset_test_rotation_matrices_3d() tensor_shape = x_matrix_init.shape[:-1] x_point_init = np.random.uniform(size=tensor_shape) self.assert_jacobian_is_correct_fn(rotation_matrix_3d.rotate, [x_point_init, x_matrix_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_random(self): """Test the Jacobian of the rotate function.""" x_matrix_init = test_helpers.generate_random_test_rotation_matrix_3d() tensor_shape = x_matrix_init.shape[:-1] x_point_init = np.random.uniform(size=tensor_shape) self.assert_jacobian_is_correct_fn(rotation_matrix_3d.rotate, [x_point_init, x_matrix_init]) @parameterized.parameters( ((td.ANGLE_90 * td.AXIS_3D_X, td.AXIS_3D_X), (td.AXIS_3D_X,)), ((td.ANGLE_90 * td.AXIS_3D_X, td.AXIS_3D_Y), (td.AXIS_3D_Z,)), ((-td.ANGLE_90 * td.AXIS_3D_X, td.AXIS_3D_Z), (td.AXIS_3D_Y,)), ((-td.ANGLE_90 * td.AXIS_3D_Y, td.AXIS_3D_X), (td.AXIS_3D_Z,)), ((td.ANGLE_90 * td.AXIS_3D_Y, td.AXIS_3D_Y), (td.AXIS_3D_Y,)), ((td.ANGLE_90 * td.AXIS_3D_Y, td.AXIS_3D_Z), (td.AXIS_3D_X,)), ((td.ANGLE_90 * td.AXIS_3D_Z, td.AXIS_3D_X), (td.AXIS_3D_Y,)), ((-td.ANGLE_90 * td.AXIS_3D_Z, td.AXIS_3D_Y), (td.AXIS_3D_X,)), ((td.ANGLE_90 * td.AXIS_3D_Z, td.AXIS_3D_Z), (td.AXIS_3D_Z,)), ) def test_rotate_vector_preset(self, test_inputs, test_outputs): """Tests that the rotate function produces the expected results.""" def func(angles, point): matrix = rotation_matrix_3d.from_euler(angles) return rotation_matrix_3d.rotate(point, matrix) self.assert_output_is_correct(func, test_inputs, test_outputs) def test_rotate_vs_rotate_quaternion_random(self): """Tests that the rotate provide the same results as quaternion.rotate.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] random_matrix = rotation_matrix_3d.from_euler(random_euler_angle) random_quaternion = quaternion.from_rotation_matrix(random_matrix) random_point = np.random.normal(size=tensor_tile + (3,)) ground_truth = quaternion.rotate(random_point, random_quaternion) prediction = rotation_matrix_3d.rotate(random_point, random_matrix) self.assertAllClose(ground_truth, prediction, rtol=1e-6) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for 3d rotation matrix.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.geometry.transformation.tests import test_data as td from tensorflow_graphics.geometry.transformation.tests import test_helpers from tensorflow_graphics.util import test_case class RotationMatrix3dTest(test_case.TestCase): @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_assert_rotation_matrix_normalized_passthrough(self): """Checks that the assert is a passthrough when the flag is False.""" angles = test_helpers.generate_preset_test_euler_angles() matrix_input = rotation_matrix_3d.from_euler(angles) matrix_output = rotation_matrix_3d.assert_rotation_matrix_normalized( matrix_input) self.assertTrue(matrix_input is matrix_output) # pylint: disable=g-generic-assert @parameterized.parameters((np.float32), (np.float64)) def test_assert_rotation_matrix_normalized_preset(self, dtype): """Checks that assert_normalized function works as expected.""" angles = test_helpers.generate_preset_test_euler_angles().astype(dtype) matrix = rotation_matrix_3d.from_euler(angles) matrix_rescaled = matrix * 1.01 matrix_normalized = rotation_matrix_3d.assert_rotation_matrix_normalized( matrix) self.evaluate(matrix_normalized) with self.assertRaises(tf.errors.InvalidArgumentError): # pylint: disable=g-error-prone-assert-raises self.evaluate(rotation_matrix_3d.assert_rotation_matrix_normalized( matrix_rescaled)) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ) def test_assert_rotation_matrix_normalized_exception_not_raised( self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( rotation_matrix_3d.assert_rotation_matrix_normalized, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -1", (3, None)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ) def test_assert_rotation_matrix_normalized_exception_raised( self, error_msg, *shapes): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised( rotation_matrix_3d.assert_rotation_matrix_normalized, error_msg, shapes) @parameterized.parameters( ((3,), (1,)), ((None, 3), (None, 1)), ((1, 3), (1, 1)), ((2, 3), (2, 1)), ((1, 3), (1,)), ((3,), (1, 1)), ) def test_from_axis_angle_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.from_axis_angle, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,), (1,)), ("must have exactly 1 dimensions in axis -1", (3,), (None,)), ) def test_from_axis_angle_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.from_axis_angle, error_msg, shapes) def test_from_axis_angle_normalized_preset(self): """Tests that axis-angles can be converted to rotation matrices.""" euler_angles = test_helpers.generate_preset_test_euler_angles() axis, angle = axis_angle.from_euler(euler_angles) matrix_axis_angle = rotation_matrix_3d.from_axis_angle(axis, angle) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_axis_angle), np.ones(euler_angles.shape[0:-1] + (1,))) def test_from_axis_angle_normalized_random(self): """Tests that axis-angles can be converted to rotation matrices.""" tensor_shape = np.random.randint(1, 10, size=np.random.randint(3)).tolist() random_axis = np.random.normal(size=tensor_shape + [3]) random_axis /= np.linalg.norm(random_axis, axis=-1, keepdims=True) random_angle = np.random.normal(size=tensor_shape + [1]) matrix_axis_angle = rotation_matrix_3d.from_axis_angle( random_axis, random_angle) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_axis_angle), np.ones(tensor_shape + [1])) @parameterized.parameters( ((td.AXIS_3D_X, td.ANGLE_45), (td.MAT_3D_X_45,)), ((td.AXIS_3D_Y, td.ANGLE_45), (td.MAT_3D_Y_45,)), ((td.AXIS_3D_Z, td.ANGLE_45), (td.MAT_3D_Z_45,)), ((td.AXIS_3D_X, td.ANGLE_90), (td.MAT_3D_X_90,)), ((td.AXIS_3D_Y, td.ANGLE_90), (td.MAT_3D_Y_90,)), ((td.AXIS_3D_Z, td.ANGLE_90), (td.MAT_3D_Z_90,)), ((td.AXIS_3D_X, td.ANGLE_180), (td.MAT_3D_X_180,)), ((td.AXIS_3D_Y, td.ANGLE_180), (td.MAT_3D_Y_180,)), ((td.AXIS_3D_Z, td.ANGLE_180), (td.MAT_3D_Z_180,)), ) def test_from_axis_angle_preset(self, test_inputs, test_outputs): """Tests that an axis-angle maps to correct matrix.""" self.assert_output_is_correct(rotation_matrix_3d.from_axis_angle, test_inputs, test_outputs) def test_from_axis_angle_random(self): """Tests conversion to matrix.""" tensor_shape = np.random.randint(1, 10, size=np.random.randint(3)).tolist() random_axis = np.random.normal(size=tensor_shape + [3]) random_axis /= np.linalg.norm(random_axis, axis=-1, keepdims=True) random_angle = np.random.normal(size=tensor_shape + [1]) matrix_axis_angle = rotation_matrix_3d.from_axis_angle( random_axis, random_angle) random_quaternion = quaternion.from_axis_angle(random_axis, random_angle) matrix_quaternion = rotation_matrix_3d.from_quaternion(random_quaternion) self.assertAllClose(matrix_axis_angle, matrix_quaternion, rtol=1e-3) # Checks that resulting rotation matrices are normalized. self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_axis_angle), np.ones(tensor_shape + [1])) @parameterized.parameters( ((td.AXIS_3D_X, td.ANGLE_90, td.AXIS_3D_X), (td.AXIS_3D_X,)), ((td.AXIS_3D_X, td.ANGLE_90, td.AXIS_3D_Y), (td.AXIS_3D_Z,)), ((td.AXIS_3D_X, -td.ANGLE_90, td.AXIS_3D_Z), (td.AXIS_3D_Y,)), ((td.AXIS_3D_Y, -td.ANGLE_90, td.AXIS_3D_X), (td.AXIS_3D_Z,)), ((td.AXIS_3D_Y, td.ANGLE_90, td.AXIS_3D_Y), (td.AXIS_3D_Y,)), ((td.AXIS_3D_Y, td.ANGLE_90, td.AXIS_3D_Z), (td.AXIS_3D_X,)), ((td.AXIS_3D_Z, td.ANGLE_90, td.AXIS_3D_X), (td.AXIS_3D_Y,)), ((td.AXIS_3D_Z, -td.ANGLE_90, td.AXIS_3D_Y), (td.AXIS_3D_X,)), ((td.AXIS_3D_Z, td.ANGLE_90, td.AXIS_3D_Z), (td.AXIS_3D_Z,)), ) def test_from_axis_angle_rotate_vector_preset(self, test_inputs, test_outputs): """Tests the directionality of axis-angle rotations.""" def func(axis, angle, point): matrix = rotation_matrix_3d.from_axis_angle(axis, angle) return rotation_matrix_3d.rotate(point, matrix) self.assert_output_is_correct(func, test_inputs, test_outputs) @parameterized.parameters( ((3,),), ((None, 3),), ((2, 3),), ) def test_from_euler_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.from_euler, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,)),) def test_from_euler_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.from_euler, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_jacobian_preset(self): """Test the Jacobian of the from_euler function.""" x_init = test_helpers.generate_preset_test_euler_angles() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_euler, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_jacobian_random(self): """Test the Jacobian of the from_euler function.""" x_init = test_helpers.generate_random_test_euler_angles() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_euler, [x_init]) def test_from_euler_normalized_preset(self): """Tests that euler angles can be converted to rotation matrices.""" euler_angles = test_helpers.generate_preset_test_euler_angles() matrix = rotation_matrix_3d.from_euler(euler_angles) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix), np.ones(euler_angles.shape[0:-1] + (1,))) def test_from_euler_normalized_random(self): """Tests that euler angles can be converted to rotation matrices.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() matrix = rotation_matrix_3d.from_euler(random_euler_angles) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix), np.ones(random_euler_angles.shape[0:-1] + (1,))) @parameterized.parameters( ((td.AXIS_3D_0,), (td.MAT_3D_ID,)), ((td.ANGLE_45 * td.AXIS_3D_X,), (td.MAT_3D_X_45,)), ((td.ANGLE_45 * td.AXIS_3D_Y,), (td.MAT_3D_Y_45,)), ((td.ANGLE_45 * td.AXIS_3D_Z,), (td.MAT_3D_Z_45,)), ((td.ANGLE_90 * td.AXIS_3D_X,), (td.MAT_3D_X_90,)), ((td.ANGLE_90 * td.AXIS_3D_Y,), (td.MAT_3D_Y_90,)), ((td.ANGLE_90 * td.AXIS_3D_Z,), (td.MAT_3D_Z_90,)), ((td.ANGLE_180 * td.AXIS_3D_X,), (td.MAT_3D_X_180,)), ((td.ANGLE_180 * td.AXIS_3D_Y,), (td.MAT_3D_Y_180,)), ((td.ANGLE_180 * td.AXIS_3D_Z,), (td.MAT_3D_Z_180,)), ) def test_from_euler_preset(self, test_inputs, test_outputs): """Tests that Euler angles create the expected matrix.""" self.assert_output_is_correct(rotation_matrix_3d.from_euler, test_inputs, test_outputs) def test_from_euler_random(self): """Tests that Euler angles produce the same result as axis-angle.""" angles = test_helpers.generate_random_test_euler_angles() matrix = rotation_matrix_3d.from_euler(angles) tensor_tile = angles.shape[:-1] x_axis = np.tile(td.AXIS_3D_X, tensor_tile + (1,)) y_axis = np.tile(td.AXIS_3D_Y, tensor_tile + (1,)) z_axis = np.tile(td.AXIS_3D_Z, tensor_tile + (1,)) x_angle = np.expand_dims(angles[..., 0], axis=-1) y_angle = np.expand_dims(angles[..., 1], axis=-1) z_angle = np.expand_dims(angles[..., 2], axis=-1) x_rotation = rotation_matrix_3d.from_axis_angle(x_axis, x_angle) y_rotation = rotation_matrix_3d.from_axis_angle(y_axis, y_angle) z_rotation = rotation_matrix_3d.from_axis_angle(z_axis, z_angle) expected_matrix = tf.matmul(z_rotation, tf.matmul(y_rotation, x_rotation)) self.assertAllClose(expected_matrix, matrix, rtol=1e-3) @parameterized.parameters( ((3,),), ((None, 3),), ) def test_from_euler_with_small_angles_approximation_exception_not_raised( self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( rotation_matrix_3d.from_euler_with_small_angles_approximation, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,)),) def test_from_euler_with_small_angles_approximation_exception_raised( self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised( rotation_matrix_3d.from_euler_with_small_angles_approximation, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_with_small_angles_approximation_jacobian_random(self): """Test the Jacobian of from_euler_with_small_angles_approximation.""" x_init = test_helpers.generate_random_test_euler_angles( min_angle=-0.17, max_angle=0.17) self.assert_jacobian_is_correct_fn( rotation_matrix_3d.from_euler_with_small_angles_approximation, [x_init]) def test_from_euler_with_small_angles_approximation_random(self): """Tests small_angles approximation by comparing to exact calculation.""" # Only generate small angles. For a test tolerance of 1e-3, 0.16 was found # empirically to be the range where the small angle approximation works. random_euler_angles = test_helpers.generate_random_test_euler_angles( min_angle=-0.16, max_angle=0.16) exact_matrix = rotation_matrix_3d.from_euler(random_euler_angles) approximate_matrix = ( rotation_matrix_3d.from_euler_with_small_angles_approximation( random_euler_angles)) self.assertAllClose(exact_matrix, approximate_matrix, atol=1e-3) @parameterized.parameters( ((4,),), ((None, 4),), ) def test_from_quaternion_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.from_quaternion, shapes) @parameterized.parameters( ("must have exactly 4 dimensions in axis -1", (None,)),) def test_from_quaternion_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.from_quaternion, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_quaternion_jacobian_preset(self): """Test the Jacobian of the from_quaternion function.""" x_init = test_helpers.generate_preset_test_quaternions() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_quaternion, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_quaternion_jacobian_random(self): """Test the Jacobian of the from_quaternion function.""" x_init = test_helpers.generate_random_test_quaternions() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_quaternion, [x_init]) def test_from_quaternion_normalized_preset(self): """Tests that quaternions can be converted to rotation matrices.""" euler_angles = test_helpers.generate_preset_test_euler_angles() quat = quaternion.from_euler(euler_angles) matrix_quat = rotation_matrix_3d.from_quaternion(quat) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_quat), np.ones(euler_angles.shape[0:-1] + (1,))) def test_from_quaternion_normalized_random(self): """Tests that random quaternions can be converted to rotation matrices.""" random_quaternion = test_helpers.generate_random_test_quaternions() tensor_shape = random_quaternion.shape[:-1] random_matrix = rotation_matrix_3d.from_quaternion(random_quaternion) self.assertAllEqual( rotation_matrix_3d.is_valid(random_matrix), np.ones(tensor_shape + (1,))) def test_from_quaternion_preset(self): """Tests that a quaternion maps to correct matrix.""" preset_quaternions = test_helpers.generate_preset_test_quaternions() preset_matrices = test_helpers.generate_preset_test_rotation_matrices_3d() self.assertAllClose(preset_matrices, rotation_matrix_3d.from_quaternion(preset_quaternions)) def test_from_quaternion_random(self): """Tests conversion to matrix.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_quaternions = quaternion.from_euler(random_euler_angles) random_rotation_matrices = rotation_matrix_3d.from_euler( random_euler_angles) self.assertAllClose(random_rotation_matrices, rotation_matrix_3d.from_quaternion(random_quaternions)) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ((2, 3, 3),), ) def test_inverse_exception_not_raised(self, *shapes): """Checks the inputs of the rotate function.""" self.assert_exception_is_not_raised(rotation_matrix_3d.inverse, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -1", (3, None)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ) def test_inverse_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.inverse, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_preset(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_preset_test_rotation_matrices_3d() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.inverse, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_random(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_random_test_rotation_matrix_3d() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.inverse, [x_init]) def test_inverse_normalized_random(self): """Checks that inverted rotation matrices are valid rotations.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] random_matrix = rotation_matrix_3d.from_euler(random_euler_angle) predicted_invert_random_matrix = rotation_matrix_3d.inverse(random_matrix) self.assertAllEqual( rotation_matrix_3d.is_valid(predicted_invert_random_matrix), np.ones(tensor_tile + (1,))) def test_inverse_random(self): """Checks that inverting rotated points results in no transformation.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] random_matrix = rotation_matrix_3d.from_euler(random_euler_angle) random_point = np.random.normal(size=tensor_tile + (3,)) rotated_random_points = rotation_matrix_3d.rotate(random_point, random_matrix) predicted_invert_random_matrix = rotation_matrix_3d.inverse(random_matrix) predicted_invert_rotated_random_points = rotation_matrix_3d.rotate( rotated_random_points, predicted_invert_random_matrix) self.assertAllClose( random_point, predicted_invert_rotated_random_points, rtol=1e-6) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ((2, 3, 3),), ) def test_is_valid_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.is_valid, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -1", (3, None)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ) def test_is_valid_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(rotation_matrix_3d.is_valid, error_msg, shape) def test_is_valid_random(self): """Tests that is_valid works as intended.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] rotation_matrix = rotation_matrix_3d.from_euler(random_euler_angle) pred_normalized = rotation_matrix_3d.is_valid(rotation_matrix) with self.subTest(name="all_normalized"): self.assertAllEqual(pred_normalized, np.ones(shape=tensor_tile + (1,), dtype=bool)) with self.subTest(name="non_orthonormal"): test_matrix = np.array([[2., 0., 0.], [0., 0.5, 0], [0., 0., 1.]]) pred_normalized = rotation_matrix_3d.is_valid(test_matrix) self.assertAllEqual(pred_normalized, np.zeros(shape=(1,), dtype=bool)) with self.subTest(name="negative_orthonormal"): test_matrix = np.array([[1., 0., 0.], [0., -1., 0.], [0., 0., 1.]]) pred_normalized = rotation_matrix_3d.is_valid(test_matrix) self.assertAllEqual(pred_normalized, np.zeros(shape=(1,), dtype=bool)) @parameterized.parameters( ((3,), (3, 3)), ((None, 3), (None, 3, 3)), ((1, 3), (1, 3, 3)), ((2, 3), (2, 3, 3)), ((3,), (1, 3, 3)), ((1, 3), (3, 3)), ) def test_rotate_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.rotate, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,), (3, 3)), ("must have a rank greater than 1", (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3, None)), ("must have exactly 3 dimensions in axis -2", (3,), (None, 3)), ) def test_rotate_exception_raised(self, error_msg, *shapes): """Checks the inputs of the rotate function.""" self.assert_exception_is_raised(rotation_matrix_3d.rotate, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_preset(self): """Test the Jacobian of the rotate function.""" x_matrix_init = test_helpers.generate_preset_test_rotation_matrices_3d() tensor_shape = x_matrix_init.shape[:-1] x_point_init = np.random.uniform(size=tensor_shape) self.assert_jacobian_is_correct_fn(rotation_matrix_3d.rotate, [x_point_init, x_matrix_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_random(self): """Test the Jacobian of the rotate function.""" x_matrix_init = test_helpers.generate_random_test_rotation_matrix_3d() tensor_shape = x_matrix_init.shape[:-1] x_point_init = np.random.uniform(size=tensor_shape) self.assert_jacobian_is_correct_fn(rotation_matrix_3d.rotate, [x_point_init, x_matrix_init]) @parameterized.parameters( ((td.ANGLE_90 * td.AXIS_3D_X, td.AXIS_3D_X), (td.AXIS_3D_X,)), ((td.ANGLE_90 * td.AXIS_3D_X, td.AXIS_3D_Y), (td.AXIS_3D_Z,)), ((-td.ANGLE_90 * td.AXIS_3D_X, td.AXIS_3D_Z), (td.AXIS_3D_Y,)), ((-td.ANGLE_90 * td.AXIS_3D_Y, td.AXIS_3D_X), (td.AXIS_3D_Z,)), ((td.ANGLE_90 * td.AXIS_3D_Y, td.AXIS_3D_Y), (td.AXIS_3D_Y,)), ((td.ANGLE_90 * td.AXIS_3D_Y, td.AXIS_3D_Z), (td.AXIS_3D_X,)), ((td.ANGLE_90 * td.AXIS_3D_Z, td.AXIS_3D_X), (td.AXIS_3D_Y,)), ((-td.ANGLE_90 * td.AXIS_3D_Z, td.AXIS_3D_Y), (td.AXIS_3D_X,)), ((td.ANGLE_90 * td.AXIS_3D_Z, td.AXIS_3D_Z), (td.AXIS_3D_Z,)), ) def test_rotate_vector_preset(self, test_inputs, test_outputs): """Tests that the rotate function produces the expected results.""" def func(angles, point): matrix = rotation_matrix_3d.from_euler(angles) return rotation_matrix_3d.rotate(point, matrix) self.assert_output_is_correct(func, test_inputs, test_outputs) def test_rotate_vs_rotate_quaternion_random(self): """Tests that the rotate provide the same results as quaternion.rotate.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] random_matrix = rotation_matrix_3d.from_euler(random_euler_angle) random_quaternion = quaternion.from_rotation_matrix(random_matrix) random_point = np.random.normal(size=tensor_tile + (3,)) ground_truth = quaternion.rotate(random_point, random_quaternion) prediction = rotation_matrix_3d.rotate(random_point, random_matrix) self.assertAllClose(ground_truth, prediction, rtol=1e-6) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
488
Gather barycentrics, triangle indices, mask, etc. into single structure - Framebuffer and use it in rasterization backend.
Gather barycentrics, triangle indices, mask, etc. into single structure - Framebuffer and use it in rasterization backend.
copybara-service[bot]
"2021-01-30T00:32:55Z"
"2021-02-02T20:48:00Z"
e539c142799936d76d84d0861951ed883a9b4673
9d257ad4a72ccf65e4349910b9fff7c0a5648073
Gather barycentrics, triangle indices, mask, etc. into single structure - Framebuffer and use it in rasterization backend.. Gather barycentrics, triangle indices, mask, etc. into single structure - Framebuffer and use it in rasterization backend.
./tensorflow_graphics/projects/local_implicit_grid/core/local_implicit_grid_layer.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Local Implicit Grid layer implemented in Tensorflow. """ import tensorflow.compat.v1 as tf from tensorflow_graphics.projects.local_implicit_grid.core import implicit_nets from tensorflow_graphics.projects.local_implicit_grid.core import regular_grid_interpolation layers = tf.keras.layers class LocalImplicitGrid(layers.Layer): """Local Implicit Grid layer. """ def __init__(self, size=(32, 32, 32), in_features=16, out_features=1, x_location_max=1, num_filters=128, net_type="imnet", method="linear", interp=True, min_grid_value=(0, 0, 0), max_grid_value=(1, 1, 1), name="lvoxgrid"): """Initialization function. Args: size: list or tuple of ints, grid dimension in each dimension. in_features: int, number of input channels. out_features: int, number of output channels. x_location_max: float, relative coordinate range for one voxel. num_filters: int, number of filters for refiner. net_type: str, one of occnet/deepsdf. method: str, one of linear/nn. interp: bool, interp final results across neighbors (only in linear mode). min_grid_value: tuple, lower bound of query points. max_grid_value: tuple, upper bound of query points. name: str, name of the layer. """ super(LocalImplicitGrid, self).__init__(name=name) # Print warning if x_location_max and method do not match if not ((x_location_max == 1 and method == "linear") or (x_location_max == 2 and method == "nn")): raise ValueError("Bad combination of x_location_max and method.") self.cin = in_features self.cout = out_features self.dim = len(size) self.x_location_max = x_location_max self.interp = interp self.min_grid_value = min_grid_value self.max_grid_value = max_grid_value self.num_filters = num_filters if self.dim not in [2, 3]: raise ValueError("`size` must be tuple or list of len 2 or 3.") if net_type == "imnet": self.net = implicit_nets.ImNet( in_features=in_features, num_filters=num_filters) elif net_type == "deepsdf": self.net = implicit_nets.DeepSDF( in_features=in_features, num_filters=num_filters) else: raise NotImplementedError if method not in ["linear", "nn"]: raise ValueError("`method` must be `linear` or `nn`.") self.method = method self.size_tensor = tf.constant(size) self.size = size if size[0] == size[1] == size[2] == 1: self.cubesize = None else: self.cubesize = tf.constant([1/(r-1) for r in size], dtype=tf.float32) def call(self, grid, pts, training=False): """Forward method for Learnable Voxel Grid. Args: grid: `[batch_size, *self.size, in_features]` tensor, input feature grid. pts: `[batch_size, num_points, dim]` tensor, coordinates of points that are within the range (0, 1). training: bool, flag indicating training phase. Returns: outputs: `[batch_size, num_points, out_features]` tensor, continuous function field value at locations specified at pts. Raises: RuntimeError: dimensions of grid does not match that of self. """ # assert that dimensions match grid = tf.ensure_shape(grid, (None, self.size[0], self.size[1], self.size[2], self.cin)) pts = tf.ensure_shape(pts, (None, None, self.dim)) lat, weights, xloc = self._interp(grid, pts) outputs = self._eval_net(lat, weights, xloc, training=training) return outputs def _interp(self, grid, pts): """Interpolation function to get local latent code, weights & relative loc. Args: grid: `[batch_size, *self.size, in_features]` tensor, input feature grid. pts: `[batch_size, num_points, dim]` tensor, coordinates of points that are within the range (0, 1). Returns: lat: `[batch_size, num_points, 2**dim, in_features]` tensor, neighbor latent codes for each input point. weights: `[batch_size, num_points, 2**dim]` tensor, bi/tri-linear interpolation weights for each neighbor. xloc: `[batch_size, num_points, 2**dim, dim]`tensor, relative coordinates. """ lat, weights, xloc = regular_grid_interpolation.get_interp_coefficients( grid, pts, min_grid_value=self.min_grid_value, max_grid_value=self.max_grid_value) xloc *= self.x_location_max return lat, weights, xloc def _eval_net(self, lat, weights, xloc, training=False): """Evaluate function values by querying shared dense network. Args: lat: `[batch_size, num_points, 2**dim, in_features]` tensor, neighbor latent codes for each input point. weights: `[batch_size, num_points, 2**dim]` tensor, bi/tri-linear interpolation weights for each neighbor. xloc: `[batch_size, num_points, 2**dim, dim]`tensor, relative coordinates. training: bool, flag indicating training phase. Returns: values: `[batch_size, num_point, out_features]` tensor, query values. """ nb, np, nn, nc = lat.get_shape().as_list() nd = self.dim if self.method == "linear": inputs = tf.concat([xloc, lat], axis=-1) # `[batch_size, num_points, 2**dim, dim+in_features]` inputs = tf.reshape(inputs, [-1, nc+nd]) values = self.net(inputs, training=training) values = tf.reshape(values, [nb, np, nn, self.cout]) # `[batch_size, num_points, 2**dim, out_features]` if self.interp: values = tf.reduce_sum(tf.expand_dims(weights, axis=-1)*values, axis=2) # `[batch_size, num_points out_features]` else: values = (values, weights) else: # nearest neighbor nid = tf.cast(tf.argmax(weights, axis=-1), tf.int32) # [batch_size, num_points] bid = tf.broadcast_to(tf.range(nb, dtype=tf.int32)[:, tf.newaxis], [nb, np]) pid = tf.broadcast_to(tf.range(np, dtype=tf.int32)[tf.newaxis, :], [nb, np]) gather_id = tf.stack((bid, pid, nid), axis=-1) lat_ = tf.gather_nd(lat, gather_id) # [batch_size, num_points, in_feat] xloc_ = tf.gather_nd(xloc, gather_id) # [batch_size, num_points, dim] inputs = tf.concat([xloc_, lat_], axis=-1) inputs = tf.reshape(inputs, [-1, nc+nd]) values = self.net(inputs, training=training) values = tf.reshape(values, [nb, np, self.cout]) # `[batch_size, num_points, out_features]` return values
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Local Implicit Grid layer implemented in Tensorflow. """ import tensorflow.compat.v1 as tf from tensorflow_graphics.projects.local_implicit_grid.core import implicit_nets from tensorflow_graphics.projects.local_implicit_grid.core import regular_grid_interpolation layers = tf.keras.layers class LocalImplicitGrid(layers.Layer): """Local Implicit Grid layer. """ def __init__(self, size=(32, 32, 32), in_features=16, out_features=1, x_location_max=1, num_filters=128, net_type="imnet", method="linear", interp=True, min_grid_value=(0, 0, 0), max_grid_value=(1, 1, 1), name="lvoxgrid"): """Initialization function. Args: size: list or tuple of ints, grid dimension in each dimension. in_features: int, number of input channels. out_features: int, number of output channels. x_location_max: float, relative coordinate range for one voxel. num_filters: int, number of filters for refiner. net_type: str, one of occnet/deepsdf. method: str, one of linear/nn. interp: bool, interp final results across neighbors (only in linear mode). min_grid_value: tuple, lower bound of query points. max_grid_value: tuple, upper bound of query points. name: str, name of the layer. """ super(LocalImplicitGrid, self).__init__(name=name) # Print warning if x_location_max and method do not match if not ((x_location_max == 1 and method == "linear") or (x_location_max == 2 and method == "nn")): raise ValueError("Bad combination of x_location_max and method.") self.cin = in_features self.cout = out_features self.dim = len(size) self.x_location_max = x_location_max self.interp = interp self.min_grid_value = min_grid_value self.max_grid_value = max_grid_value self.num_filters = num_filters if self.dim not in [2, 3]: raise ValueError("`size` must be tuple or list of len 2 or 3.") if net_type == "imnet": self.net = implicit_nets.ImNet( in_features=in_features, num_filters=num_filters) elif net_type == "deepsdf": self.net = implicit_nets.DeepSDF( in_features=in_features, num_filters=num_filters) else: raise NotImplementedError if method not in ["linear", "nn"]: raise ValueError("`method` must be `linear` or `nn`.") self.method = method self.size_tensor = tf.constant(size) self.size = size if size[0] == size[1] == size[2] == 1: self.cubesize = None else: self.cubesize = tf.constant([1/(r-1) for r in size], dtype=tf.float32) def call(self, grid, pts, training=False): """Forward method for Learnable Voxel Grid. Args: grid: `[batch_size, *self.size, in_features]` tensor, input feature grid. pts: `[batch_size, num_points, dim]` tensor, coordinates of points that are within the range (0, 1). training: bool, flag indicating training phase. Returns: outputs: `[batch_size, num_points, out_features]` tensor, continuous function field value at locations specified at pts. Raises: RuntimeError: dimensions of grid does not match that of self. """ # assert that dimensions match grid = tf.ensure_shape(grid, (None, self.size[0], self.size[1], self.size[2], self.cin)) pts = tf.ensure_shape(pts, (None, None, self.dim)) lat, weights, xloc = self._interp(grid, pts) outputs = self._eval_net(lat, weights, xloc, training=training) return outputs def _interp(self, grid, pts): """Interpolation function to get local latent code, weights & relative loc. Args: grid: `[batch_size, *self.size, in_features]` tensor, input feature grid. pts: `[batch_size, num_points, dim]` tensor, coordinates of points that are within the range (0, 1). Returns: lat: `[batch_size, num_points, 2**dim, in_features]` tensor, neighbor latent codes for each input point. weights: `[batch_size, num_points, 2**dim]` tensor, bi/tri-linear interpolation weights for each neighbor. xloc: `[batch_size, num_points, 2**dim, dim]`tensor, relative coordinates. """ lat, weights, xloc = regular_grid_interpolation.get_interp_coefficients( grid, pts, min_grid_value=self.min_grid_value, max_grid_value=self.max_grid_value) xloc *= self.x_location_max return lat, weights, xloc def _eval_net(self, lat, weights, xloc, training=False): """Evaluate function values by querying shared dense network. Args: lat: `[batch_size, num_points, 2**dim, in_features]` tensor, neighbor latent codes for each input point. weights: `[batch_size, num_points, 2**dim]` tensor, bi/tri-linear interpolation weights for each neighbor. xloc: `[batch_size, num_points, 2**dim, dim]`tensor, relative coordinates. training: bool, flag indicating training phase. Returns: values: `[batch_size, num_point, out_features]` tensor, query values. """ nb, np, nn, nc = lat.get_shape().as_list() nd = self.dim if self.method == "linear": inputs = tf.concat([xloc, lat], axis=-1) # `[batch_size, num_points, 2**dim, dim+in_features]` inputs = tf.reshape(inputs, [-1, nc+nd]) values = self.net(inputs, training=training) values = tf.reshape(values, [nb, np, nn, self.cout]) # `[batch_size, num_points, 2**dim, out_features]` if self.interp: values = tf.reduce_sum(tf.expand_dims(weights, axis=-1)*values, axis=2) # `[batch_size, num_points out_features]` else: values = (values, weights) else: # nearest neighbor nid = tf.cast(tf.argmax(weights, axis=-1), tf.int32) # [batch_size, num_points] bid = tf.broadcast_to(tf.range(nb, dtype=tf.int32)[:, tf.newaxis], [nb, np]) pid = tf.broadcast_to(tf.range(np, dtype=tf.int32)[tf.newaxis, :], [nb, np]) gather_id = tf.stack((bid, pid, nid), axis=-1) lat_ = tf.gather_nd(lat, gather_id) # [batch_size, num_points, in_feat] xloc_ = tf.gather_nd(xloc, gather_id) # [batch_size, num_points, dim] inputs = tf.concat([xloc_, lat_], axis=-1) inputs = tf.reshape(inputs, [-1, nc+nd]) values = self.net(inputs, training=training) values = tf.reshape(values, [nb, np, self.cout]) # `[batch_size, num_points, out_features]` return values
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/representation/mesh/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Mesh module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.geometry.representation.mesh import normals from tensorflow_graphics.geometry.representation.mesh import utils from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.geometry. __all__ = _export_api.get_modules()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Mesh module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.geometry.representation.mesh import normals from tensorflow_graphics.geometry.representation.mesh import sampler from tensorflow_graphics.geometry.representation.mesh import utils from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.geometry. __all__ = _export_api.get_modules()
1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/representation/mesh/sampler.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Computes a weighted point sampling of a triangular mesh. This op computes a uniform sampling of points on the surface of the mesh. Points are sampled from the surface of each triangle using a uniform distribution, proportional to a specified face density (e.g. face area). Uses the approach mentioned in the TOG 2002 paper "Shape distributions" (https://dl.acm.org/citation.cfm?id=571648) to generate random barycentric coordinates. This op can be used for several tasks, including better mesh reconstruction. For example, see these recent papers demonstrating reconstruction losses using this op: 1. "GEOMetrics: Exploiting Geometric Structure for Graph-Encoded Objects" (https://arxiv.org/abs/1901.11461) ICML 2019. 2. "Mesh R-CNN" (https://arxiv.org/abs/1906.02739) ICCV 2019. Op is differentiable w.r.t mesh vertex positions. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.representation import triangle from tensorflow_graphics.geometry.representation.mesh import normals from tensorflow_graphics.util import asserts from tensorflow_graphics.util import shape def triangle_area(vertex0, vertex1, vertex2, name=None): """Computes triangle areas. Note: Computed triangle area = 0.5 * | e1 x e2 | where e1 and e2 are edges of triangle. In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. In the following, A1 to An are optional batch dimensions. Args: vertex0: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vertex of a triangle. vertex1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vertex of a triangle. vertex2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the third vertex of a triangle. name: A name for this op. Defaults to "triangle_area". Returns: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents the triangle areas. """ with tf.compat.v1.name_scope(name, "triangle_area"): vertex0 = tf.convert_to_tensor(value=vertex0) vertex1 = tf.convert_to_tensor(value=vertex1) vertex2 = tf.convert_to_tensor(value=vertex2) triangle_normals = triangle.normal( vertex0, vertex1, vertex2, normalize=False) areas = 0.5 * tf.linalg.norm(tensor=triangle_normals, axis=-1) return areas def _random_categorical_sample(num_samples, weights, seed=None, stateless=False, name=None, sample_dtype=tf.int32): """Samples from a categorical distribution with arbitrary batch dimensions. Note: In the following, A1 to An are optional batch dimensions. Args: num_samples: An `int32` scalar denoting the number of samples to generate per mesh. weights: A `float` tensor of shape `[A1, ..., An, F]` where F is number of faces. All weights must be > 0. seed: Optional random seed, value depends on `stateless`. stateless: Optional flag to use stateless random sampler. If stateless=True, then `seed` must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate the same reproducible sequence across calls. If stateless=False, then a stateful random number generator is used (default behavior). name: Name for op. Defaults to "random_categorical_sample". sample_dtype: Type of output samples. Returns: A `sample_dtype` tensor of shape `[A1, ..., An, num_samples]`. """ with tf.compat.v1.name_scope(name, "random_categorical_sample"): asserts.assert_all_above(weights, 0) logits = tf.math.log(weights) num_faces = tf.shape(input=logits)[-1] batch_shape = tf.shape(input=logits)[:-1] logits_2d = tf.reshape(logits, [-1, num_faces]) if stateless: seed = tf.convert_to_tensor(value=seed) shape.check_static( tensor=seed, tensor_name="seed", has_dim_equals=(-1, 2)) sample_fn = tf.random.stateless_categorical else: sample_fn = tf.random.categorical draws = sample_fn( logits=logits_2d, num_samples=num_samples, dtype=sample_dtype, seed=seed) samples = tf.reshape( draws, shape=tf.concat((batch_shape, (num_samples,)), axis=0)) return samples def generate_random_face_indices(num_samples, face_weights, seed=None, stateless=False, name=None): """Generate a sample of face ids given per face probability. Note: In the following, A1 to An are optional batch dimensions. Args: num_samples: An `int32` scalar denoting the number of samples to generate per mesh. face_weights: A `float` tensor of shape `[A1, ..., An, F]` where F is number of faces. All weights must be > 0. seed: Optional seed for the random number generator. stateless: Optional flag to use stateless random sampler. If stateless=True, then `seed` must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate the same reproducible sequence across calls. If stateless=False, then a stateful random number generator is used (default behavior). name: Name for op. Defaults to "generate_random_face_indices". Returns: An `int32` tensor of shape `[A1, ..., An, num_samples]` denoting sampled face indices. """ with tf.compat.v1.name_scope(name, "generate_random_face_indices"): num_samples = tf.convert_to_tensor(value=num_samples) face_weights = tf.convert_to_tensor(value=face_weights) shape.check_static( tensor=face_weights, tensor_name="face_weights", has_rank_greater_than=0) shape.check_static( tensor=num_samples, tensor_name="num_samples", has_rank=0) face_weights = asserts.assert_all_above(face_weights, minval=0.0) eps = asserts.select_eps_for_division(face_weights.dtype) face_weights = face_weights + eps sampled_face_indices = _random_categorical_sample( num_samples=num_samples, weights=face_weights, seed=seed, stateless=stateless) return sampled_face_indices def generate_random_barycentric_coordinates(sample_shape, dtype=tf.dtypes.float32, seed=None, stateless=False, name=None): """Generate uniformly sampled random barycentric coordinates. Note: In the following, A1 to An are optional batch dimensions. Args: sample_shape: An `int` tensor with shape `[n+1,]` and values `(A1, ..., An, num_samples)` denoting total number of random samples drawn, where `n` is number of batch dimensions, and `num_samples` is the number of samples drawn for each mesh. dtype: Optional type of generated barycentric coordinates, defaults to float32. seed: An optional random seed. stateless: Optional flag to use stateless random sampler. If stateless=True, then `seed` must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate the same reproducible sequence across calls. If stateless=False, then a stateful random number generator is used (default behavior). name: Name for op. Defaults to "generate_random_barycentric_coordinates". Returns: A `dtype` tensor of shape [A1, ..., An, num_samples, 3], where the last dimension contains the sampled barycentric coordinates. """ with tf.compat.v1.name_scope(name, "generate_random_barycentric_coordinates"): sample_shape = tf.convert_to_tensor(value=sample_shape) shape.check_static( tensor=sample_shape, tensor_name="sample_shape", has_rank=1) sample_shape = tf.concat((sample_shape, (2,)), axis=0) if stateless: seed = tf.convert_to_tensor(value=seed) shape.check_static( tensor=seed, tensor_name="seed", has_dim_equals=(-1, 2)) sample_fn = tf.random.stateless_uniform else: sample_fn = tf.random.uniform random_uniform = sample_fn( shape=sample_shape, minval=0.0, maxval=1.0, dtype=dtype, seed=seed) random1 = tf.sqrt(random_uniform[..., 0]) random2 = random_uniform[..., 1] barycentric = tf.stack( (1 - random1, random1 * (1 - random2), random1 * random2), axis=-1) return barycentric def weighted_random_sample_triangle_mesh(vertex_attributes, faces, num_samples, face_weights, seed=None, stateless=False, name=None): """Performs a face probability weighted random sampling of a tri mesh. Note: In the following, A1 to An are optional batch dimensions. Args: vertex_attributes: A `float` tensor of shape `[A1, ..., An, V, D]`, where V is the number of vertices, and D is dimensionality of each vertex. faces: A `int` tensor of shape `[A1, ..., An, F, 3]`, where F is the number of faces. num_samples: A `int` 0-D tensor denoting number of samples to be drawn from each mesh. face_weights: A `float` tensor of shape ``[A1, ..., An, F]`, denoting unnormalized sampling probability of each face, where F is the number of faces. seed: Optional random seed. stateless: Optional flag to use stateless random sampler. If stateless=True, then seed must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate same sequence across calls. name: Name for op. Defaults to "weighted_random_sample_triangle_mesh". Returns: sample_points: A `float` tensor of shape `[A1, ..., An, num_samples, D]`, where D is dimensionality of each sampled point. sample_face_indices: A `int` tensor of shape `[A1, ..., An, num_samples]`. """ with tf.compat.v1.name_scope(name, "weighted_random_sample_triangle_mesh"): faces = tf.convert_to_tensor(value=faces) vertex_attributes = tf.convert_to_tensor(value=vertex_attributes) face_weights = tf.convert_to_tensor(value=face_weights) num_samples = tf.convert_to_tensor(value=num_samples) shape.check_static( tensor=vertex_attributes, tensor_name="vertex_attributes", has_rank_greater_than=1) shape.check_static( tensor=faces, tensor_name="faces", has_rank_greater_than=1) shape.check_static( tensor=face_weights, tensor_name="face_weights", has_rank_greater_than=0) shape.compare_batch_dimensions( tensors=(faces, face_weights), last_axes=(-2, -1), tensor_names=("faces", "face_weights"), broadcast_compatible=False) shape.compare_batch_dimensions( tensors=(vertex_attributes, faces, face_weights), last_axes=(-3, -3, -2), tensor_names=("vertex_attributes", "faces", "face_weights"), broadcast_compatible=False) asserts.assert_all_above(face_weights, 0) batch_dims = faces.shape.ndims - 2 batch_shape = faces.shape.as_list()[:-2] sample_shape = tf.concat( (batch_shape, tf.convert_to_tensor( value=(num_samples,), dtype=tf.int32)), axis=0) sample_face_indices = generate_random_face_indices( num_samples, face_weights, seed=seed, stateless=stateless) sample_vertex_indices = tf.gather( faces, sample_face_indices, batch_dims=batch_dims) sample_vertices = tf.gather( vertex_attributes, sample_vertex_indices, batch_dims=batch_dims) barycentric = generate_random_barycentric_coordinates( sample_shape, dtype=vertex_attributes.dtype, seed=seed, stateless=stateless) barycentric = tf.expand_dims(barycentric, axis=-1) sample_points = tf.math.multiply(sample_vertices, barycentric) sample_points = tf.reduce_sum(input_tensor=sample_points, axis=-2) return sample_points, sample_face_indices def area_weighted_random_sample_triangle_mesh(vertex_attributes, faces, num_samples, vertex_positions=None, seed=None, stateless=False, name=None): """Performs a face area weighted random sampling of a tri mesh. Note: In the following, A1 to An are optional batch dimensions. Args: vertex_attributes: A `float` tensor of shape `[A1, ..., An, V, D]`, where V is the number of vertices, and D is dimensionality of a feature defined on each vertex. If `vertex_positions` is not provided, then first 3 dimensions of `vertex_attributes` denote the vertex positions. faces: A `int` tensor of shape `[A1, ..., An, F, 3]`, where F is the number of faces. num_samples: An `int` scalar denoting number of samples to be drawn from each mesh. vertex_positions: An optional `float` tensor of shape `[A1, ..., An, V, 3]`, where V is the number of vertices. If None, then vertex_attributes[..., :3] is used as vertex positions. seed: Optional random seed. stateless: Optional flag to use stateless random sampler. If stateless=True, then seed must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate same sequence across calls. name: Name for op. Defaults to "area_weighted_random_sample_triangle_mesh". Returns: sample_pts: A `float` tensor of shape `[A1, ..., An, num_samples, D]`, where D is dimensionality of each sampled point. sample_face_indices: A `int` tensor of shape `[A1, ..., An, num_samples]`. """ with tf.compat.v1.name_scope(name, "area_weighted_random_sample_triangle_mesh"): faces = tf.convert_to_tensor(value=faces) vertex_attributes = tf.convert_to_tensor(value=vertex_attributes) num_samples = tf.convert_to_tensor(value=num_samples) shape.check_static( tensor=vertex_attributes, tensor_name="vertex_attributes", has_rank_greater_than=1) shape.check_static( tensor=vertex_attributes, tensor_name="vertex_attributes", has_dim_greater_than=(-1, 2)) if vertex_positions is not None: vertex_positions = tf.convert_to_tensor(value=vertex_positions) else: vertex_positions = vertex_attributes[..., :3] shape.check_static( tensor=vertex_positions, tensor_name="vertex_positions", has_rank_greater_than=1) shape.check_static( tensor=vertex_positions, tensor_name="vertex_positions", has_dim_equals=(-1, 3)) triangle_vertex_positions = normals.gather_faces(vertex_positions, faces) triangle_areas = triangle_area(triangle_vertex_positions[..., 0, :], triangle_vertex_positions[..., 1, :], triangle_vertex_positions[..., 2, :]) return weighted_random_sample_triangle_mesh( vertex_attributes, faces, num_samples, face_weights=triangle_areas, seed=seed, stateless=stateless)
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Computes a weighted point sampling of a triangular mesh. This op computes a uniform sampling of points on the surface of the mesh. Points are sampled from the surface of each triangle using a uniform distribution, proportional to a specified face density (e.g. face area). Uses the approach mentioned in the TOG 2002 paper "Shape distributions" (https://dl.acm.org/citation.cfm?id=571648) to generate random barycentric coordinates. This op can be used for several tasks, including better mesh reconstruction. For example, see these recent papers demonstrating reconstruction losses using this op: 1. "GEOMetrics: Exploiting Geometric Structure for Graph-Encoded Objects" (https://arxiv.org/abs/1901.11461) ICML 2019. 2. "Mesh R-CNN" (https://arxiv.org/abs/1906.02739) ICCV 2019. Op is differentiable w.r.t mesh vertex positions. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.representation import triangle from tensorflow_graphics.geometry.representation.mesh import normals from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def triangle_area(vertex0, vertex1, vertex2, name=None): """Computes triangle areas. Note: Computed triangle area = 0.5 * | e1 x e2 | where e1 and e2 are edges of triangle. In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. In the following, A1 to An are optional batch dimensions. Args: vertex0: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vertex of a triangle. vertex1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vertex of a triangle. vertex2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the third vertex of a triangle. name: A name for this op. Defaults to "triangle_area". Returns: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents the triangle areas. """ with tf.compat.v1.name_scope(name, "triangle_area"): vertex0 = tf.convert_to_tensor(value=vertex0) vertex1 = tf.convert_to_tensor(value=vertex1) vertex2 = tf.convert_to_tensor(value=vertex2) triangle_normals = triangle.normal( vertex0, vertex1, vertex2, normalize=False) areas = 0.5 * tf.linalg.norm(tensor=triangle_normals, axis=-1) return areas def _random_categorical_sample(num_samples, weights, seed=None, stateless=False, name=None, sample_dtype=tf.int32): """Samples from a categorical distribution with arbitrary batch dimensions. Note: In the following, A1 to An are optional batch dimensions. Args: num_samples: An `int32` scalar denoting the number of samples to generate per mesh. weights: A `float` tensor of shape `[A1, ..., An, F]` where F is number of faces. All weights must be > 0. seed: Optional random seed, value depends on `stateless`. stateless: Optional flag to use stateless random sampler. If stateless=True, then `seed` must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate the same reproducible sequence across calls. If stateless=False, then a stateful random number generator is used (default behavior). name: Name for op. Defaults to "random_categorical_sample". sample_dtype: Type of output samples. Returns: A `sample_dtype` tensor of shape `[A1, ..., An, num_samples]`. """ with tf.compat.v1.name_scope(name, "random_categorical_sample"): asserts.assert_all_above(weights, 0) logits = tf.math.log(weights) num_faces = tf.shape(input=logits)[-1] batch_shape = tf.shape(input=logits)[:-1] logits_2d = tf.reshape(logits, [-1, num_faces]) if stateless: seed = tf.convert_to_tensor(value=seed) shape.check_static( tensor=seed, tensor_name="seed", has_dim_equals=(-1, 2)) sample_fn = tf.random.stateless_categorical else: sample_fn = tf.random.categorical draws = sample_fn( logits=logits_2d, num_samples=num_samples, dtype=sample_dtype, seed=seed) samples = tf.reshape( draws, shape=tf.concat((batch_shape, (num_samples,)), axis=0)) return samples def generate_random_face_indices(num_samples, face_weights, seed=None, stateless=False, name=None): """Generate a sample of face ids given per face probability. Note: In the following, A1 to An are optional batch dimensions. Args: num_samples: An `int32` scalar denoting the number of samples to generate per mesh. face_weights: A `float` tensor of shape `[A1, ..., An, F]` where F is number of faces. All weights must be > 0. seed: Optional seed for the random number generator. stateless: Optional flag to use stateless random sampler. If stateless=True, then `seed` must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate the same reproducible sequence across calls. If stateless=False, then a stateful random number generator is used (default behavior). name: Name for op. Defaults to "generate_random_face_indices". Returns: An `int32` tensor of shape `[A1, ..., An, num_samples]` denoting sampled face indices. """ with tf.compat.v1.name_scope(name, "generate_random_face_indices"): num_samples = tf.convert_to_tensor(value=num_samples) face_weights = tf.convert_to_tensor(value=face_weights) shape.check_static( tensor=face_weights, tensor_name="face_weights", has_rank_greater_than=0) shape.check_static( tensor=num_samples, tensor_name="num_samples", has_rank=0) face_weights = asserts.assert_all_above(face_weights, minval=0.0) eps = asserts.select_eps_for_division(face_weights.dtype) face_weights = face_weights + eps sampled_face_indices = _random_categorical_sample( num_samples=num_samples, weights=face_weights, seed=seed, stateless=stateless) return sampled_face_indices def generate_random_barycentric_coordinates(sample_shape, dtype=tf.dtypes.float32, seed=None, stateless=False, name=None): """Generate uniformly sampled random barycentric coordinates. Note: In the following, A1 to An are optional batch dimensions. Args: sample_shape: An `int` tensor with shape `[n+1,]` and values `(A1, ..., An, num_samples)` denoting total number of random samples drawn, where `n` is number of batch dimensions, and `num_samples` is the number of samples drawn for each mesh. dtype: Optional type of generated barycentric coordinates, defaults to float32. seed: An optional random seed. stateless: Optional flag to use stateless random sampler. If stateless=True, then `seed` must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate the same reproducible sequence across calls. If stateless=False, then a stateful random number generator is used (default behavior). name: Name for op. Defaults to "generate_random_barycentric_coordinates". Returns: A `dtype` tensor of shape [A1, ..., An, num_samples, 3], where the last dimension contains the sampled barycentric coordinates. """ with tf.compat.v1.name_scope(name, "generate_random_barycentric_coordinates"): sample_shape = tf.convert_to_tensor(value=sample_shape) shape.check_static( tensor=sample_shape, tensor_name="sample_shape", has_rank=1) sample_shape = tf.concat((sample_shape, (2,)), axis=0) if stateless: seed = tf.convert_to_tensor(value=seed) shape.check_static( tensor=seed, tensor_name="seed", has_dim_equals=(-1, 2)) sample_fn = tf.random.stateless_uniform else: sample_fn = tf.random.uniform random_uniform = sample_fn( shape=sample_shape, minval=0.0, maxval=1.0, dtype=dtype, seed=seed) random1 = tf.sqrt(random_uniform[..., 0]) random2 = random_uniform[..., 1] barycentric = tf.stack( (1 - random1, random1 * (1 - random2), random1 * random2), axis=-1) return barycentric def weighted_random_sample_triangle_mesh(vertex_attributes, faces, num_samples, face_weights, seed=None, stateless=False, name=None): """Performs a face probability weighted random sampling of a tri mesh. Note: In the following, A1 to An are optional batch dimensions. Args: vertex_attributes: A `float` tensor of shape `[A1, ..., An, V, D]`, where V is the number of vertices, and D is dimensionality of each vertex. faces: A `int` tensor of shape `[A1, ..., An, F, 3]`, where F is the number of faces. num_samples: A `int` 0-D tensor denoting number of samples to be drawn from each mesh. face_weights: A `float` tensor of shape ``[A1, ..., An, F]`, denoting unnormalized sampling probability of each face, where F is the number of faces. seed: Optional random seed. stateless: Optional flag to use stateless random sampler. If stateless=True, then seed must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate same sequence across calls. name: Name for op. Defaults to "weighted_random_sample_triangle_mesh". Returns: sample_points: A `float` tensor of shape `[A1, ..., An, num_samples, D]`, where D is dimensionality of each sampled point. sample_face_indices: A `int` tensor of shape `[A1, ..., An, num_samples]`. """ with tf.compat.v1.name_scope(name, "weighted_random_sample_triangle_mesh"): faces = tf.convert_to_tensor(value=faces) vertex_attributes = tf.convert_to_tensor(value=vertex_attributes) face_weights = tf.convert_to_tensor(value=face_weights) num_samples = tf.convert_to_tensor(value=num_samples) shape.check_static( tensor=vertex_attributes, tensor_name="vertex_attributes", has_rank_greater_than=1) shape.check_static( tensor=faces, tensor_name="faces", has_rank_greater_than=1) shape.check_static( tensor=face_weights, tensor_name="face_weights", has_rank_greater_than=0) shape.compare_batch_dimensions( tensors=(faces, face_weights), last_axes=(-2, -1), tensor_names=("faces", "face_weights"), broadcast_compatible=False) shape.compare_batch_dimensions( tensors=(vertex_attributes, faces, face_weights), last_axes=(-3, -3, -2), tensor_names=("vertex_attributes", "faces", "face_weights"), broadcast_compatible=False) asserts.assert_all_above(face_weights, 0) batch_dims = faces.shape.ndims - 2 batch_shape = faces.shape.as_list()[:-2] sample_shape = tf.concat( (batch_shape, tf.convert_to_tensor( value=(num_samples,), dtype=tf.int32)), axis=0) sample_face_indices = generate_random_face_indices( num_samples, face_weights, seed=seed, stateless=stateless) sample_vertex_indices = tf.gather( faces, sample_face_indices, batch_dims=batch_dims) sample_vertices = tf.gather( vertex_attributes, sample_vertex_indices, batch_dims=batch_dims) barycentric = generate_random_barycentric_coordinates( sample_shape, dtype=vertex_attributes.dtype, seed=seed, stateless=stateless) barycentric = tf.expand_dims(barycentric, axis=-1) sample_points = tf.math.multiply(sample_vertices, barycentric) sample_points = tf.reduce_sum(input_tensor=sample_points, axis=-2) return sample_points, sample_face_indices def area_weighted_random_sample_triangle_mesh(vertex_attributes, faces, num_samples, vertex_positions=None, seed=None, stateless=False, name=None): """Performs a face area weighted random sampling of a tri mesh. Note: In the following, A1 to An are optional batch dimensions. Args: vertex_attributes: A `float` tensor of shape `[A1, ..., An, V, D]`, where V is the number of vertices, and D is dimensionality of a feature defined on each vertex. If `vertex_positions` is not provided, then first 3 dimensions of `vertex_attributes` denote the vertex positions. faces: A `int` tensor of shape `[A1, ..., An, F, 3]`, where F is the number of faces. num_samples: An `int` scalar denoting number of samples to be drawn from each mesh. vertex_positions: An optional `float` tensor of shape `[A1, ..., An, V, 3]`, where V is the number of vertices. If None, then vertex_attributes[..., :3] is used as vertex positions. seed: Optional random seed. stateless: Optional flag to use stateless random sampler. If stateless=True, then seed must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate same sequence across calls. name: Name for op. Defaults to "area_weighted_random_sample_triangle_mesh". Returns: sample_pts: A `float` tensor of shape `[A1, ..., An, num_samples, D]`, where D is dimensionality of each sampled point. sample_face_indices: A `int` tensor of shape `[A1, ..., An, num_samples]`. """ with tf.compat.v1.name_scope(name, "area_weighted_random_sample_triangle_mesh"): faces = tf.convert_to_tensor(value=faces) vertex_attributes = tf.convert_to_tensor(value=vertex_attributes) num_samples = tf.convert_to_tensor(value=num_samples) shape.check_static( tensor=vertex_attributes, tensor_name="vertex_attributes", has_rank_greater_than=1) shape.check_static( tensor=vertex_attributes, tensor_name="vertex_attributes", has_dim_greater_than=(-1, 2)) if vertex_positions is not None: vertex_positions = tf.convert_to_tensor(value=vertex_positions) else: vertex_positions = vertex_attributes[..., :3] shape.check_static( tensor=vertex_positions, tensor_name="vertex_positions", has_rank_greater_than=1) shape.check_static( tensor=vertex_positions, tensor_name="vertex_positions", has_dim_equals=(-1, 3)) triangle_vertex_positions = normals.gather_faces(vertex_positions, faces) triangle_areas = triangle_area(triangle_vertex_positions[..., 0, :], triangle_vertex_positions[..., 1, :], triangle_vertex_positions[..., 2, :]) return weighted_random_sample_triangle_mesh( vertex_attributes, faces, num_samples, face_weights=triangle_areas, seed=seed, stateless=stateless) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/transformation/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Transformation module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import euler from tensorflow_graphics.geometry.transformation import linear_blend_skinning from tensorflow_graphics.geometry.transformation import look_at from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_2d from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.transformation. __all__ = _export_api.get_modules()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Transformation module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import dual_quaternion from tensorflow_graphics.geometry.transformation import euler from tensorflow_graphics.geometry.transformation import linear_blend_skinning from tensorflow_graphics.geometry.transformation import look_at from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_2d from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.transformation. __all__ = _export_api.get_modules()
1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/transformation/dual_quaternion.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow dual quaternion utility functions. A dual quaternion is an extension of a quaternion with the real and dual parts and written as $$q = q_r + epsilon q_d$$, where $$epsilon$$ is the dual number with the property $$e^2 = 0$$. It can thus be represented as two quaternions, and thus stored as 8 numbers. We define the operations in terms of the two quaternions $$q_r$$ and $$q_d$$. Dual quaternions are extensions of quaternions to represent rigid transformations (rotations and translations). They are in particular important for deforming geometries as linear blending is a very close approximation of closest path blending, which is not the case for any other representation. Note: Some of the functions expect normalized quaternions as inputs where $$|q_r| = 1$$. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v2 as tf from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.util import asserts from tensorflow_graphics.util import shape def conjugate(dual_quaternion, name=None): """Computes the conjugate of a dual quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: dual_quaternion: A tensor of shape `[A1, ..., An, 8]`, where the last dimension represents a normalized dual quaternion. name: A name for this op that defaults to "dual_quaternion_conjugate". Returns: A tensor of shape `[A1, ..., An, 8]`, where the last dimension represents a normalized dual quaternion. Raises: ValueError: If the shape of `dual_quaternion` is not supported. """ with tf.compat.v1.name_scope(name, "dual_quaternion_conjugate", [dual_quaternion]): dual_quaternion = tf.convert_to_tensor(value=dual_quaternion) shape.check_static( tensor=dual_quaternion, tensor_name="dual_quaternion", has_dim_equals=(-1, 8)) quaternion_real, quaternion_dual = tf.split( dual_quaternion, (4, 4), axis=-1) quaternion_real = asserts.assert_normalized(quaternion_real) return tf.concat((quaternion.conjugate(quaternion_real), quaternion.conjugate(quaternion_dual)), axis=-1)
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow dual quaternion utility functions. A dual quaternion is an extension of a quaternion with the real and dual parts and written as $$q = q_r + epsilon q_d$$, where $$epsilon$$ is the dual number with the property $$e^2 = 0$$. It can thus be represented as two quaternions, and thus stored as 8 numbers. We define the operations in terms of the two quaternions $$q_r$$ and $$q_d$$. Dual quaternions are extensions of quaternions to represent rigid transformations (rotations and translations). They are in particular important for deforming geometries as linear blending is a very close approximation of closest path blending, which is not the case for any other representation. Note: Some of the functions expect normalized quaternions as inputs where $$|q_r| = 1$$. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v2 as tf from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def conjugate(dual_quaternion, name=None): """Computes the conjugate of a dual quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: dual_quaternion: A tensor of shape `[A1, ..., An, 8]`, where the last dimension represents a normalized dual quaternion. name: A name for this op that defaults to "dual_quaternion_conjugate". Returns: A tensor of shape `[A1, ..., An, 8]`, where the last dimension represents a normalized dual quaternion. Raises: ValueError: If the shape of `dual_quaternion` is not supported. """ with tf.compat.v1.name_scope(name, "dual_quaternion_conjugate", [dual_quaternion]): dual_quaternion = tf.convert_to_tensor(value=dual_quaternion) shape.check_static( tensor=dual_quaternion, tensor_name="dual_quaternion", has_dim_equals=(-1, 8)) quaternion_real, quaternion_dual = tf.split( dual_quaternion, (4, 4), axis=-1) quaternion_real = asserts.assert_normalized(quaternion_real) return tf.concat((quaternion.conjugate(quaternion_real), quaternion.conjugate(quaternion_dual)), axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/nn/layer/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Layer module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.nn.layer import graph_convolution from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.geometry. __all__ = _export_api.get_modules()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Layer module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.nn.layer import graph_convolution from tensorflow_graphics.nn.layer import pointnet from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.geometry. __all__ = _export_api.get_modules()
1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/nn/layer/pointnet.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of the PointNet networks. @inproceedings{qi2017pointnet, title={Pointnet: Deep learning on point sets for3d classification and segmentation}, author={Qi, Charles R and Su, Hao and Mo, Kaichun and Guibas, Leonidas J}, booktitle={Proceedings of the IEEE conference on computer vision and pattern recognition}, pages={652--660}, year={2017}} NOTE: scheduling of batchnorm momentum currently not available in keras. However experimentally, using the batch norm from Keras resulted in better test accuracy (+1.5%) than the author's [custom batch norm version](https://github.com/charlesq34/pointnet/blob/master/utils/tf_util.py) even when coupled with batchnorm momentum decay. Further, note the author's version is actually performing a "global normalization", as mentioned in the [tf.nn.moments documentation] (https://www.tensorflow.org/api_docs/python/tf/nn/moments). This shorthand notation is used throughout this module: `B`: Number of elements in a batch. `N`: The number of points in the point set. `D`: Number of dimensions (e.g. 2 for 2D, 3 for 3D). `C`: The number of feature channels. """ import tensorflow as tf class PointNetConv2Layer(tf.keras.layers.Layer): """The 2D convolution layer used by the feature encoder in PointNet.""" def __init__(self, channels, momentum): """Constructs a Conv2 layer. Note: Differently from the standard Keras Conv2 layer, the order of ops is: 1. fully connected layer 2. batch normalization layer 3. ReLU activation unit Args: channels: the number of generated feature. momentum: the momentum of the batch normalization layer. """ super(PointNetConv2Layer, self).__init__() self.channels = channels self.momentum = momentum def build(self, input_shape): """Builds the layer with a specified input_shape.""" self.conv = tf.keras.layers.Conv2D( self.channels, (1, 1), input_shape=input_shape) self.bn = tf.keras.layers.BatchNormalization(momentum=self.momentum) def call(self, inputs, training=None): # pylint: disable=arguments-differ """Executes the convolution. Args: inputs: a dense tensor of size `[B, N, 1, D]`. training: flag to control batch normalization update statistics. Returns: Tensor with shape `[B, N, 1, C]`. """ return tf.nn.relu(self.bn(self.conv(inputs), training)) class PointNetDenseLayer(tf.keras.layers.Layer): """The fully connected layer used by the classification head in pointnet. Note: Differently from the standard Keras Conv2 layer, the order of ops is: 1. fully connected layer 2. batch normalization layer 3. ReLU activation unit """ def __init__(self, channels, momentum): super(PointNetDenseLayer, self).__init__() self.momentum = momentum self.channels = channels def build(self, input_shape): """Builds the layer with a specified input_shape.""" self.dense = tf.keras.layers.Dense(self.channels, input_shape=input_shape) self.bn = tf.keras.layers.BatchNormalization(momentum=self.momentum) def call(self, inputs, training=None): # pylint: disable=arguments-differ """Executes the convolution. Args: inputs: a dense tensor of size `[B, D]`. training: flag to control batch normalization update statistics. Returns: Tensor with shape `[B, C]`. """ return tf.nn.relu(self.bn(self.dense(inputs), training)) class VanillaEncoder(tf.keras.layers.Layer): """The Vanilla PointNet feature encoder. Consists of five conv2 layers with (64,64,64,128,1024) output channels. Note: PointNetConv2Layer are used instead of tf.keras.layers.Conv2D. https://github.com/charlesq34/pointnet/blob/master/models/pointnet_cls_basic.py """ def __init__(self, momentum=.5): """Constructs a VanillaEncoder keras layer. Args: momentum: the momentum used for the batch normalization layer. """ super(VanillaEncoder, self).__init__() self.conv1 = PointNetConv2Layer(64, momentum) self.conv2 = PointNetConv2Layer(64, momentum) self.conv3 = PointNetConv2Layer(64, momentum) self.conv4 = PointNetConv2Layer(128, momentum) self.conv5 = PointNetConv2Layer(1024, momentum) def call(self, inputs, training=None): # pylint: disable=arguments-differ """Computes the PointNet features. Args: inputs: a dense tensor of size `[B,N,D]`. training: flag to control batch normalization update statistics. Returns: Tensor with shape `[B, N, C=1024]` """ x = tf.expand_dims(inputs, axis=2) # [B,N,1,D] x = self.conv1(x, training) # [B,N,1,64] x = self.conv2(x, training) # [B,N,1,64] x = self.conv3(x, training) # [B,N,1,64] x = self.conv4(x, training) # [B,N,1,128] x = self.conv5(x, training) # [B,N,1,1024] x = tf.math.reduce_max(input_tensor=x, axis=1) # [B,1,1024] return tf.squeeze(x) # [B,1024] class ClassificationHead(tf.keras.layers.Layer): """The PointNet classification head. The head consists of 2x PointNetDenseLayer layers (512 and 256 channels) followed by a dropout layer (drop rate=30%) a dense linear layer producing the logits of the num_classes classes. """ def __init__(self, num_classes=40, momentum=0.5, dropout_rate=0.3): """Constructor. Args: num_classes: the number of classes to classify. momentum: the momentum used for the batch normalization layer. dropout_rate: the dropout rate for fully connected layer """ super(ClassificationHead, self).__init__() self.dense1 = PointNetDenseLayer(512, momentum) self.dense2 = PointNetDenseLayer(256, momentum) self.dropout = tf.keras.layers.Dropout(dropout_rate) self.dense3 = tf.keras.layers.Dense(num_classes, activation="linear") def call(self, inputs, training=None): # pylint: disable=arguments-differ """Computes the classifiation logits given features (note: without softmax). Args: inputs: tensor of points with shape `[B,D]`. training: flag for batch normalization and dropout training. Returns: Tensor with shape `[B,num_classes]` """ x = self.dense1(inputs, training) # [B,512] x = self.dense2(x, training) # [B,256] x = self.dropout(x, training) # [B,256] return self.dense3(x) # [B,num_classes) class PointNetVanillaClassifier(tf.keras.layers.Layer): """The PointNet 'Vanilla' classifier (i.e. without spatial transformer).""" def __init__(self, num_classes=40, momentum=.5, dropout_rate=.3): """Constructor. Args: num_classes: the number of classes to classify. momentum: the momentum used for the batch normalization layer. dropout_rate: the dropout rate for the classification head. """ super(PointNetVanillaClassifier, self).__init__() self.encoder = VanillaEncoder(momentum) self.classifier = ClassificationHead( num_classes=num_classes, momentum=momentum, dropout_rate=dropout_rate) def call(self, points, training=None): # pylint: disable=arguments-differ """Computes the classifiation logits of a point set. Args: points: a tensor of points with shape `[B, D]` training: for batch normalization and dropout training. Returns: Tensor with shape `[B,num_classes]` """ features = self.encoder(points, training) # (B,1024) logits = self.classifier(features, training) # (B,num_classes) return logits @staticmethod def loss(labels, logits): """The classification model training loss. Note: see tf.nn.sparse_softmax_cross_entropy_with_logits Args: labels: a tensor with shape `[B,]` logits: a tensor with shape `[B,num_classes]` """ cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits residual = cross_entropy(labels, logits) return tf.reduce_mean(input_tensor=residual)
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of the PointNet networks. @inproceedings{qi2017pointnet, title={Pointnet: Deep learning on point sets for3d classification and segmentation}, author={Qi, Charles R and Su, Hao and Mo, Kaichun and Guibas, Leonidas J}, booktitle={Proceedings of the IEEE conference on computer vision and pattern recognition}, pages={652--660}, year={2017}} NOTE: scheduling of batchnorm momentum currently not available in keras. However experimentally, using the batch norm from Keras resulted in better test accuracy (+1.5%) than the author's [custom batch norm version](https://github.com/charlesq34/pointnet/blob/master/utils/tf_util.py) even when coupled with batchnorm momentum decay. Further, note the author's version is actually performing a "global normalization", as mentioned in the [tf.nn.moments documentation] (https://www.tensorflow.org/api_docs/python/tf/nn/moments). This shorthand notation is used throughout this module: `B`: Number of elements in a batch. `N`: The number of points in the point set. `D`: Number of dimensions (e.g. 2 for 2D, 3 for 3D). `C`: The number of feature channels. """ import tensorflow as tf from tensorflow_graphics.util import export_api class PointNetConv2Layer(tf.keras.layers.Layer): """The 2D convolution layer used by the feature encoder in PointNet.""" def __init__(self, channels, momentum): """Constructs a Conv2 layer. Note: Differently from the standard Keras Conv2 layer, the order of ops is: 1. fully connected layer 2. batch normalization layer 3. ReLU activation unit Args: channels: the number of generated feature. momentum: the momentum of the batch normalization layer. """ super(PointNetConv2Layer, self).__init__() self.channels = channels self.momentum = momentum def build(self, input_shape): """Builds the layer with a specified input_shape.""" self.conv = tf.keras.layers.Conv2D( self.channels, (1, 1), input_shape=input_shape) self.bn = tf.keras.layers.BatchNormalization(momentum=self.momentum) def call(self, inputs, training=None): # pylint: disable=arguments-differ """Executes the convolution. Args: inputs: a dense tensor of size `[B, N, 1, D]`. training: flag to control batch normalization update statistics. Returns: Tensor with shape `[B, N, 1, C]`. """ return tf.nn.relu(self.bn(self.conv(inputs), training)) class PointNetDenseLayer(tf.keras.layers.Layer): """The fully connected layer used by the classification head in pointnet. Note: Differently from the standard Keras Conv2 layer, the order of ops is: 1. fully connected layer 2. batch normalization layer 3. ReLU activation unit """ def __init__(self, channels, momentum): super(PointNetDenseLayer, self).__init__() self.momentum = momentum self.channels = channels def build(self, input_shape): """Builds the layer with a specified input_shape.""" self.dense = tf.keras.layers.Dense(self.channels, input_shape=input_shape) self.bn = tf.keras.layers.BatchNormalization(momentum=self.momentum) def call(self, inputs, training=None): # pylint: disable=arguments-differ """Executes the convolution. Args: inputs: a dense tensor of size `[B, D]`. training: flag to control batch normalization update statistics. Returns: Tensor with shape `[B, C]`. """ return tf.nn.relu(self.bn(self.dense(inputs), training)) class VanillaEncoder(tf.keras.layers.Layer): """The Vanilla PointNet feature encoder. Consists of five conv2 layers with (64,64,64,128,1024) output channels. Note: PointNetConv2Layer are used instead of tf.keras.layers.Conv2D. https://github.com/charlesq34/pointnet/blob/master/models/pointnet_cls_basic.py """ def __init__(self, momentum=.5): """Constructs a VanillaEncoder keras layer. Args: momentum: the momentum used for the batch normalization layer. """ super(VanillaEncoder, self).__init__() self.conv1 = PointNetConv2Layer(64, momentum) self.conv2 = PointNetConv2Layer(64, momentum) self.conv3 = PointNetConv2Layer(64, momentum) self.conv4 = PointNetConv2Layer(128, momentum) self.conv5 = PointNetConv2Layer(1024, momentum) def call(self, inputs, training=None): # pylint: disable=arguments-differ """Computes the PointNet features. Args: inputs: a dense tensor of size `[B,N,D]`. training: flag to control batch normalization update statistics. Returns: Tensor with shape `[B, N, C=1024]` """ x = tf.expand_dims(inputs, axis=2) # [B,N,1,D] x = self.conv1(x, training) # [B,N,1,64] x = self.conv2(x, training) # [B,N,1,64] x = self.conv3(x, training) # [B,N,1,64] x = self.conv4(x, training) # [B,N,1,128] x = self.conv5(x, training) # [B,N,1,1024] x = tf.math.reduce_max(input_tensor=x, axis=1) # [B,1,1024] return tf.squeeze(x) # [B,1024] class ClassificationHead(tf.keras.layers.Layer): """The PointNet classification head. The head consists of 2x PointNetDenseLayer layers (512 and 256 channels) followed by a dropout layer (drop rate=30%) a dense linear layer producing the logits of the num_classes classes. """ def __init__(self, num_classes=40, momentum=0.5, dropout_rate=0.3): """Constructor. Args: num_classes: the number of classes to classify. momentum: the momentum used for the batch normalization layer. dropout_rate: the dropout rate for fully connected layer """ super(ClassificationHead, self).__init__() self.dense1 = PointNetDenseLayer(512, momentum) self.dense2 = PointNetDenseLayer(256, momentum) self.dropout = tf.keras.layers.Dropout(dropout_rate) self.dense3 = tf.keras.layers.Dense(num_classes, activation="linear") def call(self, inputs, training=None): # pylint: disable=arguments-differ """Computes the classifiation logits given features (note: without softmax). Args: inputs: tensor of points with shape `[B,D]`. training: flag for batch normalization and dropout training. Returns: Tensor with shape `[B,num_classes]` """ x = self.dense1(inputs, training) # [B,512] x = self.dense2(x, training) # [B,256] x = self.dropout(x, training) # [B,256] return self.dense3(x) # [B,num_classes) class PointNetVanillaClassifier(tf.keras.layers.Layer): """The PointNet 'Vanilla' classifier (i.e. without spatial transformer).""" def __init__(self, num_classes=40, momentum=.5, dropout_rate=.3): """Constructor. Args: num_classes: the number of classes to classify. momentum: the momentum used for the batch normalization layer. dropout_rate: the dropout rate for the classification head. """ super(PointNetVanillaClassifier, self).__init__() self.encoder = VanillaEncoder(momentum) self.classifier = ClassificationHead( num_classes=num_classes, momentum=momentum, dropout_rate=dropout_rate) def call(self, points, training=None): # pylint: disable=arguments-differ """Computes the classifiation logits of a point set. Args: points: a tensor of points with shape `[B, D]` training: for batch normalization and dropout training. Returns: Tensor with shape `[B,num_classes]` """ features = self.encoder(points, training) # (B,1024) logits = self.classifier(features, training) # (B,num_classes) return logits @staticmethod def loss(labels, logits): """The classification model training loss. Note: see tf.nn.sparse_softmax_cross_entropy_with_logits Args: labels: a tensor with shape `[B,]` logits: a tensor with shape `[B,num_classes]` """ cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits residual = cross_entropy(labels, logits) return tf.reduce_mean(input_tensor=residual) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/rendering/camera/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Camera module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.rendering.camera import orthographic from tensorflow_graphics.rendering.camera import perspective from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.rendering.camera. __all__ = _export_api.get_modules()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Camera module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.rendering.camera import orthographic from tensorflow_graphics.rendering.camera import perspective from tensorflow_graphics.rendering.camera import quadratic_radial_distortion from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.rendering.camera. __all__ = _export_api.get_modules()
1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/nn/layer/tests/graph_convolution_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the graph convolution layers.""" from absl.testing import parameterized import numpy as np import tensorflow as tf import tensorflow_graphics.nn.layer.graph_convolution as gc_layer from tensorflow_graphics.util import test_case def _dense_to_sparse(data): """Convert a numpy array to a tf.SparseTensor.""" indices = np.where(data) return tf.SparseTensor( np.stack(indices, axis=-1), data[indices], dense_shape=data.shape) def _dummy_data(batch_size, num_vertices, num_channels): """Create inputs for feature_steered_convolution.""" if batch_size > 0: data = np.zeros( shape=(batch_size, num_vertices, num_channels), dtype=np.float32) neighbors = _dense_to_sparse( np.tile(np.eye(num_vertices, dtype=np.float32), (batch_size, 1, 1))) else: data = np.zeros(shape=(num_vertices, num_channels), dtype=np.float32) neighbors = _dense_to_sparse(np.eye(num_vertices, dtype=np.float32)) return data, neighbors class GraphConvolutionTestFeatureSteeredConvolutionLayerTests( test_case.TestCase): @parameterized.parameters( (1, 1, 1, 1, 1, False), (4, 2, 3, None, 5, False), (1, 2, 3, 4, 5, True), ) def test_feature_steered_convolution_layer_exception_not_raised_shapes( self, batch_size, num_vertices, in_channels, out_channels, num_weight_matrices, translation_invariant): """Check if the convolution parameters and output have correct shapes.""" data, neighbors = _dummy_data(batch_size, num_vertices, in_channels) name_scope = "test" if tf.executing_eagerly(): layer = gc_layer.FeatureSteeredConvolutionKerasLayer( translation_invariant=translation_invariant, num_weight_matrices=num_weight_matrices, num_output_channels=out_channels, name=name_scope) def _run_convolution(): """Run the appropriate feature steered convolution layer.""" if tf.executing_eagerly(): try: output = layer(inputs=[data, neighbors], sizes=None) except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) else: try: output = gc_layer.feature_steered_convolution_layer( data=data, neighbors=neighbors, sizes=None, translation_invariant=translation_invariant, num_weight_matrices=num_weight_matrices, num_output_channels=out_channels, name=None, var_name=name_scope) except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) return output output = _run_convolution() output_shape = output.shape.as_list() out_channels = in_channels if out_channels is None else out_channels self.assertEqual(output_shape[-1], out_channels) self.assertAllEqual(output_shape[:-1], data.shape[:-1]) def _get_var_shape(var_name): """Get the shape of a variable by name.""" if tf.executing_eagerly(): trainable_variables = layer.trainable_variables for tv in trainable_variables: if tv.name == name_scope + "/" + var_name + ":0": return tv.shape.as_list() raise ValueError("Variable not found.") else: with tf.compat.v1.variable_scope(name_scope, reuse=True): variable = tf.compat.v1.get_variable( var_name, initializer=tf.constant(0)) return variable.shape.as_list() self.assertAllEqual(_get_var_shape("u"), [in_channels, num_weight_matrices]) self.assertAllEqual(_get_var_shape("c"), [num_weight_matrices]) self.assertAllEqual(_get_var_shape("b"), [out_channels]) self.assertAllEqual( _get_var_shape("w"), [num_weight_matrices, in_channels, out_channels]) if not translation_invariant: self.assertAllEqual( _get_var_shape("v"), [in_channels, num_weight_matrices]) def test_feature_steered_convolution_layer_initializer(self): """Tests a custom variable initializer.""" data = np.array(((1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0))) neighbors_indices = np.array(((0, 0), (0, 1), (0, 3), (1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (2, 3), (3, 0), (3, 2), (3, 3))) neighbors = tf.SparseTensor( neighbors_indices, np.ones(shape=(12,)) / 3.0, dense_shape=(4, 4)) initializer = tf.compat.v1.keras.initializers.zeros() if tf.executing_eagerly(): layer = gc_layer.FeatureSteeredConvolutionKerasLayer( translation_invariant=False, initializer=initializer) output = layer(inputs=[data, neighbors], sizes=None) else: out = gc_layer.feature_steered_convolution_layer( data=data, neighbors=neighbors, sizes=None, translation_invariant=False, initializer=initializer) self.evaluate(tf.compat.v1.global_variables_initializer()) output = self.evaluate(out) # All zeros initializer should result in all zeros output. self.assertAllEqual(output, np.zeros_like(data)) def test_feature_steered_convolution_layer_training(self): """Test a simple training loop.""" # Generate a small valid input for a simple training task. # Four corners of a square. data = np.array(((1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0))) neighbors_indices = np.array(((0, 0), (0, 1), (0, 3), (1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (2, 3), (3, 0), (3, 2), (3, 3))) neighbors = tf.SparseTensor( neighbors_indices, np.ones(shape=(12,)) / 3.0, dense_shape=(4, 4)) # Desired output is arbitrary. labels = np.reshape([-1.0, -0.5, 0.5, 1.0], (-1, 1)) num_training_iterations = 5 if tf.executing_eagerly(): with tf.GradientTape(persistent=True) as tape: layer = gc_layer.FeatureSteeredConvolutionKerasLayer( translation_invariant=False, num_weight_matrices=1, num_output_channels=1) output = layer(inputs=[data, neighbors], sizes=None) loss = tf.nn.l2_loss(output - labels) trainable_variables = layer.trainable_variables for _ in range(num_training_iterations): grads = tape.gradient(loss, trainable_variables) tf.compat.v1.train.GradientDescentOptimizer(1e-4).apply_gradients( zip(grads, trainable_variables)) else: output = gc_layer.feature_steered_convolution_layer( data=data, neighbors=neighbors, sizes=None, translation_invariant=False, num_weight_matrices=1, num_output_channels=1) train_op = tf.compat.v1.train.GradientDescentOptimizer(1e-4).minimize( tf.nn.l2_loss(output - labels)) with tf.compat.v1.Session() as sess: sess.run(tf.compat.v1.initialize_all_variables()) for _ in range(num_training_iterations): sess.run(train_op) class GraphConvolutionTestDynamicGraphConvolutionKerasLayerTests( test_case.TestCase): @parameterized.parameters( (1, 1, 1, 1, "weighted"), (4, 2, 3, 12, "max"), (1, 2, 3, 4, "max"), ) def test_dynamic_graph_convolution_keras_layer_exception_not_raised_shapes( self, batch_size, num_vertices, in_channels, out_channels, reduction): """Check if the convolution parameters and output have correct shapes.""" if not tf.executing_eagerly(): return data, neighbors = _dummy_data(batch_size, num_vertices, in_channels) layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=out_channels, reduction=reduction) try: output = layer(inputs=[data, neighbors], sizes=None) except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) self.assertAllEqual((batch_size, num_vertices, out_channels), output.shape) @parameterized.parameters( (1, 1, 1, 1, "weighted"), (4, 2, 3, 12, "max"), (1, 2, 3, 4, "max"), ) def test_dynamic_graph_convolution_keras_layer_zero_kernel( self, batch_size, num_vertices, in_channels, out_channels, reduction): """Tests convolution with an all-zeros kernel.""" if not tf.executing_eagerly(): return data, neighbors = _dummy_data(batch_size, num_vertices, in_channels) data = np.random.uniform(size=data.shape).astype(np.float32) layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=out_channels, reduction=reduction, use_bias=False, kernel_initializer=tf.compat.v1.keras.initializers.zeros()) output = layer(inputs=[data, neighbors], sizes=None) self.assertAllEqual( output, np.zeros(shape=(batch_size, num_vertices, out_channels), dtype=np.float32)) @parameterized.parameters((1, 1, 1), (2, 3, 12), (2, 3, 4)) def test_dynamic_graph_convolution_keras_layer_duplicate_features( self, num_vertices, in_channels, out_channels): """Tests convolution when all vertex features are identical.""" if not tf.executing_eagerly(): return data = np.random.uniform(size=(1, in_channels)) data = np.tile(data, (num_vertices, 1)) # Results should be independent of 'neighbors'. neighbors = np.maximum(np.random.randint( 0, 2, size=(num_vertices, num_vertices)), np.eye(num_vertices)) neighbors = _dense_to_sparse(neighbors) layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=out_channels, reduction="max") output = layer(inputs=[data, neighbors], sizes=None) output_tile = tf.tile(output[:1, :], (num_vertices, 1)) self.assertAllEqual(output, output_tile) @parameterized.parameters("weighted", "max") def test_dynamic_graph_convolution_keras_layer_training(self, reduction): """Test a simple training loop.""" if not tf.executing_eagerly(): return # Generate a small valid input for a simple training task. # Four corners of a square. data = np.array(((1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0))) neighbors_indices = np.array(((0, 0), (0, 1), (0, 3), (1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (2, 3), (3, 0), (3, 2), (3, 3))) neighbors = tf.SparseTensor( neighbors_indices, np.ones(shape=(12,)) / 3.0, dense_shape=(4, 4)) # Desired output is arbitrary. labels = np.reshape([-1.0, -0.5, 0.5, 1.0], (-1, 1)) num_training_iterations = 5 with tf.GradientTape(persistent=True) as tape: layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=2, reduction=reduction) output = layer(inputs=[data, neighbors], sizes=None) loss = tf.nn.l2_loss(output - labels) trainable_variables = layer.trainable_variables for _ in range(num_training_iterations): grads = tape.gradient(loss, trainable_variables) tf.compat.v1.train.GradientDescentOptimizer(1e-4).apply_gradients( zip(grads, trainable_variables)) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the graph convolution layers.""" from absl.testing import parameterized import numpy as np import tensorflow as tf import tensorflow_graphics.nn.layer.graph_convolution as gc_layer from tensorflow_graphics.util import test_case def _dense_to_sparse(data): """Convert a numpy array to a tf.SparseTensor.""" indices = np.where(data) return tf.SparseTensor( np.stack(indices, axis=-1), data[indices], dense_shape=data.shape) def _dummy_data(batch_size, num_vertices, num_channels): """Create inputs for feature_steered_convolution.""" if batch_size > 0: data = np.zeros( shape=(batch_size, num_vertices, num_channels), dtype=np.float32) neighbors = _dense_to_sparse( np.tile(np.eye(num_vertices, dtype=np.float32), (batch_size, 1, 1))) else: data = np.zeros(shape=(num_vertices, num_channels), dtype=np.float32) neighbors = _dense_to_sparse(np.eye(num_vertices, dtype=np.float32)) return data, neighbors class GraphConvolutionTestFeatureSteeredConvolutionLayerTests( test_case.TestCase): @parameterized.parameters( (1, 1, 1, 1, 1, False), (4, 2, 3, None, 5, False), (1, 2, 3, 4, 5, True), ) def test_feature_steered_convolution_layer_exception_not_raised_shapes( self, batch_size, num_vertices, in_channels, out_channels, num_weight_matrices, translation_invariant): """Check if the convolution parameters and output have correct shapes.""" data, neighbors = _dummy_data(batch_size, num_vertices, in_channels) name_scope = "test" if tf.executing_eagerly(): layer = gc_layer.FeatureSteeredConvolutionKerasLayer( translation_invariant=translation_invariant, num_weight_matrices=num_weight_matrices, num_output_channels=out_channels, name=name_scope) def _run_convolution(): """Run the appropriate feature steered convolution layer.""" if tf.executing_eagerly(): try: output = layer(inputs=[data, neighbors], sizes=None) except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) else: try: output = gc_layer.feature_steered_convolution_layer( data=data, neighbors=neighbors, sizes=None, translation_invariant=translation_invariant, num_weight_matrices=num_weight_matrices, num_output_channels=out_channels, name=None, var_name=name_scope) except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) return output output = _run_convolution() output_shape = output.shape.as_list() out_channels = in_channels if out_channels is None else out_channels self.assertEqual(output_shape[-1], out_channels) self.assertAllEqual(output_shape[:-1], data.shape[:-1]) def _get_var_shape(var_name): """Get the shape of a variable by name.""" if tf.executing_eagerly(): trainable_variables = layer.trainable_variables for tv in trainable_variables: if tv.name == name_scope + "/" + var_name + ":0": return tv.shape.as_list() raise ValueError("Variable not found.") else: with tf.compat.v1.variable_scope(name_scope, reuse=True): variable = tf.compat.v1.get_variable( var_name, initializer=tf.constant(0)) return variable.shape.as_list() self.assertAllEqual(_get_var_shape("u"), [in_channels, num_weight_matrices]) self.assertAllEqual(_get_var_shape("c"), [num_weight_matrices]) self.assertAllEqual(_get_var_shape("b"), [out_channels]) self.assertAllEqual( _get_var_shape("w"), [num_weight_matrices, in_channels, out_channels]) if not translation_invariant: self.assertAllEqual( _get_var_shape("v"), [in_channels, num_weight_matrices]) def test_feature_steered_convolution_layer_initializer(self): """Tests a custom variable initializer.""" data = np.array(((1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0))) neighbors_indices = np.array(((0, 0), (0, 1), (0, 3), (1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (2, 3), (3, 0), (3, 2), (3, 3))) neighbors = tf.SparseTensor( neighbors_indices, np.ones(shape=(12,)) / 3.0, dense_shape=(4, 4)) initializer = tf.compat.v1.keras.initializers.zeros() if tf.executing_eagerly(): layer = gc_layer.FeatureSteeredConvolutionKerasLayer( translation_invariant=False, initializer=initializer) output = layer(inputs=[data, neighbors], sizes=None) else: out = gc_layer.feature_steered_convolution_layer( data=data, neighbors=neighbors, sizes=None, translation_invariant=False, initializer=initializer) self.evaluate(tf.compat.v1.global_variables_initializer()) output = self.evaluate(out) # All zeros initializer should result in all zeros output. self.assertAllEqual(output, np.zeros_like(data)) def test_feature_steered_convolution_layer_training(self): """Test a simple training loop.""" # Generate a small valid input for a simple training task. # Four corners of a square. data = np.array(((1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0))) neighbors_indices = np.array(((0, 0), (0, 1), (0, 3), (1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (2, 3), (3, 0), (3, 2), (3, 3))) neighbors = tf.SparseTensor( neighbors_indices, np.ones(shape=(12,)) / 3.0, dense_shape=(4, 4)) # Desired output is arbitrary. labels = np.reshape([-1.0, -0.5, 0.5, 1.0], (-1, 1)) num_training_iterations = 5 if tf.executing_eagerly(): with tf.GradientTape(persistent=True) as tape: layer = gc_layer.FeatureSteeredConvolutionKerasLayer( translation_invariant=False, num_weight_matrices=1, num_output_channels=1) output = layer(inputs=[data, neighbors], sizes=None) loss = tf.nn.l2_loss(output - labels) trainable_variables = layer.trainable_variables for _ in range(num_training_iterations): grads = tape.gradient(loss, trainable_variables) tf.compat.v1.train.GradientDescentOptimizer(1e-4).apply_gradients( zip(grads, trainable_variables)) else: output = gc_layer.feature_steered_convolution_layer( data=data, neighbors=neighbors, sizes=None, translation_invariant=False, num_weight_matrices=1, num_output_channels=1) train_op = tf.compat.v1.train.GradientDescentOptimizer(1e-4).minimize( tf.nn.l2_loss(output - labels)) with tf.compat.v1.Session() as sess: sess.run(tf.compat.v1.initialize_all_variables()) for _ in range(num_training_iterations): sess.run(train_op) class GraphConvolutionTestDynamicGraphConvolutionKerasLayerTests( test_case.TestCase): @parameterized.parameters( (1, 1, 1, 1, "weighted"), (4, 2, 3, 12, "max"), (1, 2, 3, 4, "max"), ) def test_dynamic_graph_convolution_keras_layer_exception_not_raised_shapes( self, batch_size, num_vertices, in_channels, out_channels, reduction): """Check if the convolution parameters and output have correct shapes.""" if not tf.executing_eagerly(): return data, neighbors = _dummy_data(batch_size, num_vertices, in_channels) layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=out_channels, reduction=reduction) try: output = layer(inputs=[data, neighbors], sizes=None) except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) self.assertAllEqual((batch_size, num_vertices, out_channels), output.shape) @parameterized.parameters( (1, 1, 1, 1, "weighted"), (4, 2, 3, 12, "max"), (1, 2, 3, 4, "max"), ) def test_dynamic_graph_convolution_keras_layer_zero_kernel( self, batch_size, num_vertices, in_channels, out_channels, reduction): """Tests convolution with an all-zeros kernel.""" if not tf.executing_eagerly(): return data, neighbors = _dummy_data(batch_size, num_vertices, in_channels) data = np.random.uniform(size=data.shape).astype(np.float32) layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=out_channels, reduction=reduction, use_bias=False, kernel_initializer=tf.compat.v1.keras.initializers.zeros()) output = layer(inputs=[data, neighbors], sizes=None) self.assertAllEqual( output, np.zeros(shape=(batch_size, num_vertices, out_channels), dtype=np.float32)) @parameterized.parameters((1, 1, 1), (2, 3, 12), (2, 3, 4)) def test_dynamic_graph_convolution_keras_layer_duplicate_features( self, num_vertices, in_channels, out_channels): """Tests convolution when all vertex features are identical.""" if not tf.executing_eagerly(): return data = np.random.uniform(size=(1, in_channels)) data = np.tile(data, (num_vertices, 1)) # Results should be independent of 'neighbors'. neighbors = np.maximum(np.random.randint( 0, 2, size=(num_vertices, num_vertices)), np.eye(num_vertices)) neighbors = _dense_to_sparse(neighbors) layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=out_channels, reduction="max") output = layer(inputs=[data, neighbors], sizes=None) output_tile = tf.tile(output[:1, :], (num_vertices, 1)) self.assertAllEqual(output, output_tile) @parameterized.parameters("weighted", "max") def test_dynamic_graph_convolution_keras_layer_training(self, reduction): """Test a simple training loop.""" if not tf.executing_eagerly(): return # Generate a small valid input for a simple training task. # Four corners of a square. data = np.array(((1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0))) neighbors_indices = np.array(((0, 0), (0, 1), (0, 3), (1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (2, 3), (3, 0), (3, 2), (3, 3))) neighbors = tf.SparseTensor( neighbors_indices, np.ones(shape=(12,)) / 3.0, dense_shape=(4, 4)) # Desired output is arbitrary. labels = np.reshape([-1.0, -0.5, 0.5, 1.0], (-1, 1)) num_training_iterations = 5 with tf.GradientTape(persistent=True) as tape: layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=2, reduction=reduction) output = layer(inputs=[data, neighbors], sizes=None) loss = tf.nn.l2_loss(output - labels) trainable_variables = layer.trainable_variables for _ in range(num_training_iterations): grads = tape.gradient(loss, trainable_variables) tf.compat.v1.train.GradientDescentOptimizer(1e-4).apply_gradients( zip(grads, trainable_variables)) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/datasets/features/voxel_feature.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Voxel grid feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np from scipy import io as sio import tensorflow as tf from tensorflow_datasets import features class VoxelGrid(features.Tensor): """`FeatureConnector` for voxel grids. During `_generate_examples`, the feature connector accepts as input any of: * `dict`: dictionary containing the path to a {.mat} file and the key under which the voxel grid is accessible inside the file. Structure of the dictionary: { 'path': 'path/to/file.mat', 'key': 'foo' } * `np.ndarray`: float32 numpy array of shape [X,Y,Z] representing the voxel grid. Output: A float32 Tensor with shape [X,Y,Z] containing the voxel occupancies. """ def __init__(self, shape): super(VoxelGrid, self).__init__(shape=shape, dtype=tf.float32) def encode_example(self, example_data): # Path to .mat file if isinstance(example_data, dict): if not all(key in example_data for key in ['path', 'key']): raise ValueError( f'Missing keys in provided dictionary! Expecting \'path\'' f' and \'key\', but {example_data.keys()} were given.') if not os.path.exists(example_data['path']): raise FileNotFoundError( f"File `{example_data['path']}` does not exist.") with tf.io.gfile.GFile(example_data['path'], 'rb') as mat_file: voxel_mat = sio.loadmat(mat_file) if example_data['key'] not in voxel_mat: raise ValueError(f"Key `{example_data['key']}` not found in .mat file. " f"Available keys in file: {voxel_mat.keys()}") voxel_grid = voxel_mat[example_data['key']].astype(np.float32) else: if example_data.ndim != 3: raise ValueError('Only 3D Voxel Grids are supported.') voxel_grid = example_data return super(VoxelGrid, self).encode_example(voxel_grid) @classmethod def from_json_content(cls, value) -> 'VoxelGrid': return cls(shape=tuple(value['shape'])) def to_json_content(self): return { 'shape': list(self._shape), }
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Voxel grid feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np from scipy import io as sio import tensorflow as tf from tensorflow_datasets import features class VoxelGrid(features.Tensor): """`FeatureConnector` for voxel grids. During `_generate_examples`, the feature connector accepts as input any of: * `dict`: dictionary containing the path to a {.mat} file and the key under which the voxel grid is accessible inside the file. Structure of the dictionary: { 'path': 'path/to/file.mat', 'key': 'foo' } * `np.ndarray`: float32 numpy array of shape [X,Y,Z] representing the voxel grid. Output: A float32 Tensor with shape [X,Y,Z] containing the voxel occupancies. """ def __init__(self, shape): super(VoxelGrid, self).__init__(shape=shape, dtype=tf.float32) def encode_example(self, example_data): # Path to .mat file if isinstance(example_data, dict): if not all(key in example_data for key in ['path', 'key']): raise ValueError( f'Missing keys in provided dictionary! Expecting \'path\'' f' and \'key\', but {example_data.keys()} were given.') if not os.path.exists(example_data['path']): raise FileNotFoundError( f"File `{example_data['path']}` does not exist.") with tf.io.gfile.GFile(example_data['path'], 'rb') as mat_file: voxel_mat = sio.loadmat(mat_file) if example_data['key'] not in voxel_mat: raise ValueError(f"Key `{example_data['key']}` not found in .mat file. " f"Available keys in file: {voxel_mat.keys()}") voxel_grid = voxel_mat[example_data['key']].astype(np.float32) else: if example_data.ndim != 3: raise ValueError('Only 3D Voxel Grids are supported.') voxel_grid = example_data return super(VoxelGrid, self).encode_example(voxel_grid) @classmethod def from_json_content(cls, value) -> 'VoxelGrid': return cls(shape=tuple(value['shape'])) def to_json_content(self): return { 'shape': list(self._shape), }
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/convolution/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Convolution module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.geometry.convolution import graph_convolution from tensorflow_graphics.geometry.convolution import graph_pooling from tensorflow_graphics.geometry.convolution import utils from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.geometry.convolution. __all__ = _export_api.get_modules()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Convolution module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.geometry.convolution import graph_convolution from tensorflow_graphics.geometry.convolution import graph_pooling from tensorflow_graphics.geometry.convolution import utils from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.geometry.convolution. __all__ = _export_api.get_modules()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/transformation/tests/test_helpers.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test helpers for the transformation module.""" import itertools import math import numpy as np from scipy import stats import tensorflow.compat.v2 as tf from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_2d from tensorflow_graphics.geometry.transformation import rotation_matrix_3d def generate_preset_test_euler_angles(dimensions=3): """Generates a permutation with duplicate of some classic euler angles.""" permutations = itertools.product( [0., np.pi, np.pi / 2., np.pi / 3., np.pi / 4., np.pi / 6.], repeat=dimensions) return np.array(list(permutations)) def generate_preset_test_translations(dimensions=3): """Generates a set of translations.""" permutations = itertools.product([0.1, -0.2, 0.5, 0.7, 0.4, -0.1], repeat=dimensions) return np.array(list(permutations)) def generate_preset_test_rotation_matrices_3d(): """Generates pre-set test 3d rotation matrices.""" angles = generate_preset_test_euler_angles() preset_rotation_matrix = rotation_matrix_3d.from_euler(angles) if tf.executing_eagerly(): return np.array(preset_rotation_matrix) with tf.compat.v1.Session() as sess: return np.array(sess.run([preset_rotation_matrix])) def generate_preset_test_rotation_matrices_2d(): """Generates pre-set test 2d rotation matrices.""" angles = generate_preset_test_euler_angles(dimensions=1) preset_rotation_matrix = rotation_matrix_2d.from_euler(angles) if tf.executing_eagerly(): return np.array(preset_rotation_matrix) with tf.compat.v1.Session() as sess: return np.array(sess.run([preset_rotation_matrix])) def generate_preset_test_axis_angle(): """Generates pre-set test rotation matrices.""" angles = generate_preset_test_euler_angles() axis, angle = axis_angle.from_euler(angles) if tf.executing_eagerly(): return np.array(axis), np.array(angle) with tf.compat.v1.Session() as sess: return np.array(sess.run([axis])), np.array(sess.run([angle])) def generate_preset_test_quaternions(): """Generates pre-set test quaternions.""" angles = generate_preset_test_euler_angles() preset_quaternion = quaternion.from_euler(angles) if tf.executing_eagerly(): return np.array(preset_quaternion) with tf.compat.v1.Session() as sess: return np.array(sess.run([preset_quaternion])) def generate_preset_test_dual_quaternions(): """Generates pre-set test quaternions.""" angles = generate_preset_test_euler_angles() preset_quaternion_real = quaternion.from_euler(angles) translations = generate_preset_test_translations() translations = np.concatenate( (translations / 2.0, np.zeros((np.ma.size(translations, 0), 1))), axis=1) preset_quaternion_translation = tf.convert_to_tensor(value=translations) preset_quaternion_dual = quaternion.multiply(preset_quaternion_translation, preset_quaternion_real) preset_dual_quaternion = tf.concat( (preset_quaternion_real, preset_quaternion_dual), axis=-1) return preset_dual_quaternion def generate_random_test_dual_quaternions(): """Generates random test dual quaternions.""" angles = generate_random_test_euler_angles() random_quaternion_real = quaternion.from_euler(angles) min_translation = -3.0 max_translation = 3.0 translations = np.random.uniform(min_translation, max_translation, angles.shape) translations_quaternion_shape = np.asarray(translations.shape) translations_quaternion_shape[-1] = 1 translations = np.concatenate( (translations / 2.0, np.zeros(translations_quaternion_shape)), axis=-1) random_quaternion_translation = tf.convert_to_tensor(value=translations) random_quaternion_dual = quaternion.multiply(random_quaternion_translation, random_quaternion_real) random_dual_quaternion = tf.concat( (random_quaternion_real, random_quaternion_dual), axis=-1) return random_dual_quaternion def generate_random_test_euler_angles(dimensions=3, min_angle=-3. * np.pi, max_angle=3. * np.pi): """Generates random test random Euler angles.""" tensor_dimensions = np.random.randint(3) tensor_tile = np.random.randint(1, 10, tensor_dimensions).tolist() return np.random.uniform(min_angle, max_angle, tensor_tile + [dimensions]) def generate_random_test_quaternions(tensor_shape=None): """Generates random test quaternions.""" if tensor_shape is None: tensor_dimensions = np.random.randint(low=1, high=3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() u1 = np.random.uniform(0.0, 1.0, tensor_shape) u2 = np.random.uniform(0.0, 2.0 * math.pi, tensor_shape) u3 = np.random.uniform(0.0, 2.0 * math.pi, tensor_shape) a = np.sqrt(1.0 - u1) b = np.sqrt(u1) return np.stack((a * np.sin(u2), a * np.cos(u2), b * np.sin(u3), b * np.cos(u3)), axis=-1) # pyformat: disable def generate_random_test_axis_angle(): """Generates random test axis-angles.""" tensor_dimensions = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() random_axis = np.random.uniform(size=tensor_shape + [3]) random_axis /= np.linalg.norm(random_axis, axis=-1, keepdims=True) random_angle = np.random.uniform(size=tensor_shape + [1]) return random_axis, random_angle def generate_random_test_rotation_matrix_3d(): """Generates random test 3d rotation matrices.""" random_matrix = np.array( [stats.special_ortho_group.rvs(3) for _ in range(20)]) return np.reshape(random_matrix, [5, 4, 3, 3]) def generate_random_test_rotation_matrix_2d(): """Generates random test 2d rotation matrices.""" random_matrix = np.array( [stats.special_ortho_group.rvs(2) for _ in range(20)]) return np.reshape(random_matrix, [5, 4, 2, 2]) def generate_random_test_lbs_blend(): """Generates random test for the linear blend skinning blend function.""" tensor_dimensions = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() random_points = np.random.uniform(size=tensor_shape + [3]) num_weights = np.random.randint(2, 10) random_weights = np.random.uniform(size=tensor_shape + [num_weights]) random_weights /= np.sum(random_weights, axis=-1, keepdims=True) random_rotations = np.array( [stats.special_ortho_group.rvs(3) for _ in range(num_weights)]) random_rotations = np.reshape(random_rotations, [num_weights, 3, 3]) random_translations = np.random.uniform(size=[num_weights, 3]) return random_points, random_weights, random_rotations, random_translations def generate_preset_test_lbs_blend(): """Generates preset test for the linear blend skinning blend function.""" points = np.array([[[1.0, 0.0, 0.0], [0.1, 0.2, 0.5]], [[0.0, 1.0, 0.0], [0.3, -0.5, 0.2]], [[-0.3, 0.1, 0.3], [0.1, -0.9, -0.4]]]) weights = np.array([[[0.0, 1.0, 0.0, 0.0], [0.4, 0.2, 0.3, 0.1]], [[0.6, 0.0, 0.4, 0.0], [0.2, 0.2, 0.1, 0.5]], [[0.0, 0.1, 0.0, 0.9], [0.1, 0.2, 0.3, 0.4]]]) rotations = np.array( [[[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], [[0.36, 0.48, -0.8], [-0.8, 0.60, 0.00], [0.48, 0.64, 0.60]], [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], [[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, -1.0]]], [[[-0.41554751, -0.42205085, -0.80572535], [0.08028719, -0.89939186, 0.42970716], [-0.9060211, 0.11387432, 0.40762533]], [[-0.05240625, -0.24389111, 0.96838562], [0.99123384, -0.13047444, 0.02078231], [0.12128095, 0.96098572, 0.2485908]], [[-0.32722936, -0.06793413, -0.94249981], [-0.70574479, 0.68082693, 0.19595657], [0.62836712, 0.72928708, -0.27073072]], [[-0.22601332, -0.95393284, 0.19730719], [-0.01189659, 0.20523618, 0.97864017], [-0.97405157, 0.21883843, -0.05773466]]]]) # pyformat: disable translations = np.array( [[[0.1, -0.2, 0.5], [-0.2, 0.7, 0.7], [0.8, -0.2, 0.4], [-0.1, 0.2, -0.3]], [[0.5, 0.6, 0.9], [-0.1, -0.3, -0.7], [0.4, -0.2, 0.8], [0.7, 0.8, -0.4]]]) # pyformat: disable blended_points = np.array([[[[0.16, -0.1, 1.18], [0.3864, 0.148, 0.7352]], [[0.38, 0.4, 0.86], [-0.2184, 0.152, 0.0088]], [[-0.05, 0.01, -0.46], [-0.3152, -0.004, -0.1136]]], [[[-0.15240625, 0.69123384, -0.57871905], [0.07776242, 0.33587402, 0.55386645]], [[0.17959584, 0.01269566, 1.22003942], [0.71406514, 0.6187734, -0.43794053]], [[0.67662743, 0.94549789, -0.14946982], [0.88587099, -0.09324637, -0.45012815]]]]) return points, weights, rotations, translations, blended_points
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test helpers for the transformation module.""" import itertools import math import numpy as np from scipy import stats import tensorflow.compat.v2 as tf from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_2d from tensorflow_graphics.geometry.transformation import rotation_matrix_3d def generate_preset_test_euler_angles(dimensions=3): """Generates a permutation with duplicate of some classic euler angles.""" permutations = itertools.product( [0., np.pi, np.pi / 2., np.pi / 3., np.pi / 4., np.pi / 6.], repeat=dimensions) return np.array(list(permutations)) def generate_preset_test_translations(dimensions=3): """Generates a set of translations.""" permutations = itertools.product([0.1, -0.2, 0.5, 0.7, 0.4, -0.1], repeat=dimensions) return np.array(list(permutations)) def generate_preset_test_rotation_matrices_3d(): """Generates pre-set test 3d rotation matrices.""" angles = generate_preset_test_euler_angles() preset_rotation_matrix = rotation_matrix_3d.from_euler(angles) if tf.executing_eagerly(): return np.array(preset_rotation_matrix) with tf.compat.v1.Session() as sess: return np.array(sess.run([preset_rotation_matrix])) def generate_preset_test_rotation_matrices_2d(): """Generates pre-set test 2d rotation matrices.""" angles = generate_preset_test_euler_angles(dimensions=1) preset_rotation_matrix = rotation_matrix_2d.from_euler(angles) if tf.executing_eagerly(): return np.array(preset_rotation_matrix) with tf.compat.v1.Session() as sess: return np.array(sess.run([preset_rotation_matrix])) def generate_preset_test_axis_angle(): """Generates pre-set test rotation matrices.""" angles = generate_preset_test_euler_angles() axis, angle = axis_angle.from_euler(angles) if tf.executing_eagerly(): return np.array(axis), np.array(angle) with tf.compat.v1.Session() as sess: return np.array(sess.run([axis])), np.array(sess.run([angle])) def generate_preset_test_quaternions(): """Generates pre-set test quaternions.""" angles = generate_preset_test_euler_angles() preset_quaternion = quaternion.from_euler(angles) if tf.executing_eagerly(): return np.array(preset_quaternion) with tf.compat.v1.Session() as sess: return np.array(sess.run([preset_quaternion])) def generate_preset_test_dual_quaternions(): """Generates pre-set test quaternions.""" angles = generate_preset_test_euler_angles() preset_quaternion_real = quaternion.from_euler(angles) translations = generate_preset_test_translations() translations = np.concatenate( (translations / 2.0, np.zeros((np.ma.size(translations, 0), 1))), axis=1) preset_quaternion_translation = tf.convert_to_tensor(value=translations) preset_quaternion_dual = quaternion.multiply(preset_quaternion_translation, preset_quaternion_real) preset_dual_quaternion = tf.concat( (preset_quaternion_real, preset_quaternion_dual), axis=-1) return preset_dual_quaternion def generate_random_test_dual_quaternions(): """Generates random test dual quaternions.""" angles = generate_random_test_euler_angles() random_quaternion_real = quaternion.from_euler(angles) min_translation = -3.0 max_translation = 3.0 translations = np.random.uniform(min_translation, max_translation, angles.shape) translations_quaternion_shape = np.asarray(translations.shape) translations_quaternion_shape[-1] = 1 translations = np.concatenate( (translations / 2.0, np.zeros(translations_quaternion_shape)), axis=-1) random_quaternion_translation = tf.convert_to_tensor(value=translations) random_quaternion_dual = quaternion.multiply(random_quaternion_translation, random_quaternion_real) random_dual_quaternion = tf.concat( (random_quaternion_real, random_quaternion_dual), axis=-1) return random_dual_quaternion def generate_random_test_euler_angles(dimensions=3, min_angle=-3. * np.pi, max_angle=3. * np.pi): """Generates random test random Euler angles.""" tensor_dimensions = np.random.randint(3) tensor_tile = np.random.randint(1, 10, tensor_dimensions).tolist() return np.random.uniform(min_angle, max_angle, tensor_tile + [dimensions]) def generate_random_test_quaternions(tensor_shape=None): """Generates random test quaternions.""" if tensor_shape is None: tensor_dimensions = np.random.randint(low=1, high=3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() u1 = np.random.uniform(0.0, 1.0, tensor_shape) u2 = np.random.uniform(0.0, 2.0 * math.pi, tensor_shape) u3 = np.random.uniform(0.0, 2.0 * math.pi, tensor_shape) a = np.sqrt(1.0 - u1) b = np.sqrt(u1) return np.stack((a * np.sin(u2), a * np.cos(u2), b * np.sin(u3), b * np.cos(u3)), axis=-1) # pyformat: disable def generate_random_test_axis_angle(): """Generates random test axis-angles.""" tensor_dimensions = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() random_axis = np.random.uniform(size=tensor_shape + [3]) random_axis /= np.linalg.norm(random_axis, axis=-1, keepdims=True) random_angle = np.random.uniform(size=tensor_shape + [1]) return random_axis, random_angle def generate_random_test_rotation_matrix_3d(): """Generates random test 3d rotation matrices.""" random_matrix = np.array( [stats.special_ortho_group.rvs(3) for _ in range(20)]) return np.reshape(random_matrix, [5, 4, 3, 3]) def generate_random_test_rotation_matrix_2d(): """Generates random test 2d rotation matrices.""" random_matrix = np.array( [stats.special_ortho_group.rvs(2) for _ in range(20)]) return np.reshape(random_matrix, [5, 4, 2, 2]) def generate_random_test_lbs_blend(): """Generates random test for the linear blend skinning blend function.""" tensor_dimensions = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() random_points = np.random.uniform(size=tensor_shape + [3]) num_weights = np.random.randint(2, 10) random_weights = np.random.uniform(size=tensor_shape + [num_weights]) random_weights /= np.sum(random_weights, axis=-1, keepdims=True) random_rotations = np.array( [stats.special_ortho_group.rvs(3) for _ in range(num_weights)]) random_rotations = np.reshape(random_rotations, [num_weights, 3, 3]) random_translations = np.random.uniform(size=[num_weights, 3]) return random_points, random_weights, random_rotations, random_translations def generate_preset_test_lbs_blend(): """Generates preset test for the linear blend skinning blend function.""" points = np.array([[[1.0, 0.0, 0.0], [0.1, 0.2, 0.5]], [[0.0, 1.0, 0.0], [0.3, -0.5, 0.2]], [[-0.3, 0.1, 0.3], [0.1, -0.9, -0.4]]]) weights = np.array([[[0.0, 1.0, 0.0, 0.0], [0.4, 0.2, 0.3, 0.1]], [[0.6, 0.0, 0.4, 0.0], [0.2, 0.2, 0.1, 0.5]], [[0.0, 0.1, 0.0, 0.9], [0.1, 0.2, 0.3, 0.4]]]) rotations = np.array( [[[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], [[0.36, 0.48, -0.8], [-0.8, 0.60, 0.00], [0.48, 0.64, 0.60]], [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], [[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, -1.0]]], [[[-0.41554751, -0.42205085, -0.80572535], [0.08028719, -0.89939186, 0.42970716], [-0.9060211, 0.11387432, 0.40762533]], [[-0.05240625, -0.24389111, 0.96838562], [0.99123384, -0.13047444, 0.02078231], [0.12128095, 0.96098572, 0.2485908]], [[-0.32722936, -0.06793413, -0.94249981], [-0.70574479, 0.68082693, 0.19595657], [0.62836712, 0.72928708, -0.27073072]], [[-0.22601332, -0.95393284, 0.19730719], [-0.01189659, 0.20523618, 0.97864017], [-0.97405157, 0.21883843, -0.05773466]]]]) # pyformat: disable translations = np.array( [[[0.1, -0.2, 0.5], [-0.2, 0.7, 0.7], [0.8, -0.2, 0.4], [-0.1, 0.2, -0.3]], [[0.5, 0.6, 0.9], [-0.1, -0.3, -0.7], [0.4, -0.2, 0.8], [0.7, 0.8, -0.4]]]) # pyformat: disable blended_points = np.array([[[[0.16, -0.1, 1.18], [0.3864, 0.148, 0.7352]], [[0.38, 0.4, 0.86], [-0.2184, 0.152, 0.0088]], [[-0.05, 0.01, -0.46], [-0.3152, -0.004, -0.1136]]], [[[-0.15240625, 0.69123384, -0.57871905], [0.07776242, 0.33587402, 0.55386645]], [[0.17959584, 0.01269566, 1.22003942], [0.71406514, 0.6187734, -0.43794053]], [[0.67662743, 0.94549789, -0.14946982], [0.88587099, -0.09324637, -0.45012815]]]]) return points, weights, rotations, translations, blended_points
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/rendering/reflectance/blinn_phong.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the Blinn-Phong specular reflectance. For a derivation of the normalization factor ensuring energy conservation, we refer the interested reader to: Fabian Giesen. "Derivation of Phong and Blinn-Phong BRDF normalization factors". 2009 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def _brdf_normalization_factor(shininess): """Returns the normalization factor needed to ensure energy conservation.""" numerator = (shininess + 2.0) * (shininess + 4.0) denominator = 8.0 * math.pi * ( tf.pow(tf.constant(2.0, dtype=shininess.dtype), -shininess / 2.0) + shininess) return safe_ops.safe_signed_div(numerator, denominator) def brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo, brdf_normalization=True, name=None): """Evaluates the specular brdf of the Blinn-Phong model. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Note: The gradient of this function is not smooth when the dot product of the normal with any light is 0.0. Args: direction_incoming_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized incoming light vector. direction_outgoing_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized outgoing light vector. surface_normal: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized surface normal. shininess: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a non-negative shininess coefficient. albedo: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents albedo with values in [0,1]. brdf_normalization: A `bool` indicating whether normalization should be applied to enforce the energy conservation property of BRDFs. Note that `brdf_normalization` must be set to False in order to use the original Blinn-Phong specular model. name: A name for this op. Defaults to "blinn_phong_brdf". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the amount of light reflected in the outgoing light direction. Raises: ValueError: if the shape of `direction_incoming_light`, `direction_outgoing_light`, `surface_normal`, `shininess` or `albedo` is not supported. InvalidArgumentError: if not all of shininess values are non-negative, or if at least one element of `albedo` is outside of [0,1]. """ with tf.compat.v1.name_scope(name, "blinn_phong_brdf", [ direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo ]): direction_incoming_light = tf.convert_to_tensor( value=direction_incoming_light) direction_outgoing_light = tf.convert_to_tensor( value=direction_outgoing_light) surface_normal = tf.convert_to_tensor(value=surface_normal) shininess = tf.convert_to_tensor(value=shininess) albedo = tf.convert_to_tensor(value=albedo) shape.check_static( tensor=direction_incoming_light, tensor_name="direction_incoming_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=direction_outgoing_light, tensor_name="direction_outgoing_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=surface_normal, tensor_name="surface_normal", has_dim_equals=(-1, 3)) shape.check_static( tensor=shininess, tensor_name="shininess", has_dim_equals=(-1, 1)) shape.check_static( tensor=albedo, tensor_name="albedo", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo), tensor_names=("direction_incoming_light", "direction_outgoing_light", "surface_normal", "shininess", "albedo"), last_axes=-2, broadcast_compatible=True) direction_incoming_light = asserts.assert_normalized( direction_incoming_light) direction_outgoing_light = asserts.assert_normalized( direction_outgoing_light) surface_normal = asserts.assert_normalized(surface_normal) albedo = asserts.assert_all_in_range(albedo, 0.0, 1.0, open_bounds=False) shininess = asserts.assert_all_above(shininess, 0.0, open_bound=False) # Checks whether the incoming or outgoing light point behind the surface. dot_incoming_light_surface_normal = vector.dot(-direction_incoming_light, surface_normal) dot_outgoing_light_surface_normal = vector.dot(direction_outgoing_light, surface_normal) min_dot = tf.minimum(dot_incoming_light_surface_normal, dot_outgoing_light_surface_normal) difference_outgoing_incoming = ( direction_outgoing_light - direction_incoming_light) difference_outgoing_incoming = tf.math.l2_normalize( difference_outgoing_incoming, axis=-1) cos_alpha = vector.dot( surface_normal, difference_outgoing_incoming, axis=-1) cos_alpha = tf.maximum(cos_alpha, tf.zeros_like(cos_alpha)) blinn_phong_model = albedo * tf.pow(cos_alpha, shininess) if brdf_normalization: blinn_phong_model *= _brdf_normalization_factor(shininess) common_shape = shape.get_broadcasted_shape(min_dot.shape, blinn_phong_model.shape) d_val = lambda dim: 1 if dim is None else tf.compat.v1.dimension_value(dim) common_shape = [d_val(dim) for dim in common_shape] condition = tf.broadcast_to(tf.greater_equal(min_dot, 0.0), common_shape) blinn_phong_model = tf.broadcast_to(blinn_phong_model, common_shape) return tf.compat.v1.where(condition, blinn_phong_model, tf.zeros_like(blinn_phong_model)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the Blinn-Phong specular reflectance. For a derivation of the normalization factor ensuring energy conservation, we refer the interested reader to: Fabian Giesen. "Derivation of Phong and Blinn-Phong BRDF normalization factors". 2009 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def _brdf_normalization_factor(shininess): """Returns the normalization factor needed to ensure energy conservation.""" numerator = (shininess + 2.0) * (shininess + 4.0) denominator = 8.0 * math.pi * ( tf.pow(tf.constant(2.0, dtype=shininess.dtype), -shininess / 2.0) + shininess) return safe_ops.safe_signed_div(numerator, denominator) def brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo, brdf_normalization=True, name=None): """Evaluates the specular brdf of the Blinn-Phong model. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Note: The gradient of this function is not smooth when the dot product of the normal with any light is 0.0. Args: direction_incoming_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized incoming light vector. direction_outgoing_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized outgoing light vector. surface_normal: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized surface normal. shininess: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a non-negative shininess coefficient. albedo: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents albedo with values in [0,1]. brdf_normalization: A `bool` indicating whether normalization should be applied to enforce the energy conservation property of BRDFs. Note that `brdf_normalization` must be set to False in order to use the original Blinn-Phong specular model. name: A name for this op. Defaults to "blinn_phong_brdf". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the amount of light reflected in the outgoing light direction. Raises: ValueError: if the shape of `direction_incoming_light`, `direction_outgoing_light`, `surface_normal`, `shininess` or `albedo` is not supported. InvalidArgumentError: if not all of shininess values are non-negative, or if at least one element of `albedo` is outside of [0,1]. """ with tf.compat.v1.name_scope(name, "blinn_phong_brdf", [ direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo ]): direction_incoming_light = tf.convert_to_tensor( value=direction_incoming_light) direction_outgoing_light = tf.convert_to_tensor( value=direction_outgoing_light) surface_normal = tf.convert_to_tensor(value=surface_normal) shininess = tf.convert_to_tensor(value=shininess) albedo = tf.convert_to_tensor(value=albedo) shape.check_static( tensor=direction_incoming_light, tensor_name="direction_incoming_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=direction_outgoing_light, tensor_name="direction_outgoing_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=surface_normal, tensor_name="surface_normal", has_dim_equals=(-1, 3)) shape.check_static( tensor=shininess, tensor_name="shininess", has_dim_equals=(-1, 1)) shape.check_static( tensor=albedo, tensor_name="albedo", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo), tensor_names=("direction_incoming_light", "direction_outgoing_light", "surface_normal", "shininess", "albedo"), last_axes=-2, broadcast_compatible=True) direction_incoming_light = asserts.assert_normalized( direction_incoming_light) direction_outgoing_light = asserts.assert_normalized( direction_outgoing_light) surface_normal = asserts.assert_normalized(surface_normal) albedo = asserts.assert_all_in_range(albedo, 0.0, 1.0, open_bounds=False) shininess = asserts.assert_all_above(shininess, 0.0, open_bound=False) # Checks whether the incoming or outgoing light point behind the surface. dot_incoming_light_surface_normal = vector.dot(-direction_incoming_light, surface_normal) dot_outgoing_light_surface_normal = vector.dot(direction_outgoing_light, surface_normal) min_dot = tf.minimum(dot_incoming_light_surface_normal, dot_outgoing_light_surface_normal) difference_outgoing_incoming = ( direction_outgoing_light - direction_incoming_light) difference_outgoing_incoming = tf.math.l2_normalize( difference_outgoing_incoming, axis=-1) cos_alpha = vector.dot( surface_normal, difference_outgoing_incoming, axis=-1) cos_alpha = tf.maximum(cos_alpha, tf.zeros_like(cos_alpha)) blinn_phong_model = albedo * tf.pow(cos_alpha, shininess) if brdf_normalization: blinn_phong_model *= _brdf_normalization_factor(shininess) common_shape = shape.get_broadcasted_shape(min_dot.shape, blinn_phong_model.shape) d_val = lambda dim: 1 if dim is None else tf.compat.v1.dimension_value(dim) common_shape = [d_val(dim) for dim in common_shape] condition = tf.broadcast_to(tf.greater_equal(min_dot, 0.0), common_shape) blinn_phong_model = tf.broadcast_to(blinn_phong_model, common_shape) return tf.compat.v1.where(condition, blinn_phong_model, tf.zeros_like(blinn_phong_model)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/transformation/tests/test_data.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module with test data for transformation tests.""" import numpy as np ANGLE_0 = np.array((0.,)) ANGLE_45 = np.array((np.pi / 4.,)) ANGLE_90 = np.array((np.pi / 2.,)) ANGLE_180 = np.array((np.pi,)) AXIS_2D_0 = np.array((0., 0.)) AXIS_2D_X = np.array((1., 0.)) AXIS_2D_Y = np.array((0., 1.)) def _rotation_2d_x(angle): """Creates a 2d rotation matrix. Args: angle: The angle. Returns: The 2d rotation matrix. """ angle = angle.item() return np.array(((np.cos(angle), -np.sin(angle)), (np.sin(angle), np.cos(angle)))) # pyformat: disable MAT_2D_ID = np.eye(2) MAT_2D_45 = _rotation_2d_x(ANGLE_45) MAT_2D_90 = _rotation_2d_x(ANGLE_90) MAT_2D_180 = _rotation_2d_x(ANGLE_180) AXIS_3D_0 = np.array((0., 0., 0.)) AXIS_3D_X = np.array((1., 0., 0.)) AXIS_3D_Y = np.array((0., 1., 0.)) AXIS_3D_Z = np.array((0., 0., 1.)) def _axis_angle_to_quaternion(axis, angle): """Converts an axis-angle representation to a quaternion. Args: axis: The axis of rotation. angle: The angle. Returns: The quaternion. """ quat = np.zeros(4) quat[0:3] = axis * np.sin(0.5 * angle) quat[3] = np.cos(0.5 * angle) return quat QUAT_ID = _axis_angle_to_quaternion(AXIS_3D_0, ANGLE_0) QUAT_X_45 = _axis_angle_to_quaternion(AXIS_3D_X, ANGLE_45) QUAT_X_90 = _axis_angle_to_quaternion(AXIS_3D_X, ANGLE_90) QUAT_X_180 = _axis_angle_to_quaternion(AXIS_3D_X, ANGLE_180) QUAT_Y_45 = _axis_angle_to_quaternion(AXIS_3D_Y, ANGLE_45) QUAT_Y_90 = _axis_angle_to_quaternion(AXIS_3D_Y, ANGLE_90) QUAT_Y_180 = _axis_angle_to_quaternion(AXIS_3D_Y, ANGLE_180) QUAT_Z_45 = _axis_angle_to_quaternion(AXIS_3D_Z, ANGLE_45) QUAT_Z_90 = _axis_angle_to_quaternion(AXIS_3D_Z, ANGLE_90) QUAT_Z_180 = _axis_angle_to_quaternion(AXIS_3D_Z, ANGLE_180) def _rotation_3d_x(angle): """Creates a 3d rotation matrix around the x axis. Args: angle: The angle. Returns: The 3d rotation matrix. """ angle = angle.item() return np.array(((1., 0., 0.), (0., np.cos(angle), -np.sin(angle)), (0., np.sin(angle), np.cos(angle)))) # pyformat: disable def _rotation_3d_y(angle): """Creates a 3d rotation matrix around the y axis. Args: angle: The angle. Returns: The 3d rotation matrix. """ angle = angle.item() return np.array(((np.cos(angle), 0., np.sin(angle)), (0., 1., 0.), (-np.sin(angle), 0., np.cos(angle)))) # pyformat: disable def _rotation_3d_z(angle): """Creates a 3d rotation matrix around the z axis. Args: angle: The angle. Returns: The 3d rotation matrix. """ angle = angle.item() return np.array(((np.cos(angle), -np.sin(angle), 0.), (np.sin(angle), np.cos(angle), 0.), (0., 0., 1.))) # pyformat: disable MAT_3D_ID = np.eye(3) MAT_3D_X_45 = _rotation_3d_x(ANGLE_45) MAT_3D_X_90 = _rotation_3d_x(ANGLE_90) MAT_3D_X_180 = _rotation_3d_x(ANGLE_180) MAT_3D_Y_45 = _rotation_3d_y(ANGLE_45) MAT_3D_Y_90 = _rotation_3d_y(ANGLE_90) MAT_3D_Y_180 = _rotation_3d_y(ANGLE_180) MAT_3D_Z_45 = _rotation_3d_z(ANGLE_45) MAT_3D_Z_90 = _rotation_3d_z(ANGLE_90) MAT_3D_Z_180 = _rotation_3d_z(ANGLE_180)
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module with test data for transformation tests.""" import numpy as np ANGLE_0 = np.array((0.,)) ANGLE_45 = np.array((np.pi / 4.,)) ANGLE_90 = np.array((np.pi / 2.,)) ANGLE_180 = np.array((np.pi,)) AXIS_2D_0 = np.array((0., 0.)) AXIS_2D_X = np.array((1., 0.)) AXIS_2D_Y = np.array((0., 1.)) def _rotation_2d_x(angle): """Creates a 2d rotation matrix. Args: angle: The angle. Returns: The 2d rotation matrix. """ angle = angle.item() return np.array(((np.cos(angle), -np.sin(angle)), (np.sin(angle), np.cos(angle)))) # pyformat: disable MAT_2D_ID = np.eye(2) MAT_2D_45 = _rotation_2d_x(ANGLE_45) MAT_2D_90 = _rotation_2d_x(ANGLE_90) MAT_2D_180 = _rotation_2d_x(ANGLE_180) AXIS_3D_0 = np.array((0., 0., 0.)) AXIS_3D_X = np.array((1., 0., 0.)) AXIS_3D_Y = np.array((0., 1., 0.)) AXIS_3D_Z = np.array((0., 0., 1.)) def _axis_angle_to_quaternion(axis, angle): """Converts an axis-angle representation to a quaternion. Args: axis: The axis of rotation. angle: The angle. Returns: The quaternion. """ quat = np.zeros(4) quat[0:3] = axis * np.sin(0.5 * angle) quat[3] = np.cos(0.5 * angle) return quat QUAT_ID = _axis_angle_to_quaternion(AXIS_3D_0, ANGLE_0) QUAT_X_45 = _axis_angle_to_quaternion(AXIS_3D_X, ANGLE_45) QUAT_X_90 = _axis_angle_to_quaternion(AXIS_3D_X, ANGLE_90) QUAT_X_180 = _axis_angle_to_quaternion(AXIS_3D_X, ANGLE_180) QUAT_Y_45 = _axis_angle_to_quaternion(AXIS_3D_Y, ANGLE_45) QUAT_Y_90 = _axis_angle_to_quaternion(AXIS_3D_Y, ANGLE_90) QUAT_Y_180 = _axis_angle_to_quaternion(AXIS_3D_Y, ANGLE_180) QUAT_Z_45 = _axis_angle_to_quaternion(AXIS_3D_Z, ANGLE_45) QUAT_Z_90 = _axis_angle_to_quaternion(AXIS_3D_Z, ANGLE_90) QUAT_Z_180 = _axis_angle_to_quaternion(AXIS_3D_Z, ANGLE_180) def _rotation_3d_x(angle): """Creates a 3d rotation matrix around the x axis. Args: angle: The angle. Returns: The 3d rotation matrix. """ angle = angle.item() return np.array(((1., 0., 0.), (0., np.cos(angle), -np.sin(angle)), (0., np.sin(angle), np.cos(angle)))) # pyformat: disable def _rotation_3d_y(angle): """Creates a 3d rotation matrix around the y axis. Args: angle: The angle. Returns: The 3d rotation matrix. """ angle = angle.item() return np.array(((np.cos(angle), 0., np.sin(angle)), (0., 1., 0.), (-np.sin(angle), 0., np.cos(angle)))) # pyformat: disable def _rotation_3d_z(angle): """Creates a 3d rotation matrix around the z axis. Args: angle: The angle. Returns: The 3d rotation matrix. """ angle = angle.item() return np.array(((np.cos(angle), -np.sin(angle), 0.), (np.sin(angle), np.cos(angle), 0.), (0., 0., 1.))) # pyformat: disable MAT_3D_ID = np.eye(3) MAT_3D_X_45 = _rotation_3d_x(ANGLE_45) MAT_3D_X_90 = _rotation_3d_x(ANGLE_90) MAT_3D_X_180 = _rotation_3d_x(ANGLE_180) MAT_3D_Y_45 = _rotation_3d_y(ANGLE_45) MAT_3D_Y_90 = _rotation_3d_y(ANGLE_90) MAT_3D_Y_180 = _rotation_3d_y(ANGLE_180) MAT_3D_Z_45 = _rotation_3d_z(ANGLE_45) MAT_3D_Z_90 = _rotation_3d_z(ANGLE_90) MAT_3D_Z_180 = _rotation_3d_z(ANGLE_180)
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/math/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Math module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=g-import-not-at-top from tensorflow_graphics.util.doc import _import_tfg_docs if _import_tfg_docs(): from tensorflow_graphics.math import interpolation from tensorflow_graphics.math import math_helpers from tensorflow_graphics.math import optimizer from tensorflow_graphics.math import spherical_harmonics from tensorflow_graphics.math import vector from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.math. __all__ = _export_api.get_modules() # pylint: enable=g-import-not-at-top
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Math module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=g-import-not-at-top from tensorflow_graphics.util.doc import _import_tfg_docs if _import_tfg_docs(): from tensorflow_graphics.math import interpolation from tensorflow_graphics.math import math_helpers from tensorflow_graphics.math import optimizer from tensorflow_graphics.math import spherical_harmonics from tensorflow_graphics.math import vector from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.math. __all__ = _export_api.get_modules() # pylint: enable=g-import-not-at-top
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/convolution/graph_convolution.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements various graph convolutions in TensorFlow.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.convolution import utils from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def feature_steered_convolution(data, neighbors, sizes, var_u, var_v, var_c, var_w, var_b, name=None): # pyformat: disable """Implements the Feature Steered graph convolution. FeaStNet: Feature-Steered Graph Convolutions for 3D Shape Analysis Nitika Verma, Edmond Boyer, Jakob Verbeek CVPR 2018 https://arxiv.org/abs/1706.05206 The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. `D`: The number of channels in the output after convolution. `W`: The number of weight matrices used in the convolution. The input variables (`var_u`, `var_v`, `var_c`, `var_w`, `var_b`) correspond to the variables with the same names in the paper cited above. Note: In the following, A1 to An are optional batch dimensions. Args: data: A `float` tensor with shape `[A1, ..., An, V, C]`. neighbors: A `SparseTensor` with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. For a mesh, a common choice for the neighborhood of vertex i would be the vertices in the K-ring of i (including i itself). Each vertex must have at least one neighbor. For a faithful implementation of the FeaStNet convolution, neighbors should be a row-normalized weight matrix corresponding to the graph adjacency matrix with self-edges: `neighbors[A1, ..., An, i, j] > 0` if vertex j is a neighbor of i, and `neighbors[A1, ..., An, i, i] > 0` for all i, and `sum(neighbors, axis=-1)[A1, ..., An, i] == 1.0 for all i`. These requirements are relaxed in this implementation. sizes: An `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding).Note that `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. An example usage of `sizes`: consider an input consisting of three graphs G0, G1, and G2 with V0, V1, and V2 vertices respectively. The padded input would have the following shapes: `data.shape = [3, V, C]` and `neighbors.shape = [3, V, V]`, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]`, `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph Gi. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. var_u: A 2-D tensor with shape `[C, W]`. var_v: A 2-D tensor with shape `[C, W]`. var_c: A 1-D tensor with shape `[W]`. var_w: A 3-D tensor with shape `[W, C, D]`. var_b: A 1-D tensor with shape `[D]`. name: A name for this op. Defaults to `graph_convolution_feature_steered_convolution`. Returns: Tensor with shape `[A1, ..., An, V, D]`. Raises: TypeError: if the input types are invalid. ValueError: if the input dimensions are invalid. """ # pyformat: enable with tf.compat.v1.name_scope( name, "graph_convolution_feature_steered_convolution", [data, neighbors, sizes, var_u, var_v, var_c, var_w, var_b]): data = tf.convert_to_tensor(value=data) neighbors = tf.compat.v1.convert_to_tensor_or_sparse_tensor(value=neighbors) if sizes is not None: sizes = tf.convert_to_tensor(value=sizes) var_u = tf.convert_to_tensor(value=var_u) var_v = tf.convert_to_tensor(value=var_v) var_c = tf.convert_to_tensor(value=var_c) var_w = tf.convert_to_tensor(value=var_w) var_b = tf.convert_to_tensor(value=var_b) data_ndims = data.shape.ndims utils.check_valid_graph_convolution_input(data, neighbors, sizes) shape.compare_dimensions( tensors=(data, var_u, var_v, var_w), tensor_names=("data", "var_u", "var_v", "var_w"), axes=(-1, 0, 0, 1)) shape.compare_dimensions( tensors=(var_u, var_v, var_c, var_w), tensor_names=("var_u", "var_v", "var_c", "var_w"), axes=(1, 1, 0, 0)) shape.compare_dimensions( tensors=(var_w, var_b), tensor_names=("var_w", "var_b"), axes=-1) # Flatten the batch dimensions and remove any vertex padding. if data_ndims > 2: if sizes is not None: sizes_square = tf.stack((sizes, sizes), axis=-1) else: sizes_square = None x_flat, unflatten = utils.flatten_batch_to_2d(data, sizes) adjacency = utils.convert_to_block_diag_2d(neighbors, sizes_square) else: x_flat = data adjacency = neighbors x_u = tf.matmul(x_flat, var_u) x_v = tf.matmul(x_flat, var_v) adjacency_ind_0 = adjacency.indices[:, 0] adjacency_ind_1 = adjacency.indices[:, 1] x_u_rep = tf.gather(x_u, adjacency_ind_0) x_v_sep = tf.gather(x_v, adjacency_ind_1) weights_q = tf.exp(x_u_rep + x_v_sep + tf.reshape(var_c, (1, -1))) weights_q_sum = tf.reduce_sum( input_tensor=weights_q, axis=-1, keepdims=True) weights_q = weights_q / weights_q_sum y_i_m = [] x_sep = tf.gather(x_flat, adjacency_ind_1) q_m_list = tf.unstack(weights_q, axis=-1) w_m_list = tf.unstack(var_w, axis=0) x_flat_shape = tf.shape(input=x_flat) for q_m, w_m in zip(q_m_list, w_m_list): # Compute `y_i_m = sum_{j in neighborhood(i)} q_m(x_i, x_j) * w_m * x_j`. q_m = tf.expand_dims(q_m, axis=-1) p_sum = tf.math.unsorted_segment_sum( data=(q_m * x_sep) * tf.expand_dims(adjacency.values, -1), segment_ids=adjacency_ind_0, num_segments=x_flat_shape[0]) y_i_m.append(tf.matmul(p_sum, w_m)) y_out = tf.add_n(inputs=y_i_m) + tf.reshape(var_b, [1, -1]) if data_ndims > 2: y_out = unflatten(y_out) return y_out def edge_convolution_template(data, neighbors, sizes, edge_function, reduction, edge_function_kwargs, name=None): # pyformat: disable r"""A template for edge convolutions. This function implements a general edge convolution for graphs of the form \\(y_i = \sum_{j \in \mathcal{N}(i)} w_{ij} f(x_i, x_j)\\), where \\(\mathcal{N}(i)\\) is the set of vertices in the neighborhood of vertex \\(i\\), \\(x_i \in \mathbb{R}^C\\) are the features at vertex \\(i\\), \\(w_{ij} \in \mathbb{R}\\) is the weight for the edge between vertex \\(i\\) and vertex \\(j\\), and finally \\(f(x_i, x_j): \mathbb{R}^{C} \times \mathbb{R}^{C} \to \mathbb{R}^{D}\\) is a user-supplied function. This template also implements the same general edge convolution described above with a max-reduction instead of a weighted sum. An example of how this template can be used is for Laplacian smoothing, which is defined as $$y_i = \frac{1}{|\mathcal{N(i)}|} \sum_{j \in \mathcal{N(i)}} x_j$$. `edge_convolution_template` can be used to perform Laplacian smoothing by setting $$w_{ij} = \frac{1}{|\mathcal{N(i)}|}$$, `edge_function=lambda x, y: y`, and `reduction='weighted'`. The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. Note: In the following, A1 to An are optional batch dimensions. Args: data: A `float` tensor with shape `[A1, ..., An, V, C]`. neighbors: A `SparseTensor` with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. The value at `neighbors[A1, ..., An, i, j]` corresponds to the weight \\(w_{ij}\\) above. Each vertex must have at least one neighbor. sizes: An `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). Note that `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. As an example, consider an input consisting of three graphs G0, G1, and G2 with V0, V1, and V2 vertices respectively. The padded input would have the shapes `[3, V, C]`, and `[3, V, V]` for `data` and `neighbors` respectively, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]` and `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph Gi. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. edge_function: A callable that takes at least two arguments of vertex features and returns a tensor of vertex features. `Y = f(X1, X2, **kwargs)`, where `X1` and `X2` have shape `[V3, C]` and `Y` must have shape `[V3, D], D >= 1`. reduction: Either 'weighted' or 'max'. Specifies the reduction over the neighborhood. For 'weighted', the reduction is a weighted sum as shown in the equation above. For 'max' the reduction is a max over features in which case the weights $$w_{ij}$$ are ignored. edge_function_kwargs: A dict containing any additional keyword arguments to be passed to `edge_function`. name: A name for this op. Defaults to `graph_convolution_edge_convolution_template`. Returns: Tensor with shape `[A1, ..., An, V, D]`. Raises: TypeError: if the input types are invalid. ValueError: if the input dimensions are invalid. """ # pyformat: enable with tf.compat.v1.name_scope(name, "graph_convolution_edge_convolution_template", [data, neighbors, sizes]): data = tf.convert_to_tensor(value=data) neighbors = tf.compat.v1.convert_to_tensor_or_sparse_tensor(value=neighbors) if sizes is not None: sizes = tf.convert_to_tensor(value=sizes) data_ndims = data.shape.ndims utils.check_valid_graph_convolution_input(data, neighbors, sizes) # Flatten the batch dimensions and remove any vertex padding. if data_ndims > 2: if sizes is not None: sizes_square = tf.stack((sizes, sizes), axis=-1) else: sizes_square = None x_flat, unflatten = utils.flatten_batch_to_2d(data, sizes) adjacency = utils.convert_to_block_diag_2d(neighbors, sizes_square) else: x_flat = data adjacency = neighbors adjacency_ind_0 = adjacency.indices[:, 0] adjacency_ind_1 = adjacency.indices[:, 1] vertex_features = tf.gather(x_flat, adjacency_ind_0) neighbor_features = tf.gather(x_flat, adjacency_ind_1) edge_features = edge_function(vertex_features, neighbor_features, **edge_function_kwargs) if reduction == "weighted": edge_features_weighted = edge_features * tf.expand_dims( adjacency.values, -1) features = tf.math.unsorted_segment_sum( data=edge_features_weighted, segment_ids=adjacency_ind_0, num_segments=tf.shape(input=x_flat)[0]) elif reduction == "max": features = tf.math.segment_max(data=edge_features, segment_ids=adjacency_ind_0) else: raise ValueError("The reduction method must be 'weighted' or 'max'") features.set_shape(features.shape.merge_with( (tf.compat.v1.dimension_value(x_flat.shape[0]), tf.compat.v1.dimension_value(edge_features.shape[-1])))) if data_ndims > 2: features = unflatten(features) return features # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements various graph convolutions in TensorFlow.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.convolution import utils from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def feature_steered_convolution(data, neighbors, sizes, var_u, var_v, var_c, var_w, var_b, name=None): # pyformat: disable """Implements the Feature Steered graph convolution. FeaStNet: Feature-Steered Graph Convolutions for 3D Shape Analysis Nitika Verma, Edmond Boyer, Jakob Verbeek CVPR 2018 https://arxiv.org/abs/1706.05206 The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. `D`: The number of channels in the output after convolution. `W`: The number of weight matrices used in the convolution. The input variables (`var_u`, `var_v`, `var_c`, `var_w`, `var_b`) correspond to the variables with the same names in the paper cited above. Note: In the following, A1 to An are optional batch dimensions. Args: data: A `float` tensor with shape `[A1, ..., An, V, C]`. neighbors: A `SparseTensor` with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. For a mesh, a common choice for the neighborhood of vertex i would be the vertices in the K-ring of i (including i itself). Each vertex must have at least one neighbor. For a faithful implementation of the FeaStNet convolution, neighbors should be a row-normalized weight matrix corresponding to the graph adjacency matrix with self-edges: `neighbors[A1, ..., An, i, j] > 0` if vertex j is a neighbor of i, and `neighbors[A1, ..., An, i, i] > 0` for all i, and `sum(neighbors, axis=-1)[A1, ..., An, i] == 1.0 for all i`. These requirements are relaxed in this implementation. sizes: An `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding).Note that `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. An example usage of `sizes`: consider an input consisting of three graphs G0, G1, and G2 with V0, V1, and V2 vertices respectively. The padded input would have the following shapes: `data.shape = [3, V, C]` and `neighbors.shape = [3, V, V]`, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]`, `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph Gi. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. var_u: A 2-D tensor with shape `[C, W]`. var_v: A 2-D tensor with shape `[C, W]`. var_c: A 1-D tensor with shape `[W]`. var_w: A 3-D tensor with shape `[W, C, D]`. var_b: A 1-D tensor with shape `[D]`. name: A name for this op. Defaults to `graph_convolution_feature_steered_convolution`. Returns: Tensor with shape `[A1, ..., An, V, D]`. Raises: TypeError: if the input types are invalid. ValueError: if the input dimensions are invalid. """ # pyformat: enable with tf.compat.v1.name_scope( name, "graph_convolution_feature_steered_convolution", [data, neighbors, sizes, var_u, var_v, var_c, var_w, var_b]): data = tf.convert_to_tensor(value=data) neighbors = tf.compat.v1.convert_to_tensor_or_sparse_tensor(value=neighbors) if sizes is not None: sizes = tf.convert_to_tensor(value=sizes) var_u = tf.convert_to_tensor(value=var_u) var_v = tf.convert_to_tensor(value=var_v) var_c = tf.convert_to_tensor(value=var_c) var_w = tf.convert_to_tensor(value=var_w) var_b = tf.convert_to_tensor(value=var_b) data_ndims = data.shape.ndims utils.check_valid_graph_convolution_input(data, neighbors, sizes) shape.compare_dimensions( tensors=(data, var_u, var_v, var_w), tensor_names=("data", "var_u", "var_v", "var_w"), axes=(-1, 0, 0, 1)) shape.compare_dimensions( tensors=(var_u, var_v, var_c, var_w), tensor_names=("var_u", "var_v", "var_c", "var_w"), axes=(1, 1, 0, 0)) shape.compare_dimensions( tensors=(var_w, var_b), tensor_names=("var_w", "var_b"), axes=-1) # Flatten the batch dimensions and remove any vertex padding. if data_ndims > 2: if sizes is not None: sizes_square = tf.stack((sizes, sizes), axis=-1) else: sizes_square = None x_flat, unflatten = utils.flatten_batch_to_2d(data, sizes) adjacency = utils.convert_to_block_diag_2d(neighbors, sizes_square) else: x_flat = data adjacency = neighbors x_u = tf.matmul(x_flat, var_u) x_v = tf.matmul(x_flat, var_v) adjacency_ind_0 = adjacency.indices[:, 0] adjacency_ind_1 = adjacency.indices[:, 1] x_u_rep = tf.gather(x_u, adjacency_ind_0) x_v_sep = tf.gather(x_v, adjacency_ind_1) weights_q = tf.exp(x_u_rep + x_v_sep + tf.reshape(var_c, (1, -1))) weights_q_sum = tf.reduce_sum( input_tensor=weights_q, axis=-1, keepdims=True) weights_q = weights_q / weights_q_sum y_i_m = [] x_sep = tf.gather(x_flat, adjacency_ind_1) q_m_list = tf.unstack(weights_q, axis=-1) w_m_list = tf.unstack(var_w, axis=0) x_flat_shape = tf.shape(input=x_flat) for q_m, w_m in zip(q_m_list, w_m_list): # Compute `y_i_m = sum_{j in neighborhood(i)} q_m(x_i, x_j) * w_m * x_j`. q_m = tf.expand_dims(q_m, axis=-1) p_sum = tf.math.unsorted_segment_sum( data=(q_m * x_sep) * tf.expand_dims(adjacency.values, -1), segment_ids=adjacency_ind_0, num_segments=x_flat_shape[0]) y_i_m.append(tf.matmul(p_sum, w_m)) y_out = tf.add_n(inputs=y_i_m) + tf.reshape(var_b, [1, -1]) if data_ndims > 2: y_out = unflatten(y_out) return y_out def edge_convolution_template(data, neighbors, sizes, edge_function, reduction, edge_function_kwargs, name=None): # pyformat: disable r"""A template for edge convolutions. This function implements a general edge convolution for graphs of the form \\(y_i = \sum_{j \in \mathcal{N}(i)} w_{ij} f(x_i, x_j)\\), where \\(\mathcal{N}(i)\\) is the set of vertices in the neighborhood of vertex \\(i\\), \\(x_i \in \mathbb{R}^C\\) are the features at vertex \\(i\\), \\(w_{ij} \in \mathbb{R}\\) is the weight for the edge between vertex \\(i\\) and vertex \\(j\\), and finally \\(f(x_i, x_j): \mathbb{R}^{C} \times \mathbb{R}^{C} \to \mathbb{R}^{D}\\) is a user-supplied function. This template also implements the same general edge convolution described above with a max-reduction instead of a weighted sum. An example of how this template can be used is for Laplacian smoothing, which is defined as $$y_i = \frac{1}{|\mathcal{N(i)}|} \sum_{j \in \mathcal{N(i)}} x_j$$. `edge_convolution_template` can be used to perform Laplacian smoothing by setting $$w_{ij} = \frac{1}{|\mathcal{N(i)}|}$$, `edge_function=lambda x, y: y`, and `reduction='weighted'`. The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. Note: In the following, A1 to An are optional batch dimensions. Args: data: A `float` tensor with shape `[A1, ..., An, V, C]`. neighbors: A `SparseTensor` with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. The value at `neighbors[A1, ..., An, i, j]` corresponds to the weight \\(w_{ij}\\) above. Each vertex must have at least one neighbor. sizes: An `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). Note that `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. As an example, consider an input consisting of three graphs G0, G1, and G2 with V0, V1, and V2 vertices respectively. The padded input would have the shapes `[3, V, C]`, and `[3, V, V]` for `data` and `neighbors` respectively, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]` and `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph Gi. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. edge_function: A callable that takes at least two arguments of vertex features and returns a tensor of vertex features. `Y = f(X1, X2, **kwargs)`, where `X1` and `X2` have shape `[V3, C]` and `Y` must have shape `[V3, D], D >= 1`. reduction: Either 'weighted' or 'max'. Specifies the reduction over the neighborhood. For 'weighted', the reduction is a weighted sum as shown in the equation above. For 'max' the reduction is a max over features in which case the weights $$w_{ij}$$ are ignored. edge_function_kwargs: A dict containing any additional keyword arguments to be passed to `edge_function`. name: A name for this op. Defaults to `graph_convolution_edge_convolution_template`. Returns: Tensor with shape `[A1, ..., An, V, D]`. Raises: TypeError: if the input types are invalid. ValueError: if the input dimensions are invalid. """ # pyformat: enable with tf.compat.v1.name_scope(name, "graph_convolution_edge_convolution_template", [data, neighbors, sizes]): data = tf.convert_to_tensor(value=data) neighbors = tf.compat.v1.convert_to_tensor_or_sparse_tensor(value=neighbors) if sizes is not None: sizes = tf.convert_to_tensor(value=sizes) data_ndims = data.shape.ndims utils.check_valid_graph_convolution_input(data, neighbors, sizes) # Flatten the batch dimensions and remove any vertex padding. if data_ndims > 2: if sizes is not None: sizes_square = tf.stack((sizes, sizes), axis=-1) else: sizes_square = None x_flat, unflatten = utils.flatten_batch_to_2d(data, sizes) adjacency = utils.convert_to_block_diag_2d(neighbors, sizes_square) else: x_flat = data adjacency = neighbors adjacency_ind_0 = adjacency.indices[:, 0] adjacency_ind_1 = adjacency.indices[:, 1] vertex_features = tf.gather(x_flat, adjacency_ind_0) neighbor_features = tf.gather(x_flat, adjacency_ind_1) edge_features = edge_function(vertex_features, neighbor_features, **edge_function_kwargs) if reduction == "weighted": edge_features_weighted = edge_features * tf.expand_dims( adjacency.values, -1) features = tf.math.unsorted_segment_sum( data=edge_features_weighted, segment_ids=adjacency_ind_0, num_segments=tf.shape(input=x_flat)[0]) elif reduction == "max": features = tf.math.segment_max(data=edge_features, segment_ids=adjacency_ind_0) else: raise ValueError("The reduction method must be 'weighted' or 'max'") features.set_shape(features.shape.merge_with( (tf.compat.v1.dimension_value(x_flat.shape[0]), tf.compat.v1.dimension_value(edge_features.shape[-1])))) if data_ndims > 2: features = unflatten(features) return features # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/rendering/light/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Light module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.rendering.light import point_light from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.rendering.light. __all__ = _export_api.get_modules()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Light module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.rendering.light import point_light from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.rendering.light. __all__ = _export_api.get_modules()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/projects/cvxnet/lib/utils.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from os import path import numpy as np import scipy as sp from skimage import measure import tensorflow.compat.v1 as tf from tensorflow_graphics.projects.cvxnet.lib import datasets from tensorflow_graphics.projects.cvxnet.lib import models from tensorflow_graphics.projects.cvxnet.lib.libmise import mise import trimesh Stats = collections.namedtuple("Stats", ["iou", "chamfer", "fscore"]) SYSNET_CLASSES = { "02691156": "airplane", "02933112": "cabinet", "03001627": "chair", "03636649": "lamp", "04090263": "rifle", "04379243": "table", "04530566": "watercraft", "02828884": "bench", "02958343": "car", "03211117": "display", "03691459": "speaker", "04256520": "sofa", "04401088": "telephone", "all": "all", } def define_flags(): """Define command line flags.""" flags = tf.app.flags # Model flags flags.DEFINE_enum("model", "multiconvex", list(k for k in models.model_dict.keys()), "Name of the model.") flags.DEFINE_float("sharpness", 75., "Sharpness term.") flags.DEFINE_integer("n_parts", 50, "Number of convexes uesd.") flags.DEFINE_integer("n_half_planes", 25, "Number of half spaces used.") flags.DEFINE_integer("latent_size", 256, "The size of latent code.") flags.DEFINE_integer("dims", 3, "The dimension of query points.") flags.DEFINE_bool("image_input", False, "Use color images as input if True.") flags.DEFINE_float("vis_scale", 1.3, "Scale of bbox used when extracting meshes.") flags.DEFINE_float("level_set", 0.5, "Level set used for extracting surfaces.") # Dataset flags flags.DEFINE_enum("dataset", "shapenet", list(k for k in datasets.dataset_dict.keys()), "Name of the dataset.") flags.DEFINE_integer("image_h", 137, "The height of the color images.") flags.DEFINE_integer("image_w", 137, "The width of the color images.") flags.DEFINE_integer("image_d", 3, "The channels of color images.") flags.DEFINE_integer("depth_h", 224, "The height of depth images.") flags.DEFINE_integer("depth_w", 224, "The width of depth images.") flags.DEFINE_integer("depth_d", 20, "The number of depth views.") flags.DEFINE_integer("n_views", 24, "The number of color images views.") flags.DEFINE_string("data_dir", None, "The base directory to load data from.") flags.mark_flag_as_required("data_dir") flags.DEFINE_string("obj_class", "*", "Object class used from dataset.") # Training flags flags.DEFINE_float("lr", 1e-4, "Start learning rate.") flags.DEFINE_string( "train_dir", None, "The base directory to save training info and" "checkpoints.") flags.DEFINE_integer("save_every", 20000, "The number of steps to save checkpoint.") flags.DEFINE_integer("max_steps", 800000, "The number of steps of training.") flags.DEFINE_integer("batch_size", 32, "Batch size.") flags.DEFINE_integer("sample_bbx", 1024, "The number of bounding box sample points.") flags.DEFINE_integer("sample_surf", 1024, "The number of surface sample points.") flags.DEFINE_float("weight_overlap", 0.1, "Weight of overlap_loss") flags.DEFINE_float("weight_balance", 0.01, "Weight of balance_loss") flags.DEFINE_float("weight_center", 0.001, "Weight of center_loss") flags.mark_flag_as_required("train_dir") # Eval flags flags.DEFINE_bool("extract_mesh", False, "Extract meshes and set to disk if True.") flags.DEFINE_bool("surface_metrics", False, "Measure surface metrics and save to csv if True.") flags.DEFINE_string("mesh_dir", None, "Path to load ground truth meshes.") flags.DEFINE_string("trans_dir", None, "Path to load pred-to-target transformations.") flags.DEFINE_bool("eval_once", False, "Evaluate the model only once if True.") def mesh_name_helper(name): name = name[0].decode("utf-8") split = name.find("-") cls_name = name[:split] obj_name = name[split + 1:] return cls_name, obj_name def extract_mesh(input_val, params, indicators, input_holder, params_holder, points_holder, sess, args): """Extracting meshes from an indicator function. Args: input_val: np.array, [1, height, width, channel], input image. params: tf.Operation, hyperplane parameter hook. indicators: tf.Operation, indicator hook. input_holder: tf.Placeholder, input image placeholder. params_holder: tf.Placeholder, hyperplane parameter placeholder. points_holder: tf.Placeholder, query point placeholder. sess: tf.Session, running sess. args: tf.app.flags.FLAGS, configurations. Returns: mesh: trimesh.Trimesh, the extracted mesh. """ mesh_extractor = mise.MISE(64, 1, args.level_set) points = mesh_extractor.query() params_val = sess.run(params, {input_holder: input_val}) while points.shape[0] != 0: orig_points = points points = points.astype(np.float32) points = ( (np.expand_dims(points, axis=0) / mesh_extractor.resolution - 0.5) * args.vis_scale) n_points = points.shape[1] values = [] for i in range(0, n_points, 100000): # Add this to prevent OOM. value = sess.run(indicators, { params_holder: params_val, points_holder: points[:, i:i + 100000] }) values.append(value) values = np.concatenate(values, axis=1) values = values[0, :, 0].astype(np.float64) mesh_extractor.update(orig_points, values) points = mesh_extractor.query() value_grid = mesh_extractor.to_dense() value_grid = np.pad(value_grid, 1, "constant", constant_values=-1e6) verts, faces, normals, unused_var = measure.marching_cubes_lewiner( value_grid, min(args.level_set, value_grid.max() * 0.75)) del normals verts -= 1 verts /= np.array([ value_grid.shape[0] - 3, value_grid.shape[1] - 3, value_grid.shape[2] - 3 ], dtype=np.float32) verts = args.vis_scale * (verts - 0.5) faces = np.stack([faces[..., 1], faces[..., 0], faces[..., 2]], axis=-1) return trimesh.Trimesh(vertices=verts, faces=faces) def transform_mesh(mesh, name, trans_dir): """Transform mesh back to the same coordinate of ground truth. Args: mesh: trimesh.Trimesh, predicted mesh before transformation. name: Tensor, hash name of the mesh as recorded in the dataset. trans_dir: string, path to the directory for loading transformations. Returns: mesh: trimesh.Trimesh, the transformed mesh. """ if trans_dir is None: raise ValueError("Need to specify args.trans_dir for loading pred-to-target" "transformations.") cls_name, obj_name = mesh_name_helper(name) with tf.io.gfile.GFile( path.join(trans_dir, "test", cls_name, obj_name, "occnet_to_gaps.txt"), "r") as fin: tx = np.loadtxt(fin).reshape([4, 4]) mesh.apply_transform(np.linalg.inv(tx)) return mesh def save_mesh(mesh, name, eval_dir): """Save a mesh to disk. Args: mesh: trimesh.Trimesh, the mesh to save. name: Tensor, hash name of the mesh as recorded in the dataset. eval_dir: string, path to the directory to save the mesh. """ cls_name, obj_name = mesh_name_helper(name) cls_dir = path.join(eval_dir, "meshes", cls_name) if not tf.io.gfile.isdir(cls_dir): tf.io.gfile.makedirs(cls_dir) with tf.io.gfile.GFile(path.join(cls_dir, obj_name + ".obj"), "w") as fout: mesh.export(fout, file_type="obj") def distance_field_helper(source, target): target_kdtree = sp.spatial.cKDTree(target) distances, unused_var = target_kdtree.query(source, n_jobs=-1) return distances def compute_surface_metrics(mesh, name, mesh_dir): """Compute surface metrics (chamfer distance and f-score) for one example. Args: mesh: trimesh.Trimesh, the mesh to evaluate. name: Tensor, hash name of the mesh as recorded in the dataset. mesh_dir: string, path to the directory for loading ground truth meshes. Returns: chamfer: float, chamfer distance. fscore: float, f-score. """ if mesh_dir is None: raise ValueError("Need to specify args.mesh_dir for loading ground truth.") cls_name, obj_name = mesh_name_helper(name) with tf.io.gfile.GFile( path.join(mesh_dir, "test", cls_name, obj_name, "model_occnet.ply"), "rb", ) as fin: mesh_gt = trimesh.Trimesh(**trimesh.exchange.ply.load_ply(fin)) # Chamfer eval_points = 100000 point_gt = mesh_gt.sample(eval_points) point_gt = point_gt.astype(np.float32) point_pred = mesh.sample(eval_points) point_pred = point_pred.astype(np.float32) pred_to_gt = distance_field_helper(point_pred, point_gt) gt_to_pred = distance_field_helper(point_gt, point_pred) chamfer = np.mean(pred_to_gt**2) + np.mean(gt_to_pred**2) # Fscore tau = 1e-4 eps = 1e-9 pred_to_gt = (pred_to_gt**2) gt_to_pred = (gt_to_pred**2) prec_tau = (pred_to_gt <= tau).astype(np.float32).mean() * 100. recall_tau = (gt_to_pred <= tau).astype(np.float32).mean() * 100. fscore = (2 * prec_tau * recall_tau) / max(prec_tau + recall_tau, eps) # Following the tradition to scale chamfer distance up by 10. return chamfer * 100., fscore def init_stats(): """Initialize evaluation stats.""" stats = {} for k in SYSNET_CLASSES: stats[k] = { "cnt": 0, "iou": 0., "chamfer": 0., "fscore": 0., } return stats def update_stats(example_stats, name, shapenet_stats): """Update evaluation statistics. Args: example_stats: Stats, the stats of one example. name: Tensor, hash name of the example as recorded in the dataset. shapenet_stats: dict, the current stats of the whole dataset. """ cls_name, unused_var = mesh_name_helper(name) shapenet_stats[cls_name]["cnt"] += 1 shapenet_stats[cls_name]["iou"] += example_stats.iou shapenet_stats[cls_name]["chamfer"] += example_stats.chamfer shapenet_stats[cls_name]["fscore"] += example_stats.fscore shapenet_stats["all"]["cnt"] += 1 shapenet_stats["all"]["iou"] += example_stats.iou shapenet_stats["all"]["chamfer"] += example_stats.chamfer shapenet_stats["all"]["fscore"] += example_stats.fscore def average_stats(shapenet_stats): """Average the accumulated stats of the whole dataset.""" for k, v in shapenet_stats.items(): cnt = max(v["cnt"], 1) shapenet_stats[k] = { "iou": v["iou"] / cnt, "chamfer": v["chamfer"] / cnt, "fscore": v["fscore"] / cnt, } def write_stats(stats, eval_dir, step): """Write stats of the dataset to disk. Args: stats: dict, statistics to save. eval_dir: string, path to the directory to save the statistics. step: int, the global step of the checkpoint. """ if not tf.io.gfile.isdir(eval_dir): tf.io.gfile.makedirs(eval_dir) with tf.io.gfile.GFile(path.join(eval_dir, "stats_{}.csv".format(step)), "w") as fout: fout.write("class,iou,chamfer,fscore\n") for k in sorted(stats.keys()): if k == "all": continue fout.write("{0},{1},{2},{3}\n".format( SYSNET_CLASSES[k], stats[k]["iou"], stats[k]["chamfer"], stats[k]["fscore"], )) fout.write("all,{0},{1},{2}".format( stats["all"]["iou"], stats["all"]["chamfer"], stats["all"]["fscore"], ))
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from os import path import numpy as np import scipy as sp from skimage import measure import tensorflow.compat.v1 as tf from tensorflow_graphics.projects.cvxnet.lib import datasets from tensorflow_graphics.projects.cvxnet.lib import models from tensorflow_graphics.projects.cvxnet.lib.libmise import mise import trimesh Stats = collections.namedtuple("Stats", ["iou", "chamfer", "fscore"]) SYSNET_CLASSES = { "02691156": "airplane", "02933112": "cabinet", "03001627": "chair", "03636649": "lamp", "04090263": "rifle", "04379243": "table", "04530566": "watercraft", "02828884": "bench", "02958343": "car", "03211117": "display", "03691459": "speaker", "04256520": "sofa", "04401088": "telephone", "all": "all", } def define_flags(): """Define command line flags.""" flags = tf.app.flags # Model flags flags.DEFINE_enum("model", "multiconvex", list(k for k in models.model_dict.keys()), "Name of the model.") flags.DEFINE_float("sharpness", 75., "Sharpness term.") flags.DEFINE_integer("n_parts", 50, "Number of convexes uesd.") flags.DEFINE_integer("n_half_planes", 25, "Number of half spaces used.") flags.DEFINE_integer("latent_size", 256, "The size of latent code.") flags.DEFINE_integer("dims", 3, "The dimension of query points.") flags.DEFINE_bool("image_input", False, "Use color images as input if True.") flags.DEFINE_float("vis_scale", 1.3, "Scale of bbox used when extracting meshes.") flags.DEFINE_float("level_set", 0.5, "Level set used for extracting surfaces.") # Dataset flags flags.DEFINE_enum("dataset", "shapenet", list(k for k in datasets.dataset_dict.keys()), "Name of the dataset.") flags.DEFINE_integer("image_h", 137, "The height of the color images.") flags.DEFINE_integer("image_w", 137, "The width of the color images.") flags.DEFINE_integer("image_d", 3, "The channels of color images.") flags.DEFINE_integer("depth_h", 224, "The height of depth images.") flags.DEFINE_integer("depth_w", 224, "The width of depth images.") flags.DEFINE_integer("depth_d", 20, "The number of depth views.") flags.DEFINE_integer("n_views", 24, "The number of color images views.") flags.DEFINE_string("data_dir", None, "The base directory to load data from.") flags.mark_flag_as_required("data_dir") flags.DEFINE_string("obj_class", "*", "Object class used from dataset.") # Training flags flags.DEFINE_float("lr", 1e-4, "Start learning rate.") flags.DEFINE_string( "train_dir", None, "The base directory to save training info and" "checkpoints.") flags.DEFINE_integer("save_every", 20000, "The number of steps to save checkpoint.") flags.DEFINE_integer("max_steps", 800000, "The number of steps of training.") flags.DEFINE_integer("batch_size", 32, "Batch size.") flags.DEFINE_integer("sample_bbx", 1024, "The number of bounding box sample points.") flags.DEFINE_integer("sample_surf", 1024, "The number of surface sample points.") flags.DEFINE_float("weight_overlap", 0.1, "Weight of overlap_loss") flags.DEFINE_float("weight_balance", 0.01, "Weight of balance_loss") flags.DEFINE_float("weight_center", 0.001, "Weight of center_loss") flags.mark_flag_as_required("train_dir") # Eval flags flags.DEFINE_bool("extract_mesh", False, "Extract meshes and set to disk if True.") flags.DEFINE_bool("surface_metrics", False, "Measure surface metrics and save to csv if True.") flags.DEFINE_string("mesh_dir", None, "Path to load ground truth meshes.") flags.DEFINE_string("trans_dir", None, "Path to load pred-to-target transformations.") flags.DEFINE_bool("eval_once", False, "Evaluate the model only once if True.") def mesh_name_helper(name): name = name[0].decode("utf-8") split = name.find("-") cls_name = name[:split] obj_name = name[split + 1:] return cls_name, obj_name def extract_mesh(input_val, params, indicators, input_holder, params_holder, points_holder, sess, args): """Extracting meshes from an indicator function. Args: input_val: np.array, [1, height, width, channel], input image. params: tf.Operation, hyperplane parameter hook. indicators: tf.Operation, indicator hook. input_holder: tf.Placeholder, input image placeholder. params_holder: tf.Placeholder, hyperplane parameter placeholder. points_holder: tf.Placeholder, query point placeholder. sess: tf.Session, running sess. args: tf.app.flags.FLAGS, configurations. Returns: mesh: trimesh.Trimesh, the extracted mesh. """ mesh_extractor = mise.MISE(64, 1, args.level_set) points = mesh_extractor.query() params_val = sess.run(params, {input_holder: input_val}) while points.shape[0] != 0: orig_points = points points = points.astype(np.float32) points = ( (np.expand_dims(points, axis=0) / mesh_extractor.resolution - 0.5) * args.vis_scale) n_points = points.shape[1] values = [] for i in range(0, n_points, 100000): # Add this to prevent OOM. value = sess.run(indicators, { params_holder: params_val, points_holder: points[:, i:i + 100000] }) values.append(value) values = np.concatenate(values, axis=1) values = values[0, :, 0].astype(np.float64) mesh_extractor.update(orig_points, values) points = mesh_extractor.query() value_grid = mesh_extractor.to_dense() value_grid = np.pad(value_grid, 1, "constant", constant_values=-1e6) verts, faces, normals, unused_var = measure.marching_cubes_lewiner( value_grid, min(args.level_set, value_grid.max() * 0.75)) del normals verts -= 1 verts /= np.array([ value_grid.shape[0] - 3, value_grid.shape[1] - 3, value_grid.shape[2] - 3 ], dtype=np.float32) verts = args.vis_scale * (verts - 0.5) faces = np.stack([faces[..., 1], faces[..., 0], faces[..., 2]], axis=-1) return trimesh.Trimesh(vertices=verts, faces=faces) def transform_mesh(mesh, name, trans_dir): """Transform mesh back to the same coordinate of ground truth. Args: mesh: trimesh.Trimesh, predicted mesh before transformation. name: Tensor, hash name of the mesh as recorded in the dataset. trans_dir: string, path to the directory for loading transformations. Returns: mesh: trimesh.Trimesh, the transformed mesh. """ if trans_dir is None: raise ValueError("Need to specify args.trans_dir for loading pred-to-target" "transformations.") cls_name, obj_name = mesh_name_helper(name) with tf.io.gfile.GFile( path.join(trans_dir, "test", cls_name, obj_name, "occnet_to_gaps.txt"), "r") as fin: tx = np.loadtxt(fin).reshape([4, 4]) mesh.apply_transform(np.linalg.inv(tx)) return mesh def save_mesh(mesh, name, eval_dir): """Save a mesh to disk. Args: mesh: trimesh.Trimesh, the mesh to save. name: Tensor, hash name of the mesh as recorded in the dataset. eval_dir: string, path to the directory to save the mesh. """ cls_name, obj_name = mesh_name_helper(name) cls_dir = path.join(eval_dir, "meshes", cls_name) if not tf.io.gfile.isdir(cls_dir): tf.io.gfile.makedirs(cls_dir) with tf.io.gfile.GFile(path.join(cls_dir, obj_name + ".obj"), "w") as fout: mesh.export(fout, file_type="obj") def distance_field_helper(source, target): target_kdtree = sp.spatial.cKDTree(target) distances, unused_var = target_kdtree.query(source, n_jobs=-1) return distances def compute_surface_metrics(mesh, name, mesh_dir): """Compute surface metrics (chamfer distance and f-score) for one example. Args: mesh: trimesh.Trimesh, the mesh to evaluate. name: Tensor, hash name of the mesh as recorded in the dataset. mesh_dir: string, path to the directory for loading ground truth meshes. Returns: chamfer: float, chamfer distance. fscore: float, f-score. """ if mesh_dir is None: raise ValueError("Need to specify args.mesh_dir for loading ground truth.") cls_name, obj_name = mesh_name_helper(name) with tf.io.gfile.GFile( path.join(mesh_dir, "test", cls_name, obj_name, "model_occnet.ply"), "rb", ) as fin: mesh_gt = trimesh.Trimesh(**trimesh.exchange.ply.load_ply(fin)) # Chamfer eval_points = 100000 point_gt = mesh_gt.sample(eval_points) point_gt = point_gt.astype(np.float32) point_pred = mesh.sample(eval_points) point_pred = point_pred.astype(np.float32) pred_to_gt = distance_field_helper(point_pred, point_gt) gt_to_pred = distance_field_helper(point_gt, point_pred) chamfer = np.mean(pred_to_gt**2) + np.mean(gt_to_pred**2) # Fscore tau = 1e-4 eps = 1e-9 pred_to_gt = (pred_to_gt**2) gt_to_pred = (gt_to_pred**2) prec_tau = (pred_to_gt <= tau).astype(np.float32).mean() * 100. recall_tau = (gt_to_pred <= tau).astype(np.float32).mean() * 100. fscore = (2 * prec_tau * recall_tau) / max(prec_tau + recall_tau, eps) # Following the tradition to scale chamfer distance up by 10. return chamfer * 100., fscore def init_stats(): """Initialize evaluation stats.""" stats = {} for k in SYSNET_CLASSES: stats[k] = { "cnt": 0, "iou": 0., "chamfer": 0., "fscore": 0., } return stats def update_stats(example_stats, name, shapenet_stats): """Update evaluation statistics. Args: example_stats: Stats, the stats of one example. name: Tensor, hash name of the example as recorded in the dataset. shapenet_stats: dict, the current stats of the whole dataset. """ cls_name, unused_var = mesh_name_helper(name) shapenet_stats[cls_name]["cnt"] += 1 shapenet_stats[cls_name]["iou"] += example_stats.iou shapenet_stats[cls_name]["chamfer"] += example_stats.chamfer shapenet_stats[cls_name]["fscore"] += example_stats.fscore shapenet_stats["all"]["cnt"] += 1 shapenet_stats["all"]["iou"] += example_stats.iou shapenet_stats["all"]["chamfer"] += example_stats.chamfer shapenet_stats["all"]["fscore"] += example_stats.fscore def average_stats(shapenet_stats): """Average the accumulated stats of the whole dataset.""" for k, v in shapenet_stats.items(): cnt = max(v["cnt"], 1) shapenet_stats[k] = { "iou": v["iou"] / cnt, "chamfer": v["chamfer"] / cnt, "fscore": v["fscore"] / cnt, } def write_stats(stats, eval_dir, step): """Write stats of the dataset to disk. Args: stats: dict, statistics to save. eval_dir: string, path to the directory to save the statistics. step: int, the global step of the checkpoint. """ if not tf.io.gfile.isdir(eval_dir): tf.io.gfile.makedirs(eval_dir) with tf.io.gfile.GFile(path.join(eval_dir, "stats_{}.csv".format(step)), "w") as fout: fout.write("class,iou,chamfer,fscore\n") for k in sorted(stats.keys()): if k == "all": continue fout.write("{0},{1},{2},{3}\n".format( SYSNET_CLASSES[k], stats[k]["iou"], stats[k]["chamfer"], stats[k]["fscore"], )) fout.write("all,{0},{1},{2}".format( stats["all"]["iou"], stats["all"]["chamfer"], stats["all"]["fscore"], ))
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/convolution/tests/utils_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for convolution utility functions.""" from absl.testing import parameterized import numpy as np from scipy import linalg import tensorflow as tf from tensorflow_graphics.geometry.convolution import utils from tensorflow_graphics.util import test_case def _dense_to_sparse(data): """Converts a numpy array to a tf.SparseTensor.""" indices = np.where(data) return tf.SparseTensor( np.stack(indices, axis=-1), data[indices], dense_shape=data.shape) class UtilsCheckValidGraphConvolutionInputTests(test_case.TestCase): def _create_default_tensors_from_shapes(self, shapes): """Creates `data`, `sparse`, `sizes` tensors from shapes list.""" data = tf.convert_to_tensor( value=np.random.uniform(size=shapes[0]).astype(np.float32)) sparse = _dense_to_sparse(np.ones(shape=shapes[1], dtype=np.float32)) if shapes[2] is not None: sizes = tf.convert_to_tensor( value=np.ones(shape=shapes[2], dtype=np.int32)) else: sizes = None return data, sparse, sizes @parameterized.parameters( ("'sizes' must have an integer type.", np.float32, np.float32, np.float32), ("'data' must have a float type.", np.int32, np.float32, np.int32), ("'neighbors' and 'data' must have the same type.", np.float32, np.float64, np.int32), ) def test_check_valid_graph_convolution_input_exception_raised_types( self, err_msg, data_type, neighbors_type, sizes_type): """Check the type errors for invalid input types.""" data = tf.convert_to_tensor( value=np.random.uniform(size=(2, 2, 2)).astype(data_type)) neighbors = _dense_to_sparse(np.ones(shape=(2, 2, 2), dtype=neighbors_type)) sizes = tf.convert_to_tensor(value=np.array((2, 2), dtype=sizes_type)) with self.assertRaisesRegexp(TypeError, err_msg): utils.check_valid_graph_convolution_input(data, neighbors, sizes) @parameterized.parameters( (np.float32, np.float32, np.int32), (np.float64, np.float64, np.int32), (np.float32, np.float32, np.int64), (np.float64, np.float64, np.int64), ) def test_check_valid_graph_convolution_input_exception_not_raised_types( self, data_type, neighbors_type, sizes_type): """Check that no exceptions are raised for valid input types.""" data = tf.convert_to_tensor( value=np.random.uniform(size=(2, 2, 2)).astype(data_type)) neighbors = _dense_to_sparse(np.ones(shape=(2, 2, 2), dtype=neighbors_type)) sizes = tf.convert_to_tensor(value=np.array((2, 2), dtype=sizes_type)) self.assert_exception_is_not_raised( utils.check_valid_graph_convolution_input, shapes=[], data=data, neighbors=neighbors, sizes=sizes) @parameterized.parameters( ((2, 3), (2, 2), None), ((1, 2, 3), (1, 2, 2), None), ((2, 2, 3), (2, 2, 2), None), ((1, 2, 3), (1, 2, 2), (1,)), ((2, 2, 3), (2, 2, 2), (2,)), ((1, 2, 2, 3), (1, 2, 2, 2), (1, 2)), ((2, 2, 2, 3), (2, 2, 2, 2), (2, 2)), ) def test_check_valid_graph_convolution_input_exception_not_raised_shapes( self, *shapes): """Check that valid input shapes do not trigger any exceptions.""" data, neighbors, sizes = self._create_default_tensors_from_shapes(shapes) self.assert_exception_is_not_raised( utils.check_valid_graph_convolution_input, shapes=[], data=data, neighbors=neighbors, sizes=sizes) @parameterized.parameters( ((None, 3), (None, 2), None), ((1, None, 3), (1, None, None), None), ((None, 2, 3), (None, 2, 2), (1,)), ((None, None, 3), (None, None, None), (2,)), ((1, None, 2, 3), (1, None, None, None), (1, 2)), ) def test_check_valid_graph_convolution_input_exception_not_raised_dynshapes( self, *shapes): """Check that valid dynamic input shapes do not trigger any exceptions.""" dtypes = [tf.float32, tf.float32] sparse_tensors = [False, True] if shapes[2] is not None: dtypes.append(tf.int32) sparse_tensors.append(False) self.assert_exception_is_not_raised( utils.check_valid_graph_convolution_input, shapes=shapes, dtypes=dtypes, sparse_tensors=sparse_tensors) else: self.assert_exception_is_not_raised( utils.check_valid_graph_convolution_input, shapes=shapes, dtypes=dtypes, sparse_tensors=sparse_tensors, sizes=None) def test_check_valid_graph_convolution_dynamic_input_sparse_exception_raised( self): """Check that passing dense `neighbors` tensor raises exception.""" error_msg = "must be a SparseTensor" dtypes = [tf.float32, tf.float32, tf.int32] sparse_tensors = [False, False, False] shapes = ((None, 3), (None, 2), (None,)) self.assert_exception_is_raised( utils.check_valid_graph_convolution_input, error_msg, shapes=shapes, dtypes=dtypes, sparse_tensors=sparse_tensors) @parameterized.parameters( ("must have a rank of 2", (5, 2), (1, 5, 2), None), ("must have a rank greater than 1", (5,), (5, 5), None), ("must have a rank of 2", (5, 2), (5,), None), ("must have a rank of 3", (5, 5, 2), (5, 5), None), ("must have the same number of dimensions in axes", (3, 2), (3, 2), None), ("must have a rank of 1", (5, 5, 2), (5, 5, 5), (5, 5)), ("Not all batch dimensions are identical.", (1, 5, 2), (1, 5, 5), (2,)), ) def test_check_valid_graph_convolution_input_exception_raised_shapes( self, error_msg, *shapes): """Check that invalid input shapes trigger the right exceptions.""" data, neighbors, sizes = self._create_default_tensors_from_shapes(shapes) self.assert_exception_is_raised( utils.check_valid_graph_convolution_input, error_msg, shapes=[], data=data, neighbors=neighbors, sizes=sizes) class UtilsCheckValidGraphPoolingInputTests(test_case.TestCase): @parameterized.parameters( ("'sizes' must have an integer type.", np.float32, np.float32, np.float32), ("'data' must have a float type.", np.int32, np.float32, np.int32), ("'pool_map' and 'data' must have the same type.", np.float32, np.float64, np.int32), ) def test_check_valid_graph_pooling_exception_raised_types( self, err_msg, data_type, pool_map_type, sizes_type): """Check the type errors for invalid input types.""" data = tf.convert_to_tensor(value=np.ones((2, 3, 3), dtype=data_type)) pool_map = _dense_to_sparse(np.ones((2, 3, 3), dtype=pool_map_type)) sizes = tf.convert_to_tensor( value=np.array(((1, 2), (2, 3)), dtype=sizes_type)) with self.assertRaisesRegexp(TypeError, err_msg): utils.check_valid_graph_pooling_input(data, pool_map, sizes) @parameterized.parameters( (np.float32, np.float32, np.int32), (np.float64, np.float64, np.int32), (np.float32, np.float32, np.int64), (np.float64, np.float64, np.int64), ) def test_check_valid_graph_pooling_exception_not_raised_types( self, data_type, pool_map_type, sizes_type): """Check there are no exceptions for valid input types.""" data = tf.convert_to_tensor(value=np.ones((2, 3, 3), dtype=data_type)) pool_map = _dense_to_sparse(np.ones((2, 3, 3), dtype=pool_map_type)) sizes = tf.convert_to_tensor( value=np.array(((1, 2), (2, 3)), dtype=sizes_type)) self.assert_exception_is_not_raised( utils.check_valid_graph_pooling_input, shapes=[], data=data, pool_map=pool_map, sizes=sizes) @parameterized.parameters( ((2, 3), (4, 2), None), ((1, 2, 3), (1, 5, 2), None), ((2, 2, 3), (2, 5, 2), ((3, 2), (2, 5))), ) def test_check_valid_graph_pooling_exception_not_raised_shapes( self, data_shape, pool_map_shape, sizes): """Check that valid input shapes do not trigger any exceptions.""" data = tf.convert_to_tensor(value=np.ones(data_shape, dtype=np.float32)) pool_map = _dense_to_sparse(np.ones(pool_map_shape, dtype=np.float32)) sizes = sizes if sizes is None else tf.convert_to_tensor(value=sizes) self.assert_exception_is_not_raised( utils.check_valid_graph_pooling_input, shapes=[], data=data, pool_map=pool_map, sizes=sizes) @parameterized.parameters( ((None, 3), (None, 2), None), ((1, None, 3), (1, None, None), None), ((None, 2, 3), (None, 5, 2), (2, 2)), ) def test_check_valid_graph_pooling_exception_not_raised_dynamic_shapes( self, *shapes): """Check that valid dynamic input shapes do not trigger any exceptions.""" dtypes = [tf.float32, tf.float32] sparse_tensors = [False, True] if shapes[2] is not None: dtypes.append(tf.int32) sparse_tensors.append(False) self.assert_exception_is_not_raised( utils.check_valid_graph_pooling_input, shapes=shapes, dtypes=dtypes, sparse_tensors=sparse_tensors) else: self.assert_exception_is_not_raised( utils.check_valid_graph_pooling_input, shapes=shapes, dtypes=dtypes, sparse_tensors=sparse_tensors, sizes=None) def test_check_graph_pooling_input_sparse_exception_raised(self): """Check that passing dense `neighbors` tensor raises exception.""" error_msg = "must be a SparseTensor" dtypes = [tf.float32, tf.float32, tf.int32] sparse_tensors = [False, False, False] shapes = ((2, 2, 3), (2, 5, 2), (2, 2)) self.assert_exception_is_raised( utils.check_valid_graph_convolution_input, error_msg, shapes=shapes, dtypes=dtypes, sparse_tensors=sparse_tensors) @parameterized.parameters( ("must have a rank greater than 1", (5,), (5, 5), None), ("must have a rank of 2", (5, 2), (5,), None), ("must have the same number of dimensions in axes", (3, 2), (3, 2), None), ("Not all batch dimensions are identical.", (3, 5, 2), (1, 5, 5), None), ("must have a rank of 2", (2, 5, 2), (2, 3, 5), (3, 5)), ("Not all batch dimensions are identical.", (3, 5, 2), (3, 3, 5), ((3, 5), (2, 4))), ) def test_check_valid_graph_pooling_exception_raised_shapes( self, err_msg, data_shape, pool_map_shape, sizes): """Check that invalid input shapes trigger the right exceptions.""" data = tf.convert_to_tensor(value=np.ones(data_shape, dtype=np.float32)) pool_map = _dense_to_sparse(np.ones(pool_map_shape, dtype=np.float32)) sizes = sizes if sizes is None else tf.convert_to_tensor(value=sizes) self.assert_exception_is_raised( utils.check_valid_graph_pooling_input, err_msg, shapes=[], data=data, pool_map=pool_map, sizes=sizes) class UtilsFlattenBatchTo2dTests(test_case.TestCase): @parameterized.parameters(((5, 3),), ((3,),)) def test_input_rank_exception_raised(self, *shapes): """Check that invalid input data rank triggers the right exceptions.""" self.assert_exception_is_raised(utils.flatten_batch_to_2d, "must have a rank greater than 2", shapes) def test_flatten_batch_to_2d_exception_raised_types(self): """Check the exception when input is not an integer.""" with self.assertRaisesRegexp(TypeError, "'sizes' must have an integer type."): utils.flatten_batch_to_2d(np.ones((3, 4, 3)), np.ones((3,))) @parameterized.parameters( ((None, 3, 3), None), ((3, None, 3), (3,)), ) def test_check_flatten_batch_to_2d_exception_not_raised_dynamic_shapes( self, *shapes): """Check that valid dynamic input shapes do not trigger any exceptions.""" dtypes = [tf.float32] if shapes[1] is not None: dtypes.append(tf.int32) self.assert_exception_is_not_raised( utils.flatten_batch_to_2d, shapes=shapes, dtypes=dtypes) else: self.assert_exception_is_not_raised( utils.flatten_batch_to_2d, shapes=shapes, dtypes=dtypes, sizes=None) @parameterized.parameters( ("must have a rank of 1", (3, 4, 3), (3, 4)), ("must have a rank of 1", (3, 4, 5), (3, 4, 5)), ) def test_flatten_batch_to_2d_exception_raised(self, error_msg, *shapes): """Check the exception when the shape of 'sizes' is invalid.""" self.assert_exception_is_raised( utils.flatten_batch_to_2d, error_msg, shapes, dtypes=(tf.float32, tf.int32)) def test_flatten_batch_to_2d_random(self): """Test flattening with random inputs.""" ndims_batch = np.random.randint(low=1, high=5) batch_dims = np.random.randint(low=1, high=10, size=ndims_batch) data_dims = np.random.randint(low=1, high=20, size=2) dims = np.concatenate([batch_dims, data_dims], axis=0) data = np.random.uniform(size=dims) with self.subTest(name="random_padding"): sizes = np.random.randint(low=0, high=data_dims[0], size=batch_dims) y, unflatten = utils.flatten_batch_to_2d(data, sizes) data_unflattened = unflatten(y) self.assertAllEqual(tf.shape(input=y), [np.sum(sizes), data_dims[1]]) self.assertAllEqual( tf.shape(input=data_unflattened), tf.shape(input=data)) with self.subTest(name="no_padding_with_sizes"): sizes = data_dims[0] * np.ones_like(sizes, dtype=np.int32) y, unflatten = utils.flatten_batch_to_2d(data, sizes) self.assertAllEqual(tf.shape(input=y), [np.sum(sizes), data_dims[1]]) self.assertAllEqual(data, unflatten(y)) with self.subTest(name="no_padding_with_sizes_none"): y, unflatten = utils.flatten_batch_to_2d(data, sizes=None) self.assertAllEqual(tf.shape(input=y), [np.sum(sizes), data_dims[1]]) self.assertAllEqual(data, unflatten(y)) def test_flatten_batch_to_2d_zero_sizes(self): """Test flattening with zero sizes.""" data = np.ones(shape=(10, 5, 3, 2)) sizes = np.zeros(shape=(10, 5), dtype=np.int32) y, unflatten = utils.flatten_batch_to_2d(data, sizes) self.assertAllEqual([0, 2], tf.shape(input=y)) self.assertAllEqual(np.zeros_like(data), unflatten(y)) def test_flatten_batch_to_2d_unflatten_different_feature_dims(self): """Test when inputs to flattening/unflattening use different channels.""" data_in = np.random.uniform(size=(3, 1, 7, 5, 4)) data_out = np.concatenate([data_in, data_in], axis=-1) y, unflatten = utils.flatten_batch_to_2d(data_in) self.assertAllEqual(unflatten(tf.concat([y, y], axis=-1)), data_out) def test_flatten_batch_to_2d_jacobian_random(self): """Test the jacobian is correct for random inputs.""" data_init = np.random.uniform(size=(3, 2, 7, 5, 4)) sizes = np.random.randint(low=1, high=5, size=(3, 2, 7)) flat_init = np.random.uniform(size=(np.sum(sizes), 10)) def flatten_batch_to_2d(data): flattened, _ = utils.flatten_batch_to_2d(data, sizes=sizes) return flattened def unflatten_2d_to_batch(flat): _, unflatten = utils.flatten_batch_to_2d(data_init, sizes=sizes) return unflatten(flat) with self.subTest(name="flatten"): self.assert_jacobian_is_correct_fn(flatten_batch_to_2d, [data_init]) with self.subTest(name="unflatten"): self.assert_jacobian_is_correct_fn(unflatten_2d_to_batch, [flat_init]) @parameterized.parameters((np.int32), (np.float32), (np.uint16)) def test_flatten_batch_to_2d_unflatten_types(self, dtype): """Test unflattening with int and float types.""" data = np.ones(shape=(2, 2, 3, 2), dtype=dtype) sizes = ((3, 2), (1, 3)) desired_unflattened = data desired_unflattened[0, 1, 2, :] = 0 desired_unflattened[1, 0, 1:, :] = 0 flat, unflatten = utils.flatten_batch_to_2d(data, sizes=sizes) data_unflattened = unflatten(flat) self.assertEqual(data.dtype, data_unflattened.dtype.as_numpy_dtype) self.assertAllEqual(data_unflattened, desired_unflattened) class UtilsUnflatten2dToBatchTest(test_case.TestCase): @parameterized.parameters(((3, 2, 4), (3,)), ((5,), (4, 2))) def test_input_rank_exception_raised(self, *shapes): """Check that invalid inputs trigger the right exception.""" self.assert_exception_is_raised(utils.unflatten_2d_to_batch, "data must have a rank of 2", shapes) def test_input_type_exception_raised(self): """Check that invalid input types trigger the right exception.""" with self.assertRaisesRegexp(TypeError, "'sizes' must have an integer type."): utils.unflatten_2d_to_batch(np.ones((3, 4)), np.ones((3,))) @parameterized.parameters( ((3, 2, 1), None, 5), ((3, 2, 1, 2), 4, 2), (((3, 2), (1, 2)), None, 2), ) def test_unflatten_batch_to_2d_random(self, sizes, max_rows, num_features): """Test unflattening with random inputs.""" max_rows = np.max(sizes) if max_rows is None else max_rows output_shape = np.concatenate( (np.shape(sizes), (max_rows,), (num_features,))) total_rows = np.sum(sizes) data = 0.1 + np.random.uniform(size=(total_rows, num_features)) unflattened = utils.unflatten_2d_to_batch(data, sizes, max_rows) flattened = tf.reshape(unflattened, (-1, num_features)) nonzero_rows = tf.compat.v1.where(tf.norm(tensor=flattened, axis=-1)) flattened_unpadded = tf.gather( params=flattened, indices=tf.squeeze(input=nonzero_rows, axis=-1)) self.assertAllEqual(tf.shape(input=unflattened), output_shape) self.assertAllEqual(flattened_unpadded, data) def test_unflatten_batch_to_2d_preset(self): """Test unflattening with a preset input.""" data = 1. + np.reshape(np.arange(12, dtype=np.float32), (6, 2)) sizes = (2, 3, 1) output_true = np.array( (((1., 2.), (3., 4.), (0., 0.)), ((5., 6.), (7., 8.), (9., 10.)), ((11., 12.), (0., 0.), (0., 0.))), dtype=np.float32) output_true_padded = np.pad( output_true, ((0, 0), (0, 2), (0, 0)), mode="constant") output = utils.unflatten_2d_to_batch(data, sizes, max_rows=None) output_padded = utils.unflatten_2d_to_batch(data, sizes, max_rows=5) self.assertAllEqual(output, output_true) self.assertAllEqual(output_padded, output_true_padded) @parameterized.parameters( ((3, 2, 1), None, 5), ((3, 2, 1, 2), 4, 2), (((3, 2), (1, 2)), None, 2), ) def test_unflatten_batch_to_2d_jacobian_random(self, sizes, max_rows, num_features): """Test that the jacobian is correct.""" max_rows = np.max(sizes) if max_rows is None else max_rows total_rows = np.sum(sizes) data_init = 0.1 + np.random.uniform(size=(total_rows, num_features)) def unflatten_2d_to_batch(data): return utils.unflatten_2d_to_batch(data, sizes, max_rows) self.assert_jacobian_is_correct_fn(unflatten_2d_to_batch, [data_init]) @parameterized.parameters((np.int32), (np.float32), (np.uint16)) def test_unflatten_batch_to_2d_types(self, dtype): """Test unflattening with int and float types.""" data = np.ones(shape=(6, 2), dtype=dtype) sizes = (2, 2, 2) unflattened_true = np.ones(shape=(3, 2, 2), dtype=dtype) unflattened = utils.unflatten_2d_to_batch(data, sizes) self.assertEqual(data.dtype, unflattened.dtype.as_numpy_dtype) self.assertAllEqual(unflattened, unflattened_true) class UtilsConvertToBlockDiag2dTests(test_case.TestCase): def _validate_sizes(self, block_diag_tensor, sizes): """Assert all elements outside the blocks are zero.""" data = [np.ones(shape=s) for s in sizes] mask = 1.0 - linalg.block_diag(*data) self.assertAllEqual( tf.sparse.to_dense(block_diag_tensor) * mask, np.zeros_like(mask)) def test_convert_to_block_diag_2d_exception_raised_types(self): """Check the exception when input is not a SparseTensor.""" with self.assertRaisesRegexp(TypeError, "'data' must be a 'SparseTensor'."): utils.convert_to_block_diag_2d(np.zeros(shape=(3, 3, 3))) with self.assertRaisesRegexp(TypeError, "'sizes' must have an integer type."): utils.convert_to_block_diag_2d( _dense_to_sparse(np.ones(shape=(3, 3, 3))), np.ones(shape=(3, 2)), ) def test_convert_to_block_diag_2d_exception_raised_ranks(self): """Check the exception when input data rank is invalid.""" with self.assertRaisesRegexp(ValueError, "must have a rank greater than 2"): utils.convert_to_block_diag_2d(_dense_to_sparse(np.ones(shape=(3, 3)))) with self.assertRaisesRegexp(ValueError, "must have a rank greater than 2"): utils.convert_to_block_diag_2d(_dense_to_sparse(np.ones(shape=(3,)))) def test_convert_to_block_diag_2d_exception_raised_sizes(self): """Check the expetion when the shape of sizes is invalid.""" with self.assertRaisesRegexp(ValueError, "must have a rank of 2"): utils.convert_to_block_diag_2d( _dense_to_sparse(np.ones(shape=(3, 3, 3))), np.ones(shape=(3,), dtype=np.int32)) with self.assertRaisesRegexp(ValueError, "must have a rank of 3"): utils.convert_to_block_diag_2d( _dense_to_sparse(np.ones(shape=(4, 3, 3, 3))), np.ones(shape=(4, 3), dtype=np.int32)) with self.assertRaisesRegexp(ValueError, "must have exactly 2 dimensions in axis -1"): utils.convert_to_block_diag_2d( _dense_to_sparse(np.ones(shape=(3, 3, 3))), np.ones(shape=(3, 1), dtype=np.int32)) def test_convert_to_block_diag_2d_random(self): """Test block diagonalization with random inputs.""" sizes = np.random.randint(low=2, high=6, size=(3, 2)) data = [np.random.uniform(size=s) for s in sizes] batch_data_padded = np.zeros( shape=np.concatenate(([len(sizes)], np.max(sizes, axis=0)), axis=0)) for i, s in enumerate(sizes): batch_data_padded[i, :s[0], :s[1]] = data[i] batch_data_padded_sparse = _dense_to_sparse(batch_data_padded) block_diag_data = linalg.block_diag(*data) block_diag_sparse = utils.convert_to_block_diag_2d( batch_data_padded_sparse, sizes=sizes) self.assertAllEqual(tf.sparse.to_dense(block_diag_sparse), block_diag_data) def test_convert_to_block_diag_2d_no_padding(self): """Test block diagonalization without any padding.""" batch_data = np.random.uniform(size=(3, 4, 5, 4)) block_diag_data = linalg.block_diag( *[x for x in np.reshape(batch_data, (-1, 5, 4))]) batch_data_sparse = _dense_to_sparse(batch_data) block_diag_sparse = utils.convert_to_block_diag_2d(batch_data_sparse) self.assertAllEqual(tf.sparse.to_dense(block_diag_sparse), block_diag_data) def test_convert_to_block_diag_2d_validate_indices(self): """Test block diagonalization when we filter out out-of-bounds indices.""" sizes = ((2, 3), (2, 3), (2, 3)) batch = _dense_to_sparse(np.random.uniform(size=(3, 4, 3))) block_diag = utils.convert_to_block_diag_2d(batch, sizes, True) self._validate_sizes(block_diag, sizes) def test_convert_to_block_diag_2d_large_sizes(self): """Test when the desired blocks are larger than the data shapes.""" sizes = ((5, 5), (6, 6), (7, 7)) batch = _dense_to_sparse(np.random.uniform(size=(3, 4, 3))) block_diag = utils.convert_to_block_diag_2d(batch, sizes) self._validate_sizes(block_diag, sizes) def test_convert_to_block_diag_2d_batch_shapes(self): """Test with different batch shapes.""" sizes_one_batch_dim = np.concatenate( [np.random.randint(low=1, high=h, size=(6 * 3 * 4, 1)) for h in (5, 7)], axis=-1) data = [np.random.uniform(size=s) for s in sizes_one_batch_dim] data_one_batch_dim_padded = np.zeros(shape=(6 * 3 * 4, 5, 7)) for i, s in enumerate(sizes_one_batch_dim): data_one_batch_dim_padded[i, :s[0], :s[1]] = data[i] data_many_batch_dim_padded = np.reshape(data_one_batch_dim_padded, (6, 3, 4, 5, 7)) sizes_many_batch_dim = np.reshape(sizes_one_batch_dim, (6, 3, 4, -1)) data_one_sparse = _dense_to_sparse(data_one_batch_dim_padded) data_many_sparse = _dense_to_sparse(data_many_batch_dim_padded) one_batch_dim = utils.convert_to_block_diag_2d(data_one_sparse, sizes_one_batch_dim) many_batch_dim = utils.convert_to_block_diag_2d(data_many_sparse, sizes_many_batch_dim) self.assertAllEqual( tf.sparse.to_dense(one_batch_dim), tf.sparse.to_dense(many_batch_dim)) self._validate_sizes(one_batch_dim, sizes_one_batch_dim) def test_convert_to_block_diag_2d_jacobian_random(self): """Test the jacobian is correct with random inputs.""" sizes = np.random.randint(low=2, high=6, size=(3, 2)) data = [np.random.uniform(size=s) for s in sizes] batch_data_padded = np.zeros( shape=np.concatenate([[len(sizes)], np.max(sizes, axis=0)], axis=0)) for i, s in enumerate(sizes): batch_data_padded[i, :s[0], :s[1]] = data[i] sparse_ind = np.where(batch_data_padded) sparse_val_init = batch_data_padded[sparse_ind] def convert_to_block_diag_2d(sparse_val): sparse = tf.SparseTensor( np.stack(sparse_ind, axis=-1), sparse_val, batch_data_padded.shape) return utils.convert_to_block_diag_2d(sparse, sizes).values self.assert_jacobian_is_correct_fn(convert_to_block_diag_2d, [sparse_val_init]) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for convolution utility functions.""" from absl.testing import parameterized import numpy as np from scipy import linalg import tensorflow as tf from tensorflow_graphics.geometry.convolution import utils from tensorflow_graphics.util import test_case def _dense_to_sparse(data): """Converts a numpy array to a tf.SparseTensor.""" indices = np.where(data) return tf.SparseTensor( np.stack(indices, axis=-1), data[indices], dense_shape=data.shape) class UtilsCheckValidGraphConvolutionInputTests(test_case.TestCase): def _create_default_tensors_from_shapes(self, shapes): """Creates `data`, `sparse`, `sizes` tensors from shapes list.""" data = tf.convert_to_tensor( value=np.random.uniform(size=shapes[0]).astype(np.float32)) sparse = _dense_to_sparse(np.ones(shape=shapes[1], dtype=np.float32)) if shapes[2] is not None: sizes = tf.convert_to_tensor( value=np.ones(shape=shapes[2], dtype=np.int32)) else: sizes = None return data, sparse, sizes @parameterized.parameters( ("'sizes' must have an integer type.", np.float32, np.float32, np.float32), ("'data' must have a float type.", np.int32, np.float32, np.int32), ("'neighbors' and 'data' must have the same type.", np.float32, np.float64, np.int32), ) def test_check_valid_graph_convolution_input_exception_raised_types( self, err_msg, data_type, neighbors_type, sizes_type): """Check the type errors for invalid input types.""" data = tf.convert_to_tensor( value=np.random.uniform(size=(2, 2, 2)).astype(data_type)) neighbors = _dense_to_sparse(np.ones(shape=(2, 2, 2), dtype=neighbors_type)) sizes = tf.convert_to_tensor(value=np.array((2, 2), dtype=sizes_type)) with self.assertRaisesRegexp(TypeError, err_msg): utils.check_valid_graph_convolution_input(data, neighbors, sizes) @parameterized.parameters( (np.float32, np.float32, np.int32), (np.float64, np.float64, np.int32), (np.float32, np.float32, np.int64), (np.float64, np.float64, np.int64), ) def test_check_valid_graph_convolution_input_exception_not_raised_types( self, data_type, neighbors_type, sizes_type): """Check that no exceptions are raised for valid input types.""" data = tf.convert_to_tensor( value=np.random.uniform(size=(2, 2, 2)).astype(data_type)) neighbors = _dense_to_sparse(np.ones(shape=(2, 2, 2), dtype=neighbors_type)) sizes = tf.convert_to_tensor(value=np.array((2, 2), dtype=sizes_type)) self.assert_exception_is_not_raised( utils.check_valid_graph_convolution_input, shapes=[], data=data, neighbors=neighbors, sizes=sizes) @parameterized.parameters( ((2, 3), (2, 2), None), ((1, 2, 3), (1, 2, 2), None), ((2, 2, 3), (2, 2, 2), None), ((1, 2, 3), (1, 2, 2), (1,)), ((2, 2, 3), (2, 2, 2), (2,)), ((1, 2, 2, 3), (1, 2, 2, 2), (1, 2)), ((2, 2, 2, 3), (2, 2, 2, 2), (2, 2)), ) def test_check_valid_graph_convolution_input_exception_not_raised_shapes( self, *shapes): """Check that valid input shapes do not trigger any exceptions.""" data, neighbors, sizes = self._create_default_tensors_from_shapes(shapes) self.assert_exception_is_not_raised( utils.check_valid_graph_convolution_input, shapes=[], data=data, neighbors=neighbors, sizes=sizes) @parameterized.parameters( ((None, 3), (None, 2), None), ((1, None, 3), (1, None, None), None), ((None, 2, 3), (None, 2, 2), (1,)), ((None, None, 3), (None, None, None), (2,)), ((1, None, 2, 3), (1, None, None, None), (1, 2)), ) def test_check_valid_graph_convolution_input_exception_not_raised_dynshapes( self, *shapes): """Check that valid dynamic input shapes do not trigger any exceptions.""" dtypes = [tf.float32, tf.float32] sparse_tensors = [False, True] if shapes[2] is not None: dtypes.append(tf.int32) sparse_tensors.append(False) self.assert_exception_is_not_raised( utils.check_valid_graph_convolution_input, shapes=shapes, dtypes=dtypes, sparse_tensors=sparse_tensors) else: self.assert_exception_is_not_raised( utils.check_valid_graph_convolution_input, shapes=shapes, dtypes=dtypes, sparse_tensors=sparse_tensors, sizes=None) def test_check_valid_graph_convolution_dynamic_input_sparse_exception_raised( self): """Check that passing dense `neighbors` tensor raises exception.""" error_msg = "must be a SparseTensor" dtypes = [tf.float32, tf.float32, tf.int32] sparse_tensors = [False, False, False] shapes = ((None, 3), (None, 2), (None,)) self.assert_exception_is_raised( utils.check_valid_graph_convolution_input, error_msg, shapes=shapes, dtypes=dtypes, sparse_tensors=sparse_tensors) @parameterized.parameters( ("must have a rank of 2", (5, 2), (1, 5, 2), None), ("must have a rank greater than 1", (5,), (5, 5), None), ("must have a rank of 2", (5, 2), (5,), None), ("must have a rank of 3", (5, 5, 2), (5, 5), None), ("must have the same number of dimensions in axes", (3, 2), (3, 2), None), ("must have a rank of 1", (5, 5, 2), (5, 5, 5), (5, 5)), ("Not all batch dimensions are identical.", (1, 5, 2), (1, 5, 5), (2,)), ) def test_check_valid_graph_convolution_input_exception_raised_shapes( self, error_msg, *shapes): """Check that invalid input shapes trigger the right exceptions.""" data, neighbors, sizes = self._create_default_tensors_from_shapes(shapes) self.assert_exception_is_raised( utils.check_valid_graph_convolution_input, error_msg, shapes=[], data=data, neighbors=neighbors, sizes=sizes) class UtilsCheckValidGraphPoolingInputTests(test_case.TestCase): @parameterized.parameters( ("'sizes' must have an integer type.", np.float32, np.float32, np.float32), ("'data' must have a float type.", np.int32, np.float32, np.int32), ("'pool_map' and 'data' must have the same type.", np.float32, np.float64, np.int32), ) def test_check_valid_graph_pooling_exception_raised_types( self, err_msg, data_type, pool_map_type, sizes_type): """Check the type errors for invalid input types.""" data = tf.convert_to_tensor(value=np.ones((2, 3, 3), dtype=data_type)) pool_map = _dense_to_sparse(np.ones((2, 3, 3), dtype=pool_map_type)) sizes = tf.convert_to_tensor( value=np.array(((1, 2), (2, 3)), dtype=sizes_type)) with self.assertRaisesRegexp(TypeError, err_msg): utils.check_valid_graph_pooling_input(data, pool_map, sizes) @parameterized.parameters( (np.float32, np.float32, np.int32), (np.float64, np.float64, np.int32), (np.float32, np.float32, np.int64), (np.float64, np.float64, np.int64), ) def test_check_valid_graph_pooling_exception_not_raised_types( self, data_type, pool_map_type, sizes_type): """Check there are no exceptions for valid input types.""" data = tf.convert_to_tensor(value=np.ones((2, 3, 3), dtype=data_type)) pool_map = _dense_to_sparse(np.ones((2, 3, 3), dtype=pool_map_type)) sizes = tf.convert_to_tensor( value=np.array(((1, 2), (2, 3)), dtype=sizes_type)) self.assert_exception_is_not_raised( utils.check_valid_graph_pooling_input, shapes=[], data=data, pool_map=pool_map, sizes=sizes) @parameterized.parameters( ((2, 3), (4, 2), None), ((1, 2, 3), (1, 5, 2), None), ((2, 2, 3), (2, 5, 2), ((3, 2), (2, 5))), ) def test_check_valid_graph_pooling_exception_not_raised_shapes( self, data_shape, pool_map_shape, sizes): """Check that valid input shapes do not trigger any exceptions.""" data = tf.convert_to_tensor(value=np.ones(data_shape, dtype=np.float32)) pool_map = _dense_to_sparse(np.ones(pool_map_shape, dtype=np.float32)) sizes = sizes if sizes is None else tf.convert_to_tensor(value=sizes) self.assert_exception_is_not_raised( utils.check_valid_graph_pooling_input, shapes=[], data=data, pool_map=pool_map, sizes=sizes) @parameterized.parameters( ((None, 3), (None, 2), None), ((1, None, 3), (1, None, None), None), ((None, 2, 3), (None, 5, 2), (2, 2)), ) def test_check_valid_graph_pooling_exception_not_raised_dynamic_shapes( self, *shapes): """Check that valid dynamic input shapes do not trigger any exceptions.""" dtypes = [tf.float32, tf.float32] sparse_tensors = [False, True] if shapes[2] is not None: dtypes.append(tf.int32) sparse_tensors.append(False) self.assert_exception_is_not_raised( utils.check_valid_graph_pooling_input, shapes=shapes, dtypes=dtypes, sparse_tensors=sparse_tensors) else: self.assert_exception_is_not_raised( utils.check_valid_graph_pooling_input, shapes=shapes, dtypes=dtypes, sparse_tensors=sparse_tensors, sizes=None) def test_check_graph_pooling_input_sparse_exception_raised(self): """Check that passing dense `neighbors` tensor raises exception.""" error_msg = "must be a SparseTensor" dtypes = [tf.float32, tf.float32, tf.int32] sparse_tensors = [False, False, False] shapes = ((2, 2, 3), (2, 5, 2), (2, 2)) self.assert_exception_is_raised( utils.check_valid_graph_convolution_input, error_msg, shapes=shapes, dtypes=dtypes, sparse_tensors=sparse_tensors) @parameterized.parameters( ("must have a rank greater than 1", (5,), (5, 5), None), ("must have a rank of 2", (5, 2), (5,), None), ("must have the same number of dimensions in axes", (3, 2), (3, 2), None), ("Not all batch dimensions are identical.", (3, 5, 2), (1, 5, 5), None), ("must have a rank of 2", (2, 5, 2), (2, 3, 5), (3, 5)), ("Not all batch dimensions are identical.", (3, 5, 2), (3, 3, 5), ((3, 5), (2, 4))), ) def test_check_valid_graph_pooling_exception_raised_shapes( self, err_msg, data_shape, pool_map_shape, sizes): """Check that invalid input shapes trigger the right exceptions.""" data = tf.convert_to_tensor(value=np.ones(data_shape, dtype=np.float32)) pool_map = _dense_to_sparse(np.ones(pool_map_shape, dtype=np.float32)) sizes = sizes if sizes is None else tf.convert_to_tensor(value=sizes) self.assert_exception_is_raised( utils.check_valid_graph_pooling_input, err_msg, shapes=[], data=data, pool_map=pool_map, sizes=sizes) class UtilsFlattenBatchTo2dTests(test_case.TestCase): @parameterized.parameters(((5, 3),), ((3,),)) def test_input_rank_exception_raised(self, *shapes): """Check that invalid input data rank triggers the right exceptions.""" self.assert_exception_is_raised(utils.flatten_batch_to_2d, "must have a rank greater than 2", shapes) def test_flatten_batch_to_2d_exception_raised_types(self): """Check the exception when input is not an integer.""" with self.assertRaisesRegexp(TypeError, "'sizes' must have an integer type."): utils.flatten_batch_to_2d(np.ones((3, 4, 3)), np.ones((3,))) @parameterized.parameters( ((None, 3, 3), None), ((3, None, 3), (3,)), ) def test_check_flatten_batch_to_2d_exception_not_raised_dynamic_shapes( self, *shapes): """Check that valid dynamic input shapes do not trigger any exceptions.""" dtypes = [tf.float32] if shapes[1] is not None: dtypes.append(tf.int32) self.assert_exception_is_not_raised( utils.flatten_batch_to_2d, shapes=shapes, dtypes=dtypes) else: self.assert_exception_is_not_raised( utils.flatten_batch_to_2d, shapes=shapes, dtypes=dtypes, sizes=None) @parameterized.parameters( ("must have a rank of 1", (3, 4, 3), (3, 4)), ("must have a rank of 1", (3, 4, 5), (3, 4, 5)), ) def test_flatten_batch_to_2d_exception_raised(self, error_msg, *shapes): """Check the exception when the shape of 'sizes' is invalid.""" self.assert_exception_is_raised( utils.flatten_batch_to_2d, error_msg, shapes, dtypes=(tf.float32, tf.int32)) def test_flatten_batch_to_2d_random(self): """Test flattening with random inputs.""" ndims_batch = np.random.randint(low=1, high=5) batch_dims = np.random.randint(low=1, high=10, size=ndims_batch) data_dims = np.random.randint(low=1, high=20, size=2) dims = np.concatenate([batch_dims, data_dims], axis=0) data = np.random.uniform(size=dims) with self.subTest(name="random_padding"): sizes = np.random.randint(low=0, high=data_dims[0], size=batch_dims) y, unflatten = utils.flatten_batch_to_2d(data, sizes) data_unflattened = unflatten(y) self.assertAllEqual(tf.shape(input=y), [np.sum(sizes), data_dims[1]]) self.assertAllEqual( tf.shape(input=data_unflattened), tf.shape(input=data)) with self.subTest(name="no_padding_with_sizes"): sizes = data_dims[0] * np.ones_like(sizes, dtype=np.int32) y, unflatten = utils.flatten_batch_to_2d(data, sizes) self.assertAllEqual(tf.shape(input=y), [np.sum(sizes), data_dims[1]]) self.assertAllEqual(data, unflatten(y)) with self.subTest(name="no_padding_with_sizes_none"): y, unflatten = utils.flatten_batch_to_2d(data, sizes=None) self.assertAllEqual(tf.shape(input=y), [np.sum(sizes), data_dims[1]]) self.assertAllEqual(data, unflatten(y)) def test_flatten_batch_to_2d_zero_sizes(self): """Test flattening with zero sizes.""" data = np.ones(shape=(10, 5, 3, 2)) sizes = np.zeros(shape=(10, 5), dtype=np.int32) y, unflatten = utils.flatten_batch_to_2d(data, sizes) self.assertAllEqual([0, 2], tf.shape(input=y)) self.assertAllEqual(np.zeros_like(data), unflatten(y)) def test_flatten_batch_to_2d_unflatten_different_feature_dims(self): """Test when inputs to flattening/unflattening use different channels.""" data_in = np.random.uniform(size=(3, 1, 7, 5, 4)) data_out = np.concatenate([data_in, data_in], axis=-1) y, unflatten = utils.flatten_batch_to_2d(data_in) self.assertAllEqual(unflatten(tf.concat([y, y], axis=-1)), data_out) def test_flatten_batch_to_2d_jacobian_random(self): """Test the jacobian is correct for random inputs.""" data_init = np.random.uniform(size=(3, 2, 7, 5, 4)) sizes = np.random.randint(low=1, high=5, size=(3, 2, 7)) flat_init = np.random.uniform(size=(np.sum(sizes), 10)) def flatten_batch_to_2d(data): flattened, _ = utils.flatten_batch_to_2d(data, sizes=sizes) return flattened def unflatten_2d_to_batch(flat): _, unflatten = utils.flatten_batch_to_2d(data_init, sizes=sizes) return unflatten(flat) with self.subTest(name="flatten"): self.assert_jacobian_is_correct_fn(flatten_batch_to_2d, [data_init]) with self.subTest(name="unflatten"): self.assert_jacobian_is_correct_fn(unflatten_2d_to_batch, [flat_init]) @parameterized.parameters((np.int32), (np.float32), (np.uint16)) def test_flatten_batch_to_2d_unflatten_types(self, dtype): """Test unflattening with int and float types.""" data = np.ones(shape=(2, 2, 3, 2), dtype=dtype) sizes = ((3, 2), (1, 3)) desired_unflattened = data desired_unflattened[0, 1, 2, :] = 0 desired_unflattened[1, 0, 1:, :] = 0 flat, unflatten = utils.flatten_batch_to_2d(data, sizes=sizes) data_unflattened = unflatten(flat) self.assertEqual(data.dtype, data_unflattened.dtype.as_numpy_dtype) self.assertAllEqual(data_unflattened, desired_unflattened) class UtilsUnflatten2dToBatchTest(test_case.TestCase): @parameterized.parameters(((3, 2, 4), (3,)), ((5,), (4, 2))) def test_input_rank_exception_raised(self, *shapes): """Check that invalid inputs trigger the right exception.""" self.assert_exception_is_raised(utils.unflatten_2d_to_batch, "data must have a rank of 2", shapes) def test_input_type_exception_raised(self): """Check that invalid input types trigger the right exception.""" with self.assertRaisesRegexp(TypeError, "'sizes' must have an integer type."): utils.unflatten_2d_to_batch(np.ones((3, 4)), np.ones((3,))) @parameterized.parameters( ((3, 2, 1), None, 5), ((3, 2, 1, 2), 4, 2), (((3, 2), (1, 2)), None, 2), ) def test_unflatten_batch_to_2d_random(self, sizes, max_rows, num_features): """Test unflattening with random inputs.""" max_rows = np.max(sizes) if max_rows is None else max_rows output_shape = np.concatenate( (np.shape(sizes), (max_rows,), (num_features,))) total_rows = np.sum(sizes) data = 0.1 + np.random.uniform(size=(total_rows, num_features)) unflattened = utils.unflatten_2d_to_batch(data, sizes, max_rows) flattened = tf.reshape(unflattened, (-1, num_features)) nonzero_rows = tf.compat.v1.where(tf.norm(tensor=flattened, axis=-1)) flattened_unpadded = tf.gather( params=flattened, indices=tf.squeeze(input=nonzero_rows, axis=-1)) self.assertAllEqual(tf.shape(input=unflattened), output_shape) self.assertAllEqual(flattened_unpadded, data) def test_unflatten_batch_to_2d_preset(self): """Test unflattening with a preset input.""" data = 1. + np.reshape(np.arange(12, dtype=np.float32), (6, 2)) sizes = (2, 3, 1) output_true = np.array( (((1., 2.), (3., 4.), (0., 0.)), ((5., 6.), (7., 8.), (9., 10.)), ((11., 12.), (0., 0.), (0., 0.))), dtype=np.float32) output_true_padded = np.pad( output_true, ((0, 0), (0, 2), (0, 0)), mode="constant") output = utils.unflatten_2d_to_batch(data, sizes, max_rows=None) output_padded = utils.unflatten_2d_to_batch(data, sizes, max_rows=5) self.assertAllEqual(output, output_true) self.assertAllEqual(output_padded, output_true_padded) @parameterized.parameters( ((3, 2, 1), None, 5), ((3, 2, 1, 2), 4, 2), (((3, 2), (1, 2)), None, 2), ) def test_unflatten_batch_to_2d_jacobian_random(self, sizes, max_rows, num_features): """Test that the jacobian is correct.""" max_rows = np.max(sizes) if max_rows is None else max_rows total_rows = np.sum(sizes) data_init = 0.1 + np.random.uniform(size=(total_rows, num_features)) def unflatten_2d_to_batch(data): return utils.unflatten_2d_to_batch(data, sizes, max_rows) self.assert_jacobian_is_correct_fn(unflatten_2d_to_batch, [data_init]) @parameterized.parameters((np.int32), (np.float32), (np.uint16)) def test_unflatten_batch_to_2d_types(self, dtype): """Test unflattening with int and float types.""" data = np.ones(shape=(6, 2), dtype=dtype) sizes = (2, 2, 2) unflattened_true = np.ones(shape=(3, 2, 2), dtype=dtype) unflattened = utils.unflatten_2d_to_batch(data, sizes) self.assertEqual(data.dtype, unflattened.dtype.as_numpy_dtype) self.assertAllEqual(unflattened, unflattened_true) class UtilsConvertToBlockDiag2dTests(test_case.TestCase): def _validate_sizes(self, block_diag_tensor, sizes): """Assert all elements outside the blocks are zero.""" data = [np.ones(shape=s) for s in sizes] mask = 1.0 - linalg.block_diag(*data) self.assertAllEqual( tf.sparse.to_dense(block_diag_tensor) * mask, np.zeros_like(mask)) def test_convert_to_block_diag_2d_exception_raised_types(self): """Check the exception when input is not a SparseTensor.""" with self.assertRaisesRegexp(TypeError, "'data' must be a 'SparseTensor'."): utils.convert_to_block_diag_2d(np.zeros(shape=(3, 3, 3))) with self.assertRaisesRegexp(TypeError, "'sizes' must have an integer type."): utils.convert_to_block_diag_2d( _dense_to_sparse(np.ones(shape=(3, 3, 3))), np.ones(shape=(3, 2)), ) def test_convert_to_block_diag_2d_exception_raised_ranks(self): """Check the exception when input data rank is invalid.""" with self.assertRaisesRegexp(ValueError, "must have a rank greater than 2"): utils.convert_to_block_diag_2d(_dense_to_sparse(np.ones(shape=(3, 3)))) with self.assertRaisesRegexp(ValueError, "must have a rank greater than 2"): utils.convert_to_block_diag_2d(_dense_to_sparse(np.ones(shape=(3,)))) def test_convert_to_block_diag_2d_exception_raised_sizes(self): """Check the expetion when the shape of sizes is invalid.""" with self.assertRaisesRegexp(ValueError, "must have a rank of 2"): utils.convert_to_block_diag_2d( _dense_to_sparse(np.ones(shape=(3, 3, 3))), np.ones(shape=(3,), dtype=np.int32)) with self.assertRaisesRegexp(ValueError, "must have a rank of 3"): utils.convert_to_block_diag_2d( _dense_to_sparse(np.ones(shape=(4, 3, 3, 3))), np.ones(shape=(4, 3), dtype=np.int32)) with self.assertRaisesRegexp(ValueError, "must have exactly 2 dimensions in axis -1"): utils.convert_to_block_diag_2d( _dense_to_sparse(np.ones(shape=(3, 3, 3))), np.ones(shape=(3, 1), dtype=np.int32)) def test_convert_to_block_diag_2d_random(self): """Test block diagonalization with random inputs.""" sizes = np.random.randint(low=2, high=6, size=(3, 2)) data = [np.random.uniform(size=s) for s in sizes] batch_data_padded = np.zeros( shape=np.concatenate(([len(sizes)], np.max(sizes, axis=0)), axis=0)) for i, s in enumerate(sizes): batch_data_padded[i, :s[0], :s[1]] = data[i] batch_data_padded_sparse = _dense_to_sparse(batch_data_padded) block_diag_data = linalg.block_diag(*data) block_diag_sparse = utils.convert_to_block_diag_2d( batch_data_padded_sparse, sizes=sizes) self.assertAllEqual(tf.sparse.to_dense(block_diag_sparse), block_diag_data) def test_convert_to_block_diag_2d_no_padding(self): """Test block diagonalization without any padding.""" batch_data = np.random.uniform(size=(3, 4, 5, 4)) block_diag_data = linalg.block_diag( *[x for x in np.reshape(batch_data, (-1, 5, 4))]) batch_data_sparse = _dense_to_sparse(batch_data) block_diag_sparse = utils.convert_to_block_diag_2d(batch_data_sparse) self.assertAllEqual(tf.sparse.to_dense(block_diag_sparse), block_diag_data) def test_convert_to_block_diag_2d_validate_indices(self): """Test block diagonalization when we filter out out-of-bounds indices.""" sizes = ((2, 3), (2, 3), (2, 3)) batch = _dense_to_sparse(np.random.uniform(size=(3, 4, 3))) block_diag = utils.convert_to_block_diag_2d(batch, sizes, True) self._validate_sizes(block_diag, sizes) def test_convert_to_block_diag_2d_large_sizes(self): """Test when the desired blocks are larger than the data shapes.""" sizes = ((5, 5), (6, 6), (7, 7)) batch = _dense_to_sparse(np.random.uniform(size=(3, 4, 3))) block_diag = utils.convert_to_block_diag_2d(batch, sizes) self._validate_sizes(block_diag, sizes) def test_convert_to_block_diag_2d_batch_shapes(self): """Test with different batch shapes.""" sizes_one_batch_dim = np.concatenate( [np.random.randint(low=1, high=h, size=(6 * 3 * 4, 1)) for h in (5, 7)], axis=-1) data = [np.random.uniform(size=s) for s in sizes_one_batch_dim] data_one_batch_dim_padded = np.zeros(shape=(6 * 3 * 4, 5, 7)) for i, s in enumerate(sizes_one_batch_dim): data_one_batch_dim_padded[i, :s[0], :s[1]] = data[i] data_many_batch_dim_padded = np.reshape(data_one_batch_dim_padded, (6, 3, 4, 5, 7)) sizes_many_batch_dim = np.reshape(sizes_one_batch_dim, (6, 3, 4, -1)) data_one_sparse = _dense_to_sparse(data_one_batch_dim_padded) data_many_sparse = _dense_to_sparse(data_many_batch_dim_padded) one_batch_dim = utils.convert_to_block_diag_2d(data_one_sparse, sizes_one_batch_dim) many_batch_dim = utils.convert_to_block_diag_2d(data_many_sparse, sizes_many_batch_dim) self.assertAllEqual( tf.sparse.to_dense(one_batch_dim), tf.sparse.to_dense(many_batch_dim)) self._validate_sizes(one_batch_dim, sizes_one_batch_dim) def test_convert_to_block_diag_2d_jacobian_random(self): """Test the jacobian is correct with random inputs.""" sizes = np.random.randint(low=2, high=6, size=(3, 2)) data = [np.random.uniform(size=s) for s in sizes] batch_data_padded = np.zeros( shape=np.concatenate([[len(sizes)], np.max(sizes, axis=0)], axis=0)) for i, s in enumerate(sizes): batch_data_padded[i, :s[0], :s[1]] = data[i] sparse_ind = np.where(batch_data_padded) sparse_val_init = batch_data_padded[sparse_ind] def convert_to_block_diag_2d(sparse_val): sparse = tf.SparseTensor( np.stack(sparse_ind, axis=-1), sparse_val, batch_data_padded.shape) return utils.convert_to_block_diag_2d(sparse, sizes).values self.assert_jacobian_is_correct_fn(convert_to_block_diag_2d, [sparse_val_init]) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/transformation/rotation_matrix_3d.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow 3d rotation matrix utility functions. More details rotation matrices can be found on [this page.] (https://en.wikipedia.org/wiki/Rotation_matrix) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape from tensorflow_graphics.util import tfg_flags FLAGS = flags.FLAGS def _build_matrix_from_sines_and_cosines(sin_angles, cos_angles): """Builds a rotation matrix from sines and cosines of Euler angles. Note: In the following, A1 to An are optional batch dimensions. Args: sin_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the sine of the Euler angles. cos_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the cosine of the Euler angles. Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. """ sin_angles.shape.assert_is_compatible_with(cos_angles.shape) sx, sy, sz = tf.unstack(sin_angles, axis=-1) cx, cy, cz = tf.unstack(cos_angles, axis=-1) m00 = cy * cz m01 = (sx * sy * cz) - (cx * sz) m02 = (cx * sy * cz) + (sx * sz) m10 = cy * sz m11 = (sx * sy * sz) + (cx * cz) m12 = (cx * sy * sz) - (sx * cz) m20 = -sy m21 = sx * cy m22 = cx * cy matrix = tf.stack((m00, m01, m02, m10, m11, m12, m20, m21, m22), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=sin_angles)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def assert_rotation_matrix_normalized(matrix, eps=1e-3, name=None): """Checks whether a matrix is a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. eps: The absolute tolerance parameter. name: A name for this op that defaults to 'assert_rotation_matrix_normalized'. Returns: The input matrix, with dependence on the assertion operator in the graph. Raises: tf.errors.InvalidArgumentError: If rotation_matrix_3d is not normalized. """ if not FLAGS[tfg_flags.TFG_ADD_ASSERTS_TO_GRAPH].value: return matrix with tf.compat.v1.name_scope(name, "assert_rotation_matrix_normalized", [matrix]): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) is_matrix_normalized = is_valid(matrix, atol=eps) with tf.control_dependencies([ tf.compat.v1.assert_equal( is_matrix_normalized, tf.ones_like(is_matrix_normalized, dtype=tf.bool)) ]): return tf.identity(matrix) def from_axis_angle(axis, angle, name=None): """Convert an axis-angle representation to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a normalized axis. name: A name for this op that defaults to "rotation_matrix_3d_from_axis_angle". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represents a 3d rotation matrix. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_from_axis_angle", [axis, angle]): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) sin_axis = tf.sin(angle) * axis cos_angle = tf.cos(angle) cos1_axis = (1.0 - cos_angle) * axis _, axis_y, axis_z = tf.unstack(axis, axis=-1) cos1_axis_x, cos1_axis_y, _ = tf.unstack(cos1_axis, axis=-1) sin_axis_x, sin_axis_y, sin_axis_z = tf.unstack(sin_axis, axis=-1) tmp = cos1_axis_x * axis_y m01 = tmp - sin_axis_z m10 = tmp + sin_axis_z tmp = cos1_axis_x * axis_z m02 = tmp + sin_axis_y m20 = tmp - sin_axis_y tmp = cos1_axis_y * axis_z m12 = tmp - sin_axis_x m21 = tmp + sin_axis_x diag = cos1_axis * axis + cos_angle diag_x, diag_y, diag_z = tf.unstack(diag, axis=-1) matrix = tf.stack((diag_x, m01, m02, m10, diag_y, m12, m20, m21, diag_z), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=axis)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def from_euler(angles, name=None): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_from_euler", [angles]): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = tf.sin(angles) cos_angles = tf.cos(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_euler_with_small_angles_approximation(angles, name=None): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three small Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians, `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.compat.v1.name_scope( name, "rotation_matrix_3d_from_euler_with_small_angles", [angles]): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = angles cos_angles = 1.0 - 0.5 * tf.square(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_quaternion(quaternion, name=None): """Convert a quaternion to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "rotation_matrix_3d_from_quaternion". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_from_quaternion", [quaternion]): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) x, y, z, w = tf.unstack(quaternion, axis=-1) tx = 2.0 * x ty = 2.0 * y tz = 2.0 * z twx = tx * w twy = ty * w twz = tz * w txx = tx * x txy = ty * x txz = tz * x tyy = ty * y tyz = tz * y tzz = tz * z matrix = tf.stack((1.0 - (tyy + tzz), txy - twz, txz + twy, txy + twz, 1.0 - (txx + tzz), tyz - twx, txz - twy, tyz + twx, 1.0 - (txx + tyy)), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=quaternion)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def inverse(matrix, name=None): """Computes the inverse of a 3D rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_inverse". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `matrix` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_inverse", [matrix]): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) matrix = assert_rotation_matrix_normalized(matrix) ndims = matrix.shape.ndims perm = list(range(ndims - 2)) + [ndims - 1, ndims - 2] return tf.transpose(a=matrix, perm=perm) def is_valid(matrix, atol=1e-3, name=None): """Determines if a matrix is a valid rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last two dimensions represent a matrix. atol: Absolute tolerance parameter. name: A name for this op that defaults to "rotation_matrix_3d_is_valid". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]` where False indicates that the input is not a valid rotation matrix. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_is_valid", [matrix]): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) return rotation_matrix_common.is_valid(matrix, atol) def rotate(point, matrix, name=None): """Rotate a point using a rotation matrix 3d. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last dimension represents a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If the shape of `point` or `rotation_matrix_3d` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_rotate", [point, matrix]): point = tf.convert_to_tensor(value=point) matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) shape.compare_batch_dimensions( tensors=(point, matrix), tensor_names=("point", "matrix"), last_axes=(-2, -3), broadcast_compatible=True) matrix = assert_rotation_matrix_normalized(matrix) point = tf.expand_dims(point, axis=-1) common_batch_shape = shape.get_broadcasted_shape( point.shape[:-2], matrix.shape[:-2]) def dim_value(dim): return 1 if dim is None else tf.compat.v1.dimension_value(dim) common_batch_shape = [dim_value(dim) for dim in common_batch_shape] point = tf.broadcast_to(point, common_batch_shape + [3, 1]) matrix = tf.broadcast_to(matrix, common_batch_shape + [3, 3]) rotated_point = tf.matmul(matrix, point) return tf.squeeze(rotated_point, axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow 3d rotation matrix utility functions. More details rotation matrices can be found on [this page.] (https://en.wikipedia.org/wiki/Rotation_matrix) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape from tensorflow_graphics.util import tfg_flags FLAGS = flags.FLAGS def _build_matrix_from_sines_and_cosines(sin_angles, cos_angles): """Builds a rotation matrix from sines and cosines of Euler angles. Note: In the following, A1 to An are optional batch dimensions. Args: sin_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the sine of the Euler angles. cos_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the cosine of the Euler angles. Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. """ sin_angles.shape.assert_is_compatible_with(cos_angles.shape) sx, sy, sz = tf.unstack(sin_angles, axis=-1) cx, cy, cz = tf.unstack(cos_angles, axis=-1) m00 = cy * cz m01 = (sx * sy * cz) - (cx * sz) m02 = (cx * sy * cz) + (sx * sz) m10 = cy * sz m11 = (sx * sy * sz) + (cx * cz) m12 = (cx * sy * sz) - (sx * cz) m20 = -sy m21 = sx * cy m22 = cx * cy matrix = tf.stack((m00, m01, m02, m10, m11, m12, m20, m21, m22), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=sin_angles)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def assert_rotation_matrix_normalized(matrix, eps=1e-3, name=None): """Checks whether a matrix is a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. eps: The absolute tolerance parameter. name: A name for this op that defaults to 'assert_rotation_matrix_normalized'. Returns: The input matrix, with dependence on the assertion operator in the graph. Raises: tf.errors.InvalidArgumentError: If rotation_matrix_3d is not normalized. """ if not FLAGS[tfg_flags.TFG_ADD_ASSERTS_TO_GRAPH].value: return matrix with tf.compat.v1.name_scope(name, "assert_rotation_matrix_normalized", [matrix]): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) is_matrix_normalized = is_valid(matrix, atol=eps) with tf.control_dependencies([ tf.compat.v1.assert_equal( is_matrix_normalized, tf.ones_like(is_matrix_normalized, dtype=tf.bool)) ]): return tf.identity(matrix) def from_axis_angle(axis, angle, name=None): """Convert an axis-angle representation to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a normalized axis. name: A name for this op that defaults to "rotation_matrix_3d_from_axis_angle". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represents a 3d rotation matrix. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_from_axis_angle", [axis, angle]): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) sin_axis = tf.sin(angle) * axis cos_angle = tf.cos(angle) cos1_axis = (1.0 - cos_angle) * axis _, axis_y, axis_z = tf.unstack(axis, axis=-1) cos1_axis_x, cos1_axis_y, _ = tf.unstack(cos1_axis, axis=-1) sin_axis_x, sin_axis_y, sin_axis_z = tf.unstack(sin_axis, axis=-1) tmp = cos1_axis_x * axis_y m01 = tmp - sin_axis_z m10 = tmp + sin_axis_z tmp = cos1_axis_x * axis_z m02 = tmp + sin_axis_y m20 = tmp - sin_axis_y tmp = cos1_axis_y * axis_z m12 = tmp - sin_axis_x m21 = tmp + sin_axis_x diag = cos1_axis * axis + cos_angle diag_x, diag_y, diag_z = tf.unstack(diag, axis=-1) matrix = tf.stack((diag_x, m01, m02, m10, diag_y, m12, m20, m21, diag_z), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=axis)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def from_euler(angles, name=None): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_from_euler", [angles]): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = tf.sin(angles) cos_angles = tf.cos(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_euler_with_small_angles_approximation(angles, name=None): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three small Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians, `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.compat.v1.name_scope( name, "rotation_matrix_3d_from_euler_with_small_angles", [angles]): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = angles cos_angles = 1.0 - 0.5 * tf.square(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_quaternion(quaternion, name=None): """Convert a quaternion to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "rotation_matrix_3d_from_quaternion". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_from_quaternion", [quaternion]): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) x, y, z, w = tf.unstack(quaternion, axis=-1) tx = 2.0 * x ty = 2.0 * y tz = 2.0 * z twx = tx * w twy = ty * w twz = tz * w txx = tx * x txy = ty * x txz = tz * x tyy = ty * y tyz = tz * y tzz = tz * z matrix = tf.stack((1.0 - (tyy + tzz), txy - twz, txz + twy, txy + twz, 1.0 - (txx + tzz), tyz - twx, txz - twy, tyz + twx, 1.0 - (txx + tyy)), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=quaternion)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def inverse(matrix, name=None): """Computes the inverse of a 3D rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_inverse". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `matrix` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_inverse", [matrix]): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) matrix = assert_rotation_matrix_normalized(matrix) ndims = matrix.shape.ndims perm = list(range(ndims - 2)) + [ndims - 1, ndims - 2] return tf.transpose(a=matrix, perm=perm) def is_valid(matrix, atol=1e-3, name=None): """Determines if a matrix is a valid rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last two dimensions represent a matrix. atol: Absolute tolerance parameter. name: A name for this op that defaults to "rotation_matrix_3d_is_valid". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]` where False indicates that the input is not a valid rotation matrix. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_is_valid", [matrix]): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) return rotation_matrix_common.is_valid(matrix, atol) def rotate(point, matrix, name=None): """Rotate a point using a rotation matrix 3d. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last dimension represents a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If the shape of `point` or `rotation_matrix_3d` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_rotate", [point, matrix]): point = tf.convert_to_tensor(value=point) matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) shape.compare_batch_dimensions( tensors=(point, matrix), tensor_names=("point", "matrix"), last_axes=(-2, -3), broadcast_compatible=True) matrix = assert_rotation_matrix_normalized(matrix) point = tf.expand_dims(point, axis=-1) common_batch_shape = shape.get_broadcasted_shape( point.shape[:-2], matrix.shape[:-2]) def dim_value(dim): return 1 if dim is None else tf.compat.v1.dimension_value(dim) common_batch_shape = [dim_value(dim) for dim in common_batch_shape] point = tf.broadcast_to(point, common_batch_shape + [3, 1]) matrix = tf.broadcast_to(matrix, common_batch_shape + [3, 3]) rotated_point = tf.matmul(matrix, point) return tf.squeeze(rotated_point, axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/rendering/voxels/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/nn/metric/tests/intersection_over_union_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the intersection-over-union metric.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.nn.metric import intersection_over_union from tensorflow_graphics.util import test_case def random_tensor(tensor_shape): return np.random.uniform(low=0.0, high=1.0, size=tensor_shape) def random_tensor_shape(): tensor_size = np.random.randint(5) + 1 return np.random.randint(1, 10, size=(tensor_size)).tolist() class IntersectionOverUnionTest(test_case.TestCase): @parameterized.parameters( # 1 dimensional grid. ([1., 0, 0, 1, 1, 0, 1], \ [1., 0, 1, 1, 1, 1, 0], 3. / 6.), # 2 dimensional grid. ([[1., 0, 1], [0, 0, 1], [0, 1, 1]], \ [[0., 1, 1], [1, 1, 1], [0, 0, 1]], 3. / 8.), ([[0., 0, 1], [0, 0, 0]], \ [[1., 1, 0], [0, 0, 1]], 0.), # Returns 1 if the prediction and ground-truth are all zeros. ([[0., 0, 0], [0, 0, 0]], \ [[0., 0, 0], [0, 0, 0]], 1.), ) def test_evaluate_preset(self, ground_truth, predictions, expected_iou): tensor_shape = random_tensor_shape() grid_size = np.array(ground_truth).ndim ground_truth_labels = np.tile(ground_truth, tensor_shape + [1] * grid_size) predicted_labels = np.tile(predictions, tensor_shape + [1] * grid_size) expected = np.tile(expected_iou, tensor_shape) result = intersection_over_union.evaluate(ground_truth_labels, predicted_labels, grid_size) self.assertAllClose(expected, result) @parameterized.parameters( # Exception is raised since not all the value are in the range [0, 1] (r"0.* 0\.7.* 0", [0., 0.7, 0], [0., 1.0, 0.0], 1), (r"0\.3.* 1.* 0.*", [0., 1.0, 0], [0.3, 1.0, 0.0], 1), # Grid size must be less or equal to min_inputs_dimensions. (r"Invalid reduction dimension .*\-2 for input with 1 dimension", [1., 0.], [[0., 1.0], [1., 1.0]], 2), ) def test_evaluate_invalid_argument_exception_raised(self, error_msg, ground_truth, predictions, grid_size): with self.assertRaisesRegexp((tf.errors.InvalidArgumentError, ValueError), error_msg): self.evaluate( intersection_over_union.evaluate(ground_truth, predictions, grid_size)) @parameterized.parameters( ("Not all batch dimensions are broadcast-compatible.", (1, 5, 3), (4, 3)), ("Not all batch dimensions are broadcast-compatible.", (3, 4), (2, 4, 5)), ) def test_evaluate_shape_exception_raised(self, error_msg, *shape): """Tests that the shape exception is raised.""" self.assert_exception_is_raised(intersection_over_union.evaluate, error_msg, shape) @parameterized.parameters( ((1, 5, 3), (2, 5, 1)), ((None, 2, 6), (4, 2, None)), ((3, 5, 8, 2), (3, 1, 1, 2)), ) def test_evaluate_shape_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(intersection_over_union.evaluate, shapes) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the intersection-over-union metric.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.nn.metric import intersection_over_union from tensorflow_graphics.util import test_case def random_tensor(tensor_shape): return np.random.uniform(low=0.0, high=1.0, size=tensor_shape) def random_tensor_shape(): tensor_size = np.random.randint(5) + 1 return np.random.randint(1, 10, size=(tensor_size)).tolist() class IntersectionOverUnionTest(test_case.TestCase): @parameterized.parameters( # 1 dimensional grid. ([1., 0, 0, 1, 1, 0, 1], \ [1., 0, 1, 1, 1, 1, 0], 3. / 6.), # 2 dimensional grid. ([[1., 0, 1], [0, 0, 1], [0, 1, 1]], \ [[0., 1, 1], [1, 1, 1], [0, 0, 1]], 3. / 8.), ([[0., 0, 1], [0, 0, 0]], \ [[1., 1, 0], [0, 0, 1]], 0.), # Returns 1 if the prediction and ground-truth are all zeros. ([[0., 0, 0], [0, 0, 0]], \ [[0., 0, 0], [0, 0, 0]], 1.), ) def test_evaluate_preset(self, ground_truth, predictions, expected_iou): tensor_shape = random_tensor_shape() grid_size = np.array(ground_truth).ndim ground_truth_labels = np.tile(ground_truth, tensor_shape + [1] * grid_size) predicted_labels = np.tile(predictions, tensor_shape + [1] * grid_size) expected = np.tile(expected_iou, tensor_shape) result = intersection_over_union.evaluate(ground_truth_labels, predicted_labels, grid_size) self.assertAllClose(expected, result) @parameterized.parameters( # Exception is raised since not all the value are in the range [0, 1] (r"0.* 0\.7.* 0", [0., 0.7, 0], [0., 1.0, 0.0], 1), (r"0\.3.* 1.* 0.*", [0., 1.0, 0], [0.3, 1.0, 0.0], 1), # Grid size must be less or equal to min_inputs_dimensions. (r"Invalid reduction dimension .*\-2 for input with 1 dimension", [1., 0.], [[0., 1.0], [1., 1.0]], 2), ) def test_evaluate_invalid_argument_exception_raised(self, error_msg, ground_truth, predictions, grid_size): with self.assertRaisesRegexp((tf.errors.InvalidArgumentError, ValueError), error_msg): self.evaluate( intersection_over_union.evaluate(ground_truth, predictions, grid_size)) @parameterized.parameters( ("Not all batch dimensions are broadcast-compatible.", (1, 5, 3), (4, 3)), ("Not all batch dimensions are broadcast-compatible.", (3, 4), (2, 4, 5)), ) def test_evaluate_shape_exception_raised(self, error_msg, *shape): """Tests that the shape exception is raised.""" self.assert_exception_is_raised(intersection_over_union.evaluate, error_msg, shape) @parameterized.parameters( ((1, 5, 3), (2, 5, 1)), ((None, 2, 6), (4, 2, None)), ((3, 5, 8, 2), (3, 1, 1, 2)), ) def test_evaluate_shape_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(intersection_over_union.evaluate, shapes) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/representation/mesh/normals.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow utility functions to compute normals on meshes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.representation import triangle from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def gather_faces(vertices, indices, name=None): """Gather corresponding vertices for each face. Note: In the following, A1 to An are optional batch dimensions. Args: vertices: A tensor of shape `[A1, ..., An, V, D]`, where `V` is the number of vertices and `D` the dimensionality of each vertex. The rank of this tensor should be at least 2. indices: A tensor of shape `[A1, ..., An, F, M]`, where `F` is the number of faces, and `M` is the number of vertices per face. The rank of this tensor should be at least 2. name: A name for this op. Defaults to "normals_gather_faces". Returns: A tensor of shape `[A1, ..., An, F, M, D]` containing the vertices of each face. Raises: ValueError: If the shape of `vertices` or `indices` is not supported. """ with tf.compat.v1.name_scope(name, "normals_gather_faces", [vertices, indices]): vertices = tf.convert_to_tensor(value=vertices) indices = tf.convert_to_tensor(value=indices) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1) shape.check_static( tensor=indices, tensor_name="indices", has_rank_greater_than=1) shape.compare_batch_dimensions( tensors=(vertices, indices), last_axes=(-3, -3), broadcast_compatible=False) if hasattr(tf, "batch_gather"): expanded_vertices = tf.expand_dims(vertices, axis=-3) broadcasted_shape = tf.concat([tf.shape(input=indices)[:-1], tf.shape(input=vertices)[-2:]], axis=-1) broadcasted_vertices = tf.broadcast_to( expanded_vertices, broadcasted_shape) return tf.compat.v1.batch_gather(broadcasted_vertices, indices) else: return tf.gather( vertices, indices, axis=-2, batch_dims=indices.shape.ndims - 2) def face_normals(faces, clockwise=True, normalize=True, name=None): """Computes face normals for meshes. This function supports planar convex polygon faces. Note that for non-triangular faces, this function uses the first 3 vertices of each face to calculate the face normal. Note: In the following, A1 to An are optional batch dimensions. Args: faces: A tensor of shape `[A1, ..., An, M, 3]`, which stores vertices positions of each face, where M is the number of vertices of each face. The rank of this tensor should be at least 2. clockwise: Winding order to determine front-facing faces. The order of vertices should be either clockwise or counterclockwise. normalize: A `bool` defining whether output normals are normalized. name: A name for this op. Defaults to "normals_face_normals". Returns: A tensor of shape `[A1, ..., An, 3]` containing the face normals. Raises: ValueError: If the shape of `vertices`, `faces` is not supported. """ with tf.compat.v1.name_scope(name, "normals_face_normals", [faces]): faces = tf.convert_to_tensor(value=faces) shape.check_static( tensor=faces, tensor_name="faces", has_rank_greater_than=1, has_dim_equals=(-1, 3), has_dim_greater_than=(-2, 2)) vertices = tf.unstack(faces, axis=-2) vertices = vertices[:3] return triangle.normal(*vertices, clockwise=clockwise, normalize=normalize) def vertex_normals(vertices, indices, clockwise=True, name=None): """Computes vertex normals from a mesh. This function computes vertex normals as the weighted sum of the adjacent face normals, where the weights correspond to the area of each face. This function supports planar convex polygon faces. For non-triangular meshes, this function converts them into triangular meshes to calculate vertex normals. Note: In the following, A1 to An are optional batch dimensions. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]`, where V is the number of vertices. indices: A tensor of shape `[A1, ..., An, F, M]`, where F is the number of faces and M is the number of vertices per face. clockwise: Winding order to determine front-facing faces. The order of vertices should be either clockwise or counterclockwise. name: A name for this op. Defaults to "normals_vertex_normals". Returns: A tensor of shape `[A1, ..., An, V, 3]` containing vertex normals. If vertices and indices have different batch dimensions, this function broadcasts them into the same batch dimensions and the output batch dimensions are the broadcasted. Raises: ValueError: If the shape of `vertices`, `indices` is not supported. """ with tf.compat.v1.name_scope(name, "normals_vertex_normals", [vertices, indices]): vertices = tf.convert_to_tensor(value=vertices) indices = tf.convert_to_tensor(value=indices) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1, has_dim_equals=(-1, 3)) shape.check_static( tensor=indices, tensor_name="indices", has_rank_greater_than=1, has_dim_greater_than=(-1, 2)) shape.compare_batch_dimensions( tensors=(vertices, indices), last_axes=(-3, -3), broadcast_compatible=True) shape_indices = indices.shape.as_list() if None in shape_indices[:-2]: raise ValueError("'indices' must have specified batch dimensions.") common_batch_dims = shape.get_broadcasted_shape(vertices.shape[:-2], indices.shape[:-2]) vertices_repeat = [ common_batch_dims[x] // vertices.shape.as_list()[x] for x in range(len(common_batch_dims)) ] indices_repeat = [ common_batch_dims[x] // shape_indices[x] for x in range(len(common_batch_dims)) ] vertices = tf.tile( vertices, vertices_repeat + [1, 1], name="vertices_broadcast") indices = tf.tile( indices, indices_repeat + [1, 1], name="indices_broadcast") # Triangulate non-triangular faces. if shape_indices[-1] > 3: triangle_indices = [] for i in range(1, shape_indices[-1] - 1): triangle_indices.append( tf.concat((indices[..., 0:1], indices[..., i:i + 2]), axis=-1)) indices = tf.concat(triangle_indices, axis=-2) shape_indices = indices.shape.as_list() face_vertices = gather_faces(vertices, indices) # Use unnormalized face normals to scale normals by area. mesh_face_normals = face_normals( face_vertices, clockwise=clockwise, normalize=False) if vertices.shape.ndims > 2: outer_indices = np.meshgrid( *[np.arange(i) for i in shape_indices[:-2]], sparse=False, indexing="ij") outer_indices = [np.expand_dims(i, axis=-1) for i in outer_indices] outer_indices = np.concatenate(outer_indices, axis=-1) outer_indices = np.expand_dims(outer_indices, axis=-2) outer_indices = tf.constant(outer_indices, dtype=tf.int32) outer_indices = tf.tile(outer_indices, [1] * len(shape_indices[:-2]) + [tf.shape(input=indices)[-2]] + [1]) unnormalized_vertex_normals = tf.zeros_like(vertices) for i in range(shape_indices[-1]): scatter_indices = tf.concat([outer_indices, indices[..., i:i + 1]], axis=-1) unnormalized_vertex_normals = tf.compat.v1.tensor_scatter_add( unnormalized_vertex_normals, scatter_indices, mesh_face_normals) else: unnormalized_vertex_normals = tf.zeros_like(vertices) for i in range(shape_indices[-1]): unnormalized_vertex_normals = tf.compat.v1.tensor_scatter_add( unnormalized_vertex_normals, indices[..., i:i + 1], mesh_face_normals) vector_norms = tf.sqrt( tf.reduce_sum( input_tensor=unnormalized_vertex_normals**2, axis=-1, keepdims=True)) return safe_ops.safe_unsigned_div(unnormalized_vertex_normals, vector_norms) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow utility functions to compute normals on meshes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.representation import triangle from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def gather_faces(vertices, indices, name=None): """Gather corresponding vertices for each face. Note: In the following, A1 to An are optional batch dimensions. Args: vertices: A tensor of shape `[A1, ..., An, V, D]`, where `V` is the number of vertices and `D` the dimensionality of each vertex. The rank of this tensor should be at least 2. indices: A tensor of shape `[A1, ..., An, F, M]`, where `F` is the number of faces, and `M` is the number of vertices per face. The rank of this tensor should be at least 2. name: A name for this op. Defaults to "normals_gather_faces". Returns: A tensor of shape `[A1, ..., An, F, M, D]` containing the vertices of each face. Raises: ValueError: If the shape of `vertices` or `indices` is not supported. """ with tf.compat.v1.name_scope(name, "normals_gather_faces", [vertices, indices]): vertices = tf.convert_to_tensor(value=vertices) indices = tf.convert_to_tensor(value=indices) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1) shape.check_static( tensor=indices, tensor_name="indices", has_rank_greater_than=1) shape.compare_batch_dimensions( tensors=(vertices, indices), last_axes=(-3, -3), broadcast_compatible=False) if hasattr(tf, "batch_gather"): expanded_vertices = tf.expand_dims(vertices, axis=-3) broadcasted_shape = tf.concat([tf.shape(input=indices)[:-1], tf.shape(input=vertices)[-2:]], axis=-1) broadcasted_vertices = tf.broadcast_to( expanded_vertices, broadcasted_shape) return tf.compat.v1.batch_gather(broadcasted_vertices, indices) else: return tf.gather( vertices, indices, axis=-2, batch_dims=indices.shape.ndims - 2) def face_normals(faces, clockwise=True, normalize=True, name=None): """Computes face normals for meshes. This function supports planar convex polygon faces. Note that for non-triangular faces, this function uses the first 3 vertices of each face to calculate the face normal. Note: In the following, A1 to An are optional batch dimensions. Args: faces: A tensor of shape `[A1, ..., An, M, 3]`, which stores vertices positions of each face, where M is the number of vertices of each face. The rank of this tensor should be at least 2. clockwise: Winding order to determine front-facing faces. The order of vertices should be either clockwise or counterclockwise. normalize: A `bool` defining whether output normals are normalized. name: A name for this op. Defaults to "normals_face_normals". Returns: A tensor of shape `[A1, ..., An, 3]` containing the face normals. Raises: ValueError: If the shape of `vertices`, `faces` is not supported. """ with tf.compat.v1.name_scope(name, "normals_face_normals", [faces]): faces = tf.convert_to_tensor(value=faces) shape.check_static( tensor=faces, tensor_name="faces", has_rank_greater_than=1, has_dim_equals=(-1, 3), has_dim_greater_than=(-2, 2)) vertices = tf.unstack(faces, axis=-2) vertices = vertices[:3] return triangle.normal(*vertices, clockwise=clockwise, normalize=normalize) def vertex_normals(vertices, indices, clockwise=True, name=None): """Computes vertex normals from a mesh. This function computes vertex normals as the weighted sum of the adjacent face normals, where the weights correspond to the area of each face. This function supports planar convex polygon faces. For non-triangular meshes, this function converts them into triangular meshes to calculate vertex normals. Note: In the following, A1 to An are optional batch dimensions. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]`, where V is the number of vertices. indices: A tensor of shape `[A1, ..., An, F, M]`, where F is the number of faces and M is the number of vertices per face. clockwise: Winding order to determine front-facing faces. The order of vertices should be either clockwise or counterclockwise. name: A name for this op. Defaults to "normals_vertex_normals". Returns: A tensor of shape `[A1, ..., An, V, 3]` containing vertex normals. If vertices and indices have different batch dimensions, this function broadcasts them into the same batch dimensions and the output batch dimensions are the broadcasted. Raises: ValueError: If the shape of `vertices`, `indices` is not supported. """ with tf.compat.v1.name_scope(name, "normals_vertex_normals", [vertices, indices]): vertices = tf.convert_to_tensor(value=vertices) indices = tf.convert_to_tensor(value=indices) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1, has_dim_equals=(-1, 3)) shape.check_static( tensor=indices, tensor_name="indices", has_rank_greater_than=1, has_dim_greater_than=(-1, 2)) shape.compare_batch_dimensions( tensors=(vertices, indices), last_axes=(-3, -3), broadcast_compatible=True) shape_indices = indices.shape.as_list() if None in shape_indices[:-2]: raise ValueError("'indices' must have specified batch dimensions.") common_batch_dims = shape.get_broadcasted_shape(vertices.shape[:-2], indices.shape[:-2]) vertices_repeat = [ common_batch_dims[x] // vertices.shape.as_list()[x] for x in range(len(common_batch_dims)) ] indices_repeat = [ common_batch_dims[x] // shape_indices[x] for x in range(len(common_batch_dims)) ] vertices = tf.tile( vertices, vertices_repeat + [1, 1], name="vertices_broadcast") indices = tf.tile( indices, indices_repeat + [1, 1], name="indices_broadcast") # Triangulate non-triangular faces. if shape_indices[-1] > 3: triangle_indices = [] for i in range(1, shape_indices[-1] - 1): triangle_indices.append( tf.concat((indices[..., 0:1], indices[..., i:i + 2]), axis=-1)) indices = tf.concat(triangle_indices, axis=-2) shape_indices = indices.shape.as_list() face_vertices = gather_faces(vertices, indices) # Use unnormalized face normals to scale normals by area. mesh_face_normals = face_normals( face_vertices, clockwise=clockwise, normalize=False) if vertices.shape.ndims > 2: outer_indices = np.meshgrid( *[np.arange(i) for i in shape_indices[:-2]], sparse=False, indexing="ij") outer_indices = [np.expand_dims(i, axis=-1) for i in outer_indices] outer_indices = np.concatenate(outer_indices, axis=-1) outer_indices = np.expand_dims(outer_indices, axis=-2) outer_indices = tf.constant(outer_indices, dtype=tf.int32) outer_indices = tf.tile(outer_indices, [1] * len(shape_indices[:-2]) + [tf.shape(input=indices)[-2]] + [1]) unnormalized_vertex_normals = tf.zeros_like(vertices) for i in range(shape_indices[-1]): scatter_indices = tf.concat([outer_indices, indices[..., i:i + 1]], axis=-1) unnormalized_vertex_normals = tf.compat.v1.tensor_scatter_add( unnormalized_vertex_normals, scatter_indices, mesh_face_normals) else: unnormalized_vertex_normals = tf.zeros_like(vertices) for i in range(shape_indices[-1]): unnormalized_vertex_normals = tf.compat.v1.tensor_scatter_add( unnormalized_vertex_normals, indices[..., i:i + 1], mesh_face_normals) vector_norms = tf.sqrt( tf.reduce_sum( input_tensor=unnormalized_vertex_normals**2, axis=-1, keepdims=True)) return safe_ops.safe_unsigned_div(unnormalized_vertex_normals, vector_norms) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/rendering/camera/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/projects/pointnet/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """PointNet module."""
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """PointNet module."""
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/image/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/rendering/opengl/rasterization_backend.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """OpenGL rasterization backend for TF Graphics.""" import tensorflow as tf from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape # pylint: disable=g-import-not-at-top try: from tensorflow_graphics.rendering.opengl import gen_rasterizer_op as render_ops except ImportError: import os dir_path = os.path.dirname(os.path.abspath(__file__)) render_ops = tf.load_op_library(os.path.join(dir_path, "rasterizer_op.so")) # pylint: enable=g-import-not-at-top def _dim_value(dim): return 1 if dim is None else tf.compat.v1.dimension_value(dim) # Empty vertex shader; all the work happens in the geometry shader. vertex_shader = """ #version 430 void main() { } """ # Geometry shader that projects the vertices of visible triangles onto the image # plane. geometry_shader = """ #version 430 uniform mat4 view_projection_matrix; layout(points) in; layout(triangle_strip, max_vertices=3) out; out layout(location = 0) vec2 barycentric_coordinates; out layout(location = 1) float triangle_index; layout(binding=0) buffer triangular_mesh { float mesh_buffer[]; }; vec3 get_vertex_position(int vertex_index) { // Triangles are packed as 3 consecuitve vertices, each with 3 coordinates. int offset = gl_PrimitiveIDIn * 9 + vertex_index * 3; return vec3(mesh_buffer[offset], mesh_buffer[offset + 1], mesh_buffer[offset + 2]); } void main() { vec3 positions[3] = {get_vertex_position(0), get_vertex_position(1), get_vertex_position(2)}; vec4 projected_vertices[3] = { view_projection_matrix * vec4(positions[0], 1.0), view_projection_matrix * vec4(positions[1], 1.0), view_projection_matrix * vec4(positions[2], 1.0)}; for (int i = 0; i < 3; ++i) { // gl_Position is a pre-defined size 4 output variable. gl_Position = projected_vertices[i]; barycentric_coordinates = vec2(i==0 ? 1.0 : 0.0, i==1 ? 1.0 : 0.0); triangle_index = gl_PrimitiveIDIn; EmitVertex(); } EndPrimitive(); } """ # Fragment shader that packs barycentric coordinates, and triangle index. fragment_shader = """ #version 430 in layout(location = 0) vec2 barycentric_coordinates; in layout(location = 1) float triangle_index; out vec4 output_color; void main() { output_color = vec4(round(triangle_index + 1.0), barycentric_coordinates, 1.0); } """ def rasterize(vertices, triangles, view_projection_matrices, image_size, name=None): """Rasterizes the scene. This rasterizer estimates which triangle is associated with each pixel using OpenGL. Note: In the following, A1 to An are optional batch dimensions which must be broadcast compatible for inputs `vertices` and `view_projection_matrices`. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]` containing batches of `V` vertices, each defined by a 3D point. triangles: A tensor of shape `[T, 3]` containing `T` triangles, each associated with 3 vertices from `scene_vertices` view_projection_matrices: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of view projection matrices image_size: An tuple of integers (width, height) containing the dimensions in pixels of the rasterized image. name: A name for this op. Defaults to 'rasterization_backend_rasterize'. Returns: A tuple of 3 elements. The first one of shape `[A1, ..., An, H, W, 1]` representing the triangle index associated with each pixel. If no triangle is associated to a pixel, the index is set to -1. The second element in the tuple is of shape `[A1, ..., An, H, W, 3]` and correspond to barycentric coordinates per pixel. The last element in the tuple is of shape `[A1, ..., An, H, W]` and stores a value of `0` of the pixel is assciated with the background, and `1` with the foreground. """ with tf.compat.v1.name_scope(name, "rasterization_backend_rasterize", (vertices, triangles, view_projection_matrices)): vertices = tf.convert_to_tensor(value=vertices) triangles = tf.convert_to_tensor(value=triangles) view_projection_matrices = tf.convert_to_tensor( value=view_projection_matrices) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1, has_dim_equals=((-1, 3))) shape.check_static( tensor=triangles, tensor_name="triangles", has_rank=2, has_dim_equals=((-1, 3))) shape.check_static( tensor=view_projection_matrices, tensor_name="view_projection_matrices", has_rank_greater_than=1, has_dim_equals=((-1, 4), (-2, 4))) shape.compare_batch_dimensions( tensors=(vertices, view_projection_matrices), tensor_names=("vertices", "view_projection_matrices"), last_axes=(-3, -3), broadcast_compatible=True) common_batch_shape = shape.get_broadcasted_shape( vertices.shape[:-2], view_projection_matrices.shape[:-2]) common_batch_shape = [_dim_value(dim) for dim in common_batch_shape] vertices = tf.broadcast_to(vertices, common_batch_shape + vertices.shape[-2:]) view_projection_matrices = tf.broadcast_to(view_projection_matrices, common_batch_shape + [4, 4]) geometry = tf.gather(vertices, triangles, axis=-2) rasterized = render_ops.rasterize( num_points=geometry.shape[-3], alpha_clear=0.0, enable_cull_face=True, variable_names=("view_projection_matrix", "triangular_mesh"), variable_kinds=("mat", "buffer"), variable_values=(view_projection_matrices, tf.reshape(geometry, shape=common_batch_shape + [-1])), output_resolution=image_size, vertex_shader=vertex_shader, geometry_shader=geometry_shader, fragment_shader=fragment_shader) triangle_index = tf.cast(rasterized[..., 0], tf.int32) - 1 barycentric_coordinates = rasterized[..., 1:3] barycentric_coordinates = tf.concat( (barycentric_coordinates, 1.0 - barycentric_coordinates[..., 0:1] - barycentric_coordinates[..., 1:2]), axis=-1) mask = tf.cast(rasterized[..., 3], tf.int32) return triangle_index, barycentric_coordinates, mask # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """OpenGL rasterization backend for TF Graphics.""" import tensorflow as tf from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape # pylint: disable=g-import-not-at-top try: from tensorflow_graphics.rendering.opengl import gen_rasterizer_op as render_ops except ImportError: import os dir_path = os.path.dirname(os.path.abspath(__file__)) render_ops = tf.load_op_library(os.path.join(dir_path, "rasterizer_op.so")) # pylint: enable=g-import-not-at-top def _dim_value(dim): return 1 if dim is None else tf.compat.v1.dimension_value(dim) # Empty vertex shader; all the work happens in the geometry shader. vertex_shader = """ #version 430 void main() { } """ # Geometry shader that projects the vertices of visible triangles onto the image # plane. geometry_shader = """ #version 430 uniform mat4 view_projection_matrix; layout(points) in; layout(triangle_strip, max_vertices=3) out; out layout(location = 0) vec2 barycentric_coordinates; out layout(location = 1) float triangle_index; layout(binding=0) buffer triangular_mesh { float mesh_buffer[]; }; vec3 get_vertex_position(int vertex_index) { // Triangles are packed as 3 consecuitve vertices, each with 3 coordinates. int offset = gl_PrimitiveIDIn * 9 + vertex_index * 3; return vec3(mesh_buffer[offset], mesh_buffer[offset + 1], mesh_buffer[offset + 2]); } void main() { vec3 positions[3] = {get_vertex_position(0), get_vertex_position(1), get_vertex_position(2)}; vec4 projected_vertices[3] = { view_projection_matrix * vec4(positions[0], 1.0), view_projection_matrix * vec4(positions[1], 1.0), view_projection_matrix * vec4(positions[2], 1.0)}; for (int i = 0; i < 3; ++i) { // gl_Position is a pre-defined size 4 output variable. gl_Position = projected_vertices[i]; barycentric_coordinates = vec2(i==0 ? 1.0 : 0.0, i==1 ? 1.0 : 0.0); triangle_index = gl_PrimitiveIDIn; EmitVertex(); } EndPrimitive(); } """ # Fragment shader that packs barycentric coordinates, and triangle index. fragment_shader = """ #version 430 in layout(location = 0) vec2 barycentric_coordinates; in layout(location = 1) float triangle_index; out vec4 output_color; void main() { output_color = vec4(round(triangle_index + 1.0), barycentric_coordinates, 1.0); } """ def rasterize(vertices, triangles, view_projection_matrices, image_size, name=None): """Rasterizes the scene. This rasterizer estimates which triangle is associated with each pixel using OpenGL. Note: In the following, A1 to An are optional batch dimensions which must be broadcast compatible for inputs `vertices` and `view_projection_matrices`. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]` containing batches of `V` vertices, each defined by a 3D point. triangles: A tensor of shape `[T, 3]` containing `T` triangles, each associated with 3 vertices from `scene_vertices` view_projection_matrices: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of view projection matrices image_size: An tuple of integers (width, height) containing the dimensions in pixels of the rasterized image. name: A name for this op. Defaults to 'rasterization_backend_rasterize'. Returns: A tuple of 3 elements. The first one of shape `[A1, ..., An, H, W, 1]` representing the triangle index associated with each pixel. If no triangle is associated to a pixel, the index is set to -1. The second element in the tuple is of shape `[A1, ..., An, H, W, 3]` and correspond to barycentric coordinates per pixel. The last element in the tuple is of shape `[A1, ..., An, H, W]` and stores a value of `0` of the pixel is assciated with the background, and `1` with the foreground. """ with tf.compat.v1.name_scope(name, "rasterization_backend_rasterize", (vertices, triangles, view_projection_matrices)): vertices = tf.convert_to_tensor(value=vertices) triangles = tf.convert_to_tensor(value=triangles) view_projection_matrices = tf.convert_to_tensor( value=view_projection_matrices) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1, has_dim_equals=((-1, 3))) shape.check_static( tensor=triangles, tensor_name="triangles", has_rank=2, has_dim_equals=((-1, 3))) shape.check_static( tensor=view_projection_matrices, tensor_name="view_projection_matrices", has_rank_greater_than=1, has_dim_equals=((-1, 4), (-2, 4))) shape.compare_batch_dimensions( tensors=(vertices, view_projection_matrices), tensor_names=("vertices", "view_projection_matrices"), last_axes=(-3, -3), broadcast_compatible=True) common_batch_shape = shape.get_broadcasted_shape( vertices.shape[:-2], view_projection_matrices.shape[:-2]) common_batch_shape = [_dim_value(dim) for dim in common_batch_shape] vertices = tf.broadcast_to(vertices, common_batch_shape + vertices.shape[-2:]) view_projection_matrices = tf.broadcast_to(view_projection_matrices, common_batch_shape + [4, 4]) geometry = tf.gather(vertices, triangles, axis=-2) rasterized = render_ops.rasterize( num_points=geometry.shape[-3], alpha_clear=0.0, enable_cull_face=True, variable_names=("view_projection_matrix", "triangular_mesh"), variable_kinds=("mat", "buffer"), variable_values=(view_projection_matrices, tf.reshape(geometry, shape=common_batch_shape + [-1])), output_resolution=image_size, vertex_shader=vertex_shader, geometry_shader=geometry_shader, fragment_shader=fragment_shader) triangle_index = tf.cast(rasterized[..., 0], tf.int32) - 1 barycentric_coordinates = rasterized[..., 1:3] barycentric_coordinates = tf.concat( (barycentric_coordinates, 1.0 - barycentric_coordinates[..., 0:1] - barycentric_coordinates[..., 1:2]), axis=-1) mask = tf.cast(rasterized[..., 3], tf.int32) return triangle_index, barycentric_coordinates, mask # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/nn/loss/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/rendering/triangle_rasterizer.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements a differentiable rasterizer of triangular meshes. The resulting rendering contains perspective-correct interpolation of attributes defined at the vertices of the rasterized meshes. This rasterizer does not provide gradients through visibility, but it does through visible geometry and attributes. """ import tensorflow as tf from tensorflow_graphics.rendering import rasterization_backend from tensorflow_graphics.rendering.opengl import math as glm from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def _perspective_correct_barycentrics(vertices_per_pixel, model_to_eye_matrix, perspective_matrix, image_size_float): """Creates the pixels grid and computes barycentrics.""" # Construct the pixel grid with half-integer pixel centers. width = image_size_float[1] height = image_size_float[0] px = tf.linspace(0.5, width - 0.5, num=int(width)) py = tf.linspace(0.5, height - 0.5, num=int(height)) xv, yv = tf.meshgrid(px, py) pixel_position = tf.stack((xv, yv), axis=-1) return glm.perspective_correct_barycentrics(vertices_per_pixel, pixel_position, model_to_eye_matrix, perspective_matrix, (width, height)) def _perspective_correct_attributes(attribute, barycentrics, triangles, triangle_index, len_batch_shape): attribute = tf.gather(attribute, triangles, axis=-2) attribute_per_pixel = tf.gather( attribute, triangle_index, axis=-3, batch_dims=len_batch_shape) return glm.interpolate_attributes(attribute_per_pixel, barycentrics) def _dim_value(dim): return 1 if dim is None else tf.compat.v1.dimension_value(dim) def rasterize(vertices, triangles, attributes, model_to_eye_matrix, perspective_matrix, image_size, backend=rasterization_backend.RasterizationBackends.OPENGL, name=None): """Rasterizes the scene. Note: In the following, A1 to An are optional batch dimensions. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]` containing batches of `V` vertices, each defined by a 3D point. triangles: A tensor of shape `[T, 3]` containing `T` triangles, each associated with 3 vertices from `vertices`. attributes: A dictionary of tensors, each of shape `[A1, ..., An, V, K_a]` containing batches of `V` vertices, each associated with K-dimensional attributes. K_a may vary by attribute. model_to_eye_matrix: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of matrices used to transform vertices from model to eye coordinates. perspective_matrix: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of matrices used to project vertices from eye to clip coordinates. image_size: A tuple (height, width) containing the dimensions in pixels of the rasterized image. backend: A rasterization_backend.RasterizationBackends enum containing the backend method to use for rasterization. name: A name for this op. Defaults to 'triangle_rasterizer_rasterize'. Returns: A dictionary. The key "mask" is of shape `[A1, ..., An, height, width]` and stores a value of `0` of the pixel is assciated with the background, and `1` with the foreground. The key "barycentrics" is of shape `[A1, ..., An, height, width, 3]` and stores barycentric weights. Finally, the dictionary contains perspective correct interpolated attributes of shape `[A1, ..., An, height, width, K]` per entry in the `attributes` dictionary. """ with tf.compat.v1.name_scope(name, "triangle_rasterizer_rasterize", (vertices, triangles, attributes, model_to_eye_matrix, perspective_matrix)): vertices = tf.convert_to_tensor(value=vertices) triangles = tf.convert_to_tensor(value=triangles) model_to_eye_matrix = tf.convert_to_tensor(value=model_to_eye_matrix) perspective_matrix = tf.convert_to_tensor(value=perspective_matrix) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1, has_dim_equals=((-1, 3))) shape.check_static( tensor=triangles, tensor_name="triangles", has_rank=2, has_dim_equals=((-1, 3))) shape.check_static( tensor=model_to_eye_matrix, tensor_name="model_to_eye_matrix", has_dim_equals=(((-2, 4), (-1, 4)))) shape.check_static( tensor=perspective_matrix, tensor_name="perspective_matrix", has_dim_equals=(((-2, 4), (-1, 4)))) image_size_float = (float(image_size[0]), float(image_size[1])) image_size_backend = (int(image_size[1]), int(image_size[0])) view_projection_matrix = tf.linalg.matmul(perspective_matrix, model_to_eye_matrix) triangle_index, _, mask = rasterization_backend.rasterize( vertices, triangles, view_projection_matrix, image_size_backend, backend) outputs = {"mask": mask, "triangle_indices": triangle_index} batch_shape = triangle_index.shape[:-3] batch_shape = [_dim_value(dim) for dim in batch_shape] vertices = tf.gather(vertices, triangles, axis=-2) # Gather does not work on negative indices, which is the case for the pixel # associated to the background. triangle_index = triangle_index * mask vertices_per_pixel = tf.gather( vertices, triangle_index, axis=-3, batch_dims=len(batch_shape)) barycentrics = _perspective_correct_barycentrics(vertices_per_pixel, model_to_eye_matrix, perspective_matrix, image_size_float) mask_float = tf.cast(tf.expand_dims(mask, axis=-1), vertices.dtype) outputs["barycentrics"] = mask_float * barycentrics for key, attribute in attributes.items(): attribute = tf.convert_to_tensor(value=attribute) outputs[key] = mask_float * _perspective_correct_attributes( attribute, barycentrics, triangles, triangle_index, len(batch_shape)) return outputs # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements a differentiable rasterizer of triangular meshes. The resulting rendering contains perspective-correct interpolation of attributes defined at the vertices of the rasterized meshes. This rasterizer does not provide gradients through visibility, but it does through visible geometry and attributes. """ import tensorflow as tf from tensorflow_graphics.rendering import rasterization_backend from tensorflow_graphics.rendering.opengl import math as glm from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def _perspective_correct_barycentrics(vertices_per_pixel, model_to_eye_matrix, perspective_matrix, image_size_float): """Creates the pixels grid and computes barycentrics.""" # Construct the pixel grid with half-integer pixel centers. width = image_size_float[1] height = image_size_float[0] px = tf.linspace(0.5, width - 0.5, num=int(width)) py = tf.linspace(0.5, height - 0.5, num=int(height)) xv, yv = tf.meshgrid(px, py) pixel_position = tf.stack((xv, yv), axis=-1) return glm.perspective_correct_barycentrics(vertices_per_pixel, pixel_position, model_to_eye_matrix, perspective_matrix, (width, height)) def _perspective_correct_attributes(attribute, barycentrics, triangles, triangle_index, len_batch_shape): attribute = tf.gather(attribute, triangles, axis=-2) attribute_per_pixel = tf.gather( attribute, triangle_index, axis=-3, batch_dims=len_batch_shape) return glm.interpolate_attributes(attribute_per_pixel, barycentrics) def _dim_value(dim): return 1 if dim is None else tf.compat.v1.dimension_value(dim) def rasterize(vertices, triangles, attributes, model_to_eye_matrix, perspective_matrix, image_size, backend=rasterization_backend.RasterizationBackends.OPENGL, name=None): """Rasterizes the scene. Note: In the following, A1 to An are optional batch dimensions. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]` containing batches of `V` vertices, each defined by a 3D point. triangles: A tensor of shape `[T, 3]` containing `T` triangles, each associated with 3 vertices from `vertices`. attributes: A dictionary of tensors, each of shape `[A1, ..., An, V, K_a]` containing batches of `V` vertices, each associated with K-dimensional attributes. K_a may vary by attribute. model_to_eye_matrix: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of matrices used to transform vertices from model to eye coordinates. perspective_matrix: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of matrices used to project vertices from eye to clip coordinates. image_size: A tuple (height, width) containing the dimensions in pixels of the rasterized image. backend: A rasterization_backend.RasterizationBackends enum containing the backend method to use for rasterization. name: A name for this op. Defaults to 'triangle_rasterizer_rasterize'. Returns: A dictionary. The key "mask" is of shape `[A1, ..., An, height, width]` and stores a value of `0` of the pixel is assciated with the background, and `1` with the foreground. The key "barycentrics" is of shape `[A1, ..., An, height, width, 3]` and stores barycentric weights. Finally, the dictionary contains perspective correct interpolated attributes of shape `[A1, ..., An, height, width, K]` per entry in the `attributes` dictionary. """ with tf.compat.v1.name_scope(name, "triangle_rasterizer_rasterize", (vertices, triangles, attributes, model_to_eye_matrix, perspective_matrix)): vertices = tf.convert_to_tensor(value=vertices) triangles = tf.convert_to_tensor(value=triangles) model_to_eye_matrix = tf.convert_to_tensor(value=model_to_eye_matrix) perspective_matrix = tf.convert_to_tensor(value=perspective_matrix) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1, has_dim_equals=((-1, 3))) shape.check_static( tensor=triangles, tensor_name="triangles", has_rank=2, has_dim_equals=((-1, 3))) shape.check_static( tensor=model_to_eye_matrix, tensor_name="model_to_eye_matrix", has_dim_equals=(((-2, 4), (-1, 4)))) shape.check_static( tensor=perspective_matrix, tensor_name="perspective_matrix", has_dim_equals=(((-2, 4), (-1, 4)))) image_size_float = (float(image_size[0]), float(image_size[1])) image_size_backend = (int(image_size[1]), int(image_size[0])) view_projection_matrix = tf.linalg.matmul(perspective_matrix, model_to_eye_matrix) triangle_index, _, mask = rasterization_backend.rasterize( vertices, triangles, view_projection_matrix, image_size_backend, backend) outputs = {"mask": mask, "triangle_indices": triangle_index} batch_shape = triangle_index.shape[:-3] batch_shape = [_dim_value(dim) for dim in batch_shape] vertices = tf.gather(vertices, triangles, axis=-2) # Gather does not work on negative indices, which is the case for the pixel # associated to the background. triangle_index = triangle_index * mask vertices_per_pixel = tf.gather( vertices, triangle_index, axis=-3, batch_dims=len(batch_shape)) barycentrics = _perspective_correct_barycentrics(vertices_per_pixel, model_to_eye_matrix, perspective_matrix, image_size_float) mask_float = tf.cast(tf.expand_dims(mask, axis=-1), vertices.dtype) outputs["barycentrics"] = mask_float * barycentrics for key, attribute in attributes.items(): attribute = tf.convert_to_tensor(value=attribute) outputs[key] = mask_float * _perspective_correct_attributes( attribute, barycentrics, triangles, triangle_index, len(batch_shape)) return outputs # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/datasets/pix3d/pix3d_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for the Pix3D dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow_datasets.public_api as tfds from tensorflow_graphics.datasets import pix3d class Pix3dTest(tfds.testing.DatasetBuilderTestCase): """Test Cases for Pix3D Dataset implementation.""" DATASET_CLASS = pix3d.Pix3d SPLITS = { 'train': 2, # Number of fake train example 'test': 1, # Number of fake test example } DL_EXTRACT_RESULT = '' EXAMPLE_DIR = os.path.join(os.path.dirname(__file__), 'fakes') MOCK_OUT_FORBIDDEN_OS_FUNCTIONS = False # SKIP_CHECKSUMS = True def setUp(self): # pylint: disable=invalid-name super(Pix3dTest, self).setUp() self.builder.TRAIN_SPLIT_IDX = os.path.join(self.EXAMPLE_DIR, 'pix3d_train.npy') self.builder.TEST_SPLIT_IDX = os.path.join(self.EXAMPLE_DIR, 'pix3d_test.npy') if __name__ == '__main__': tfds.testing.test_main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for the Pix3D dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow_datasets.public_api as tfds from tensorflow_graphics.datasets import pix3d class Pix3dTest(tfds.testing.DatasetBuilderTestCase): """Test Cases for Pix3D Dataset implementation.""" DATASET_CLASS = pix3d.Pix3d SPLITS = { 'train': 2, # Number of fake train example 'test': 1, # Number of fake test example } DL_EXTRACT_RESULT = '' EXAMPLE_DIR = os.path.join(os.path.dirname(__file__), 'fakes') MOCK_OUT_FORBIDDEN_OS_FUNCTIONS = False # SKIP_CHECKSUMS = True def setUp(self): # pylint: disable=invalid-name super(Pix3dTest, self).setUp() self.builder.TRAIN_SPLIT_IDX = os.path.join(self.EXAMPLE_DIR, 'pix3d_train.npy') self.builder.TEST_SPLIT_IDX = os.path.join(self.EXAMPLE_DIR, 'pix3d_test.npy') if __name__ == '__main__': tfds.testing.test_main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/rendering/camera/tests/orthographic_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for orthographic camera functionalities.""" from absl.testing import parameterized import numpy as np from tensorflow_graphics.rendering.camera import orthographic from tensorflow_graphics.util import test_case class OrthographicTest(test_case.TestCase): @parameterized.parameters( ((3,),), ((None, 3),), ) def test_project_exception_not_exception_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(orthographic.project, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (1,)), ("must have exactly 3 dimensions in axis -1", (2,)), ("must have exactly 3 dimensions in axis -1", (4,)), ) def test_project_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(orthographic.project, error_msg, shape) def test_project_jacobian_random(self): """Test the Jacobian of the project function.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() point_3d_init = np.random.uniform(size=tensor_shape + [3]) self.assert_jacobian_is_correct_fn(orthographic.project, [point_3d_init]) def test_project_random(self): """Test the project function using random 3d points.""" point_3d = np.random.uniform(size=(100, 3)) pred = orthographic.project(point_3d) self.assertAllEqual(pred, point_3d[:, 0:2]) @parameterized.parameters( ((2,),), ((None, 2),), ) def test_ray_exception_not_exception_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(orthographic.ray, shapes) @parameterized.parameters( ("must have exactly 2 dimensions in axis -1", (1,)), ("must have exactly 2 dimensions in axis -1", (3,)), ) def test_ray_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(orthographic.ray, error_msg, shape) def test_ray_jacobian_random(self): """Test the Jacobian of the ray function.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() point_2d_init = np.random.uniform(size=tensor_shape + [2]) self.assert_jacobian_is_correct_fn(orthographic.ray, [point_2d_init]) def test_ray_random(self): """Test the ray function using random 2d points.""" point_2d = np.random.uniform(size=(100, 2)) pred = orthographic.ray(point_2d) gt = np.tile((0.0, 0.0, 1.0), (100, 1)) self.assertAllEqual(pred, gt) @parameterized.parameters( ((2,), (1,)), ((None, 2), (None, 1)), ((2, 2), (2, 1)), ) def test_unproject_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(orthographic.unproject, shapes) @parameterized.parameters( ("must have exactly 2 dimensions in axis -1", (1,), (1,)), ("must have exactly 2 dimensions in axis -1", (3,), (1,)), ("must have exactly 1 dimensions in axis -1", (2,), (2,)), ("Not all batch dimensions are identical.", (3, 2), (2, 1)), ) def test_unproject_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(orthographic.unproject, error_msg, shape) def test_unproject_jacobian_random(self): """Test the Jacobian of the unproject function.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() point_2d_init = np.random.uniform(size=tensor_shape + [2]) depth_init = np.random.uniform(size=tensor_shape + [1]) self.assert_jacobian_is_correct_fn(orthographic.unproject, [point_2d_init, depth_init]) def test_unproject_random(self): """Test the unproject function using random 2d points.""" point_2d = np.random.uniform(size=(100, 2)) depth = np.random.uniform(size=(100, 1)) pred = orthographic.unproject(point_2d, depth) self.assertAllEqual(pred[:, 0:2], point_2d) self.assertAllEqual(pred[:, 2], np.squeeze(depth)) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for orthographic camera functionalities.""" from absl.testing import parameterized import numpy as np from tensorflow_graphics.rendering.camera import orthographic from tensorflow_graphics.util import test_case class OrthographicTest(test_case.TestCase): @parameterized.parameters( ((3,),), ((None, 3),), ) def test_project_exception_not_exception_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(orthographic.project, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (1,)), ("must have exactly 3 dimensions in axis -1", (2,)), ("must have exactly 3 dimensions in axis -1", (4,)), ) def test_project_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(orthographic.project, error_msg, shape) def test_project_jacobian_random(self): """Test the Jacobian of the project function.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() point_3d_init = np.random.uniform(size=tensor_shape + [3]) self.assert_jacobian_is_correct_fn(orthographic.project, [point_3d_init]) def test_project_random(self): """Test the project function using random 3d points.""" point_3d = np.random.uniform(size=(100, 3)) pred = orthographic.project(point_3d) self.assertAllEqual(pred, point_3d[:, 0:2]) @parameterized.parameters( ((2,),), ((None, 2),), ) def test_ray_exception_not_exception_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(orthographic.ray, shapes) @parameterized.parameters( ("must have exactly 2 dimensions in axis -1", (1,)), ("must have exactly 2 dimensions in axis -1", (3,)), ) def test_ray_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(orthographic.ray, error_msg, shape) def test_ray_jacobian_random(self): """Test the Jacobian of the ray function.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() point_2d_init = np.random.uniform(size=tensor_shape + [2]) self.assert_jacobian_is_correct_fn(orthographic.ray, [point_2d_init]) def test_ray_random(self): """Test the ray function using random 2d points.""" point_2d = np.random.uniform(size=(100, 2)) pred = orthographic.ray(point_2d) gt = np.tile((0.0, 0.0, 1.0), (100, 1)) self.assertAllEqual(pred, gt) @parameterized.parameters( ((2,), (1,)), ((None, 2), (None, 1)), ((2, 2), (2, 1)), ) def test_unproject_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(orthographic.unproject, shapes) @parameterized.parameters( ("must have exactly 2 dimensions in axis -1", (1,), (1,)), ("must have exactly 2 dimensions in axis -1", (3,), (1,)), ("must have exactly 1 dimensions in axis -1", (2,), (2,)), ("Not all batch dimensions are identical.", (3, 2), (2, 1)), ) def test_unproject_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(orthographic.unproject, error_msg, shape) def test_unproject_jacobian_random(self): """Test the Jacobian of the unproject function.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() point_2d_init = np.random.uniform(size=tensor_shape + [2]) depth_init = np.random.uniform(size=tensor_shape + [1]) self.assert_jacobian_is_correct_fn(orthographic.unproject, [point_2d_init, depth_init]) def test_unproject_random(self): """Test the unproject function using random 2d points.""" point_2d = np.random.uniform(size=(100, 2)) depth = np.random.uniform(size=(100, 1)) pred = orthographic.unproject(point_2d, depth) self.assertAllEqual(pred[:, 0:2], point_2d) self.assertAllEqual(pred[:, 2], np.squeeze(depth)) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/projects/pointnet/train_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests of pointnet module.""" import importlib import sys import tempfile import tensorflow_datasets as tfds from tensorflow_graphics.datasets import testing from tensorflow_graphics.util import test_case class TrainTest(test_case.TestCase): def test_train(self): batch_size = 8 with tfds.testing.mock_data(batch_size * 2, data_dir=testing.DATA_DIR): with tempfile.TemporaryDirectory() as logdir: # yapf: disable sys.argv = [ "train.py", "--num_epochs", "2", "--assert_gpu", "False", "--ev_every", "1", "--tb_every", "1", "--logdir", logdir, "--batch_size", str(batch_size), ] # yapf: enable importlib.import_module("tensorflow_graphics.projects.pointnet.train") if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests of pointnet module.""" import importlib import sys import tempfile import tensorflow_datasets as tfds from tensorflow_graphics.datasets import testing from tensorflow_graphics.util import test_case class TrainTest(test_case.TestCase): def test_train(self): batch_size = 8 with tfds.testing.mock_data(batch_size * 2, data_dir=testing.DATA_DIR): with tempfile.TemporaryDirectory() as logdir: # yapf: disable sys.argv = [ "train.py", "--num_epochs", "2", "--assert_gpu", "False", "--ev_every", "1", "--tb_every", "1", "--logdir", logdir, "--batch_size", str(batch_size), ] # yapf: enable importlib.import_module("tensorflow_graphics.projects.pointnet.train") if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/datasets/features/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """`tensorflow_graphics.datasets.features` API defining feature types.""" from tensorflow_graphics.datasets.features.camera_feature import Camera from tensorflow_graphics.datasets.features.pose_feature import Pose from tensorflow_graphics.datasets.features.trimesh_feature import TriangleMesh from tensorflow_graphics.datasets.features.voxel_feature import VoxelGrid __all__ = [ "TriangleMesh", "VoxelGrid", "Camera", "Pose" ]
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """`tensorflow_graphics.datasets.features` API defining feature types.""" from tensorflow_graphics.datasets.features.camera_feature import Camera from tensorflow_graphics.datasets.features.pose_feature import Pose from tensorflow_graphics.datasets.features.trimesh_feature import TriangleMesh from tensorflow_graphics.datasets.features.voxel_feature import VoxelGrid __all__ = [ "TriangleMesh", "VoxelGrid", "Camera", "Pose" ]
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/projects/local_implicit_grid/core/point_utils.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Additional data utilities for point preprocessing. """ import numpy as np from plyfile import PlyData from plyfile import PlyElement def read_point_ply(filename): """Load point cloud from ply file. Args: filename: str, filename for ply file to load. Returns: v: np.array of shape [#v, 3], vertex coordinates n: np.array of shape [#v, 3], vertex normals """ pd = PlyData.read(filename)['vertex'] v = np.array(np.stack([pd[i] for i in ['x', 'y', 'z']], axis=-1)) n = np.array(np.stack([pd[i] for i in ['nx', 'ny', 'nz']], axis=-1)) return v, n def write_point_ply(filename, v, n): """Write point cloud to ply file. Args: filename: str, filename for ply file to load. v: np.array of shape [#v, 3], vertex coordinates n: np.array of shape [#v, 3], vertex normals """ vn = np.concatenate([v, n], axis=1) vn = [tuple(vn[i]) for i in range(vn.shape[0])] vn = np.array(vn, dtype=[('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4')]) el = PlyElement.describe(vn, 'vertex') PlyData([el]).write(filename) def np_pad_points(points, ntarget): """Pad point cloud to required size. If number of points is larger than ntarget, take ntarget random samples. If number of points is smaller than ntarget, pad by repeating last point. Args: points: `[npoints, nchannel]` np array, where first 3 channels are xyz. ntarget: int, number of target channels. Returns: result: `[ntarget, nchannel]` np array, padded points to ntarget numbers. """ if points.shape[0] < ntarget: mult = np.ceil(float(ntarget)/float(points.shape[0])) - 1 rand_pool = np.tile(points, [int(mult), 1]) nextra = ntarget-points.shape[0] extra_idx = np.random.choice(rand_pool.shape[0], nextra, replace=False) extra_pts = rand_pool[extra_idx] points_out = np.concatenate([points, extra_pts], axis=0) else: idx_choice = np.random.choice(points.shape[0], size=ntarget, replace=False) points_out = points[idx_choice] return points_out def np_gather_ijk_index(arr, index): arr_flat = arr.reshape(-1, arr.shape[-1]) _, j, k, _ = arr.shape index_transform = index[:, 0]*j*k+index[:, 1]*k+index[:, 2] return arr_flat[index_transform] def np_shifted_crop(v, idx_grid, shift, crop_size, ntarget): """Create a shifted crop.""" nchannel = v.shape[1] vxyz = v[:, :3] - shift * crop_size * 0.5 vall = v.copy() point_idxs = np.arange(v.shape[0]) point_grid_idx = np.floor(vxyz / crop_size).astype(np.int32) valid_mask = np.ones(point_grid_idx.shape[0]).astype(np.bool) for i in range(3): valid_mask = np.logical_and(valid_mask, point_grid_idx[:, i] >= 0) valid_mask = np.logical_and(valid_mask, point_grid_idx[:, i] < idx_grid.shape[i]) point_grid_idx = point_grid_idx[valid_mask] # translate to global grid index point_grid_idx = np_gather_ijk_index(idx_grid, point_grid_idx) vall = vall[valid_mask] point_idxs = point_idxs[valid_mask] crop_indices, revidx = np.unique(point_grid_idx, axis=0, return_inverse=True) ncrops = crop_indices.shape[0] sortarr = np.argsort(revidx) revidx_sorted = revidx[sortarr] vall_sorted = vall[sortarr] point_idxs_sorted = point_idxs[sortarr] bins = np.searchsorted(revidx_sorted, np.arange(ncrops)) bins = list(bins) + [v.shape[0]] sid = bins[0:-1] eid = bins[1:] # initialize outputs point_crops = np.zeros([ncrops, ntarget, nchannel]) crop_point_idxs = [] # extract crops and pad for i, (s, e) in enumerate(zip(sid, eid)): cropped_points = vall_sorted[s:e] crop_point_idx = point_idxs_sorted[s:e] crop_point_idxs.append(crop_point_idx) if cropped_points.shape[0] < ntarget: padded_points = np_pad_points(cropped_points, ntarget=ntarget) else: choice_idx = np.random.choice(cropped_points.shape[0], ntarget, replace=False) padded_points = cropped_points[choice_idx] point_crops[i] = padded_points return point_crops, crop_indices, crop_point_idxs def np_get_occupied_idx(v, xmin=(0., 0., 0.), xmax=(1., 1., 1.), crop_size=.125, ntarget=2048, overlap=True, normalize_crops=False, return_shape=False, return_crop_point_idxs=False): """Get crop indices for point clouds.""" v = v.copy()-xmin xmin = np.array(xmin) xmax = np.array(xmax) r = (xmax-xmin)/crop_size r = np.ceil(r) rr = r.astype(np.int32) if not overlap else (2*r-1).astype(np.int32) # create index grid idx_grid = np.stack(np.meshgrid(np.arange(rr[0]), np.arange(rr[1]), np.arange(rr[2]), indexing='ij'), axis=-1) # [rr[0], rr[1], rr[2], 3] shift_idxs = np.stack( np.meshgrid(np.arange(int(overlap)+1), np.arange(int(overlap)+1), np.arange(int(overlap)+1), indexing='ij'), axis=-1) shift_idxs = np.reshape(shift_idxs, [-1, 3]) point_crops = [] crop_indices = [] crop_point_idxs = [] for i in range(shift_idxs.shape[0]): sft = shift_idxs[i] skp = int(overlap)+1 idg = idx_grid[sft[0]::skp, sft[1]::skp, sft[2]::skp] pc, ci, cpidx = np_shifted_crop(v, idg, sft, crop_size=crop_size, ntarget=ntarget) point_crops.append(pc) crop_indices.append(ci) crop_point_idxs += cpidx point_crops = np.concatenate(point_crops, axis=0) # [ncrops, nsurface, 6] crop_indices = np.concatenate(crop_indices, axis=0) # [ncrops, 3] if normalize_crops: # normalize each crop crop_corners = crop_indices * 0.5 * crop_size crop_centers = crop_corners + 0.5 * crop_size # [ncrops, 3] crop_centers = crop_centers[:, np.newaxis, :] # [ncrops, 1, 3] point_crops[..., :3] = point_crops[..., :3] -crop_centers point_crops[..., :3] = point_crops[..., :3] / crop_size * 2 outputs = [point_crops, crop_indices] if return_shape: outputs += [idx_grid.shape[:3]] if return_crop_point_idxs: outputs += [crop_point_idxs] return tuple(outputs)
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Additional data utilities for point preprocessing. """ import numpy as np from plyfile import PlyData from plyfile import PlyElement def read_point_ply(filename): """Load point cloud from ply file. Args: filename: str, filename for ply file to load. Returns: v: np.array of shape [#v, 3], vertex coordinates n: np.array of shape [#v, 3], vertex normals """ pd = PlyData.read(filename)['vertex'] v = np.array(np.stack([pd[i] for i in ['x', 'y', 'z']], axis=-1)) n = np.array(np.stack([pd[i] for i in ['nx', 'ny', 'nz']], axis=-1)) return v, n def write_point_ply(filename, v, n): """Write point cloud to ply file. Args: filename: str, filename for ply file to load. v: np.array of shape [#v, 3], vertex coordinates n: np.array of shape [#v, 3], vertex normals """ vn = np.concatenate([v, n], axis=1) vn = [tuple(vn[i]) for i in range(vn.shape[0])] vn = np.array(vn, dtype=[('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4')]) el = PlyElement.describe(vn, 'vertex') PlyData([el]).write(filename) def np_pad_points(points, ntarget): """Pad point cloud to required size. If number of points is larger than ntarget, take ntarget random samples. If number of points is smaller than ntarget, pad by repeating last point. Args: points: `[npoints, nchannel]` np array, where first 3 channels are xyz. ntarget: int, number of target channels. Returns: result: `[ntarget, nchannel]` np array, padded points to ntarget numbers. """ if points.shape[0] < ntarget: mult = np.ceil(float(ntarget)/float(points.shape[0])) - 1 rand_pool = np.tile(points, [int(mult), 1]) nextra = ntarget-points.shape[0] extra_idx = np.random.choice(rand_pool.shape[0], nextra, replace=False) extra_pts = rand_pool[extra_idx] points_out = np.concatenate([points, extra_pts], axis=0) else: idx_choice = np.random.choice(points.shape[0], size=ntarget, replace=False) points_out = points[idx_choice] return points_out def np_gather_ijk_index(arr, index): arr_flat = arr.reshape(-1, arr.shape[-1]) _, j, k, _ = arr.shape index_transform = index[:, 0]*j*k+index[:, 1]*k+index[:, 2] return arr_flat[index_transform] def np_shifted_crop(v, idx_grid, shift, crop_size, ntarget): """Create a shifted crop.""" nchannel = v.shape[1] vxyz = v[:, :3] - shift * crop_size * 0.5 vall = v.copy() point_idxs = np.arange(v.shape[0]) point_grid_idx = np.floor(vxyz / crop_size).astype(np.int32) valid_mask = np.ones(point_grid_idx.shape[0]).astype(np.bool) for i in range(3): valid_mask = np.logical_and(valid_mask, point_grid_idx[:, i] >= 0) valid_mask = np.logical_and(valid_mask, point_grid_idx[:, i] < idx_grid.shape[i]) point_grid_idx = point_grid_idx[valid_mask] # translate to global grid index point_grid_idx = np_gather_ijk_index(idx_grid, point_grid_idx) vall = vall[valid_mask] point_idxs = point_idxs[valid_mask] crop_indices, revidx = np.unique(point_grid_idx, axis=0, return_inverse=True) ncrops = crop_indices.shape[0] sortarr = np.argsort(revidx) revidx_sorted = revidx[sortarr] vall_sorted = vall[sortarr] point_idxs_sorted = point_idxs[sortarr] bins = np.searchsorted(revidx_sorted, np.arange(ncrops)) bins = list(bins) + [v.shape[0]] sid = bins[0:-1] eid = bins[1:] # initialize outputs point_crops = np.zeros([ncrops, ntarget, nchannel]) crop_point_idxs = [] # extract crops and pad for i, (s, e) in enumerate(zip(sid, eid)): cropped_points = vall_sorted[s:e] crop_point_idx = point_idxs_sorted[s:e] crop_point_idxs.append(crop_point_idx) if cropped_points.shape[0] < ntarget: padded_points = np_pad_points(cropped_points, ntarget=ntarget) else: choice_idx = np.random.choice(cropped_points.shape[0], ntarget, replace=False) padded_points = cropped_points[choice_idx] point_crops[i] = padded_points return point_crops, crop_indices, crop_point_idxs def np_get_occupied_idx(v, xmin=(0., 0., 0.), xmax=(1., 1., 1.), crop_size=.125, ntarget=2048, overlap=True, normalize_crops=False, return_shape=False, return_crop_point_idxs=False): """Get crop indices for point clouds.""" v = v.copy()-xmin xmin = np.array(xmin) xmax = np.array(xmax) r = (xmax-xmin)/crop_size r = np.ceil(r) rr = r.astype(np.int32) if not overlap else (2*r-1).astype(np.int32) # create index grid idx_grid = np.stack(np.meshgrid(np.arange(rr[0]), np.arange(rr[1]), np.arange(rr[2]), indexing='ij'), axis=-1) # [rr[0], rr[1], rr[2], 3] shift_idxs = np.stack( np.meshgrid(np.arange(int(overlap)+1), np.arange(int(overlap)+1), np.arange(int(overlap)+1), indexing='ij'), axis=-1) shift_idxs = np.reshape(shift_idxs, [-1, 3]) point_crops = [] crop_indices = [] crop_point_idxs = [] for i in range(shift_idxs.shape[0]): sft = shift_idxs[i] skp = int(overlap)+1 idg = idx_grid[sft[0]::skp, sft[1]::skp, sft[2]::skp] pc, ci, cpidx = np_shifted_crop(v, idg, sft, crop_size=crop_size, ntarget=ntarget) point_crops.append(pc) crop_indices.append(ci) crop_point_idxs += cpidx point_crops = np.concatenate(point_crops, axis=0) # [ncrops, nsurface, 6] crop_indices = np.concatenate(crop_indices, axis=0) # [ncrops, 3] if normalize_crops: # normalize each crop crop_corners = crop_indices * 0.5 * crop_size crop_centers = crop_corners + 0.5 * crop_size # [ncrops, 3] crop_centers = crop_centers[:, np.newaxis, :] # [ncrops, 1, 3] point_crops[..., :3] = point_crops[..., :3] -crop_centers point_crops[..., :3] = point_crops[..., :3] / crop_size * 2 outputs = [point_crops, crop_indices] if return_shape: outputs += [idx_grid.shape[:3]] if return_crop_point_idxs: outputs += [crop_point_idxs] return tuple(outputs)
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/representation/mesh/utils.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements utility functions for meshes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np def extract_unique_edges_from_triangular_mesh(faces, directed_edges=False): """Extracts all the unique edges using the faces of a mesh. Args: faces: A numpy.ndarray of shape [T, 3], where T is the number of triangular faces in the mesh. Each entry in this array describes the index of a vertex in the mesh. directed_edges: A boolean flag, whether to treat an edge as directed or undirected. If (i, j) is an edge in the mesh and directed_edges is True, then both (i, j) and (j, i) are returned in the list of edges. If (i, j) is an edge in the mesh and directed_edges is False, then one of (i, j) or (j, i) is returned. Returns: A numpy.ndarray of shape [E, 2], where E is the number of edges in the mesh. For eg: given faces = [[0, 1, 2], [0, 1, 3]], then for directed_edges = False, one valid output is [[0, 1], [0, 2], [0, 3], [1, 2], [3, 1]] for directed_edges = True, one valid output is [[0, 1], [0, 2], [0, 3], [1, 0], [1, 2], [1, 3], [2, 0], [2, 1], [3, 0], [3, 1]] Raises: ValueError: If `faces` is not a numpy.ndarray or if its shape is not supported. """ if not isinstance(faces, np.ndarray): raise ValueError("'faces' must be a numpy.ndarray.") faces_shape = faces.shape faces_rank = len(faces_shape) if faces_rank != 2: raise ValueError( "'faces' must have a rank equal to 2, but it has rank {} and shape {}." .format(faces_rank, faces_shape)) if faces_shape[1] != 3: raise ValueError( "'faces' must have exactly 3 dimensions in the last axis, but it has {}" " dimensions and is of shape {}.".format(faces_shape[1], faces_shape)) edges = np.concatenate([faces[:, 0:2], faces[:, 1:3], faces[:, [2, 0]]], axis=0) if directed_edges: edges = np.concatenate([edges, np.flip(edges, axis=-1)]) unique_edges = np.unique(edges, axis=0) return unique_edges def get_degree_based_edge_weights(edges, dtype=np.float32): r"""Computes vertex degree based weights for edges of a mesh. The degree (valence) of a vertex is number of edges incident on the vertex. The weight for an edge $w_{ij}$ connecting vertex $v_i$ and vertex $v_j$ is defined as, $$ w_{ij} = 1.0 / degree(v_i) \sum_{j} w_{ij} = 1 $$ Args: edges: A numpy.ndarray of shape [E, 2], where E is the number of directed edges in the mesh. dtype: A numpy float data type. The output weights are of data type dtype. Returns: weights: A dtype numpy.ndarray of shape [E,] denoting edge weights. Raises: ValueError: If `edges` is not a numpy.ndarray or if its shape is not supported, or dtype is not a float type. """ if not isinstance(dtype(1), np.floating): raise ValueError("'dtype' must be a numpy float type.") if not isinstance(edges, np.ndarray): raise ValueError("'edges' must be a numpy.ndarray.") edges_shape = edges.shape edges_rank = len(edges_shape) if edges_rank != 2: raise ValueError( "'edges' must have a rank equal to 2, but it has rank {} and shape {}." .format(edges_rank, edges_shape)) if edges_shape[1] != 2: raise ValueError( "'edges' must have exactly 2 dimensions in the last axis, but it has {}" " dimensions and is of shape {}.".format(edges_shape[1], edges_shape)) degree = np.bincount(edges[:, 0]) rep_degree = degree[edges[:, 0]] weights = 1.0 / rep_degree.astype(dtype) return weights # API contains all public functions and classes. __all__ = []
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements utility functions for meshes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np def extract_unique_edges_from_triangular_mesh(faces, directed_edges=False): """Extracts all the unique edges using the faces of a mesh. Args: faces: A numpy.ndarray of shape [T, 3], where T is the number of triangular faces in the mesh. Each entry in this array describes the index of a vertex in the mesh. directed_edges: A boolean flag, whether to treat an edge as directed or undirected. If (i, j) is an edge in the mesh and directed_edges is True, then both (i, j) and (j, i) are returned in the list of edges. If (i, j) is an edge in the mesh and directed_edges is False, then one of (i, j) or (j, i) is returned. Returns: A numpy.ndarray of shape [E, 2], where E is the number of edges in the mesh. For eg: given faces = [[0, 1, 2], [0, 1, 3]], then for directed_edges = False, one valid output is [[0, 1], [0, 2], [0, 3], [1, 2], [3, 1]] for directed_edges = True, one valid output is [[0, 1], [0, 2], [0, 3], [1, 0], [1, 2], [1, 3], [2, 0], [2, 1], [3, 0], [3, 1]] Raises: ValueError: If `faces` is not a numpy.ndarray or if its shape is not supported. """ if not isinstance(faces, np.ndarray): raise ValueError("'faces' must be a numpy.ndarray.") faces_shape = faces.shape faces_rank = len(faces_shape) if faces_rank != 2: raise ValueError( "'faces' must have a rank equal to 2, but it has rank {} and shape {}." .format(faces_rank, faces_shape)) if faces_shape[1] != 3: raise ValueError( "'faces' must have exactly 3 dimensions in the last axis, but it has {}" " dimensions and is of shape {}.".format(faces_shape[1], faces_shape)) edges = np.concatenate([faces[:, 0:2], faces[:, 1:3], faces[:, [2, 0]]], axis=0) if directed_edges: edges = np.concatenate([edges, np.flip(edges, axis=-1)]) unique_edges = np.unique(edges, axis=0) return unique_edges def get_degree_based_edge_weights(edges, dtype=np.float32): r"""Computes vertex degree based weights for edges of a mesh. The degree (valence) of a vertex is number of edges incident on the vertex. The weight for an edge $w_{ij}$ connecting vertex $v_i$ and vertex $v_j$ is defined as, $$ w_{ij} = 1.0 / degree(v_i) \sum_{j} w_{ij} = 1 $$ Args: edges: A numpy.ndarray of shape [E, 2], where E is the number of directed edges in the mesh. dtype: A numpy float data type. The output weights are of data type dtype. Returns: weights: A dtype numpy.ndarray of shape [E,] denoting edge weights. Raises: ValueError: If `edges` is not a numpy.ndarray or if its shape is not supported, or dtype is not a float type. """ if not isinstance(dtype(1), np.floating): raise ValueError("'dtype' must be a numpy float type.") if not isinstance(edges, np.ndarray): raise ValueError("'edges' must be a numpy.ndarray.") edges_shape = edges.shape edges_rank = len(edges_shape) if edges_rank != 2: raise ValueError( "'edges' must have a rank equal to 2, but it has rank {} and shape {}." .format(edges_rank, edges_shape)) if edges_shape[1] != 2: raise ValueError( "'edges' must have exactly 2 dimensions in the last axis, but it has {}" " dimensions and is of shape {}.".format(edges_shape[1], edges_shape)) degree = np.bincount(edges[:, 0]) rep_degree = degree[edges[:, 0]] weights = 1.0 / rep_degree.astype(dtype) return weights # API contains all public functions and classes. __all__ = []
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/rendering/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Rendering module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=g-import-not-at-top from tensorflow_graphics.util.doc import _import_tfg_docs if _import_tfg_docs(): from tensorflow_graphics.rendering import camera from tensorflow_graphics.rendering import opengl from tensorflow_graphics.rendering import reflectance from tensorflow_graphics.rendering import voxels from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.rendering. __all__ = _export_api.get_modules() # pylint: enable=g-import-not-at-top
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Rendering module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=g-import-not-at-top from tensorflow_graphics.util.doc import _import_tfg_docs if _import_tfg_docs(): from tensorflow_graphics.rendering import camera from tensorflow_graphics.rendering import opengl from tensorflow_graphics.rendering import reflectance from tensorflow_graphics.rendering import voxels from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.rendering. __all__ = _export_api.get_modules() # pylint: enable=g-import-not-at-top
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/projects/nasa/train.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Training Loop.""" import numpy as np import tensorflow.compat.v1 as tf from tensorflow_graphics.projects.nasa.lib import datasets from tensorflow_graphics.projects.nasa.lib import models from tensorflow_graphics.projects.nasa.lib import utils tf.disable_eager_execution() flags = tf.app.flags logging = tf.logging tf.logging.set_verbosity(tf.logging.INFO) utils.define_flags() FLAGS = flags.FLAGS def main(unused_argv): tf.random.set_random_seed(20200823) np.random.seed(20200823) logging.info("=> Starting ...") # Select dataset. logging.info("=> Preparing datasets ...") input_fn = datasets.get_dataset("train", FLAGS) # Select model. logging.info("=> Creating {} model".format(FLAGS.model)) model_fn = models.get_model(FLAGS) # Set up training. logging.info("=> Setting up training ...") run_config = tf.estimator.RunConfig( model_dir=FLAGS.train_dir, save_checkpoints_steps=FLAGS.save_every, save_summary_steps=FLAGS.summary_every, keep_checkpoint_max=None, ) trainer = tf.estimator.Estimator( model_fn=model_fn, config=run_config, ) # Start training. logging.info("=> Training ...") trainer.train(input_fn=input_fn, max_steps=FLAGS.max_steps) if __name__ == "__main__": tf.app.run(main)
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Training Loop.""" import numpy as np import tensorflow.compat.v1 as tf from tensorflow_graphics.projects.nasa.lib import datasets from tensorflow_graphics.projects.nasa.lib import models from tensorflow_graphics.projects.nasa.lib import utils tf.disable_eager_execution() flags = tf.app.flags logging = tf.logging tf.logging.set_verbosity(tf.logging.INFO) utils.define_flags() FLAGS = flags.FLAGS def main(unused_argv): tf.random.set_random_seed(20200823) np.random.seed(20200823) logging.info("=> Starting ...") # Select dataset. logging.info("=> Preparing datasets ...") input_fn = datasets.get_dataset("train", FLAGS) # Select model. logging.info("=> Creating {} model".format(FLAGS.model)) model_fn = models.get_model(FLAGS) # Set up training. logging.info("=> Setting up training ...") run_config = tf.estimator.RunConfig( model_dir=FLAGS.train_dir, save_checkpoints_steps=FLAGS.save_every, save_summary_steps=FLAGS.summary_every, keep_checkpoint_max=None, ) trainer = tf.estimator.Estimator( model_fn=model_fn, config=run_config, ) # Start training. logging.info("=> Training ...") trainer.train(input_fn=input_fn, max_steps=FLAGS.max_steps) if __name__ == "__main__": tf.app.run(main)
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/rendering/reflectance/tests/phong_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for Phong reflectance.""" import math import sys from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.rendering.reflectance import phong from tensorflow_graphics.util import test_case class PhongTest(test_case.TestCase): @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_brdf_jacobian_random(self): """Tests the Jacobian of brdf.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() direction_incoming_light_init = np.random.uniform( -1.0, 1.0, size=tensor_shape + [3]) direction_outgoing_light_init = np.random.uniform( -1.0, 1.0, size=tensor_shape + [3]) surface_normal_init = np.random.uniform(-1.0, 1.0, size=tensor_shape + [3]) shininess_init = np.random.uniform(size=tensor_shape + [1]) albedo_init = np.random.random(tensor_shape + [3]) self.assert_jacobian_is_correct_fn( phong.brdf, [ direction_incoming_light_init, direction_outgoing_light_init, surface_normal_init, shininess_init, albedo_init ], atol=1e-5, delta=1e-9) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_brdf_jacobian_preset(self): delta = 1e-5 direction_incoming_light_init = np.array((delta, -1.0, 0.0)) direction_outgoing_light_init = np.array((delta, 1.0, 0.0)) surface_normal_init = np.array((1.0, 0.0, 0.0)) shininess_init = np.array((1.0,)) albedo_init = np.array((1.0, 1.0, 1.0)) self.assert_jacobian_is_correct_fn( phong.brdf, [ direction_incoming_light_init, direction_outgoing_light_init, surface_normal_init, shininess_init, albedo_init ], delta=delta / 10.0) @parameterized.parameters( (-1.0, 1.0, 1.0 / math.pi), (1.0, 1.0, 0.0), (-1.0, -1.0, 0.0), (1.0, -1.0, 0.0), ) def test_brdf_random(self, incoming_yz, outgoing_yz, ratio): tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() shininess = np.zeros(shape=tensor_shape + [1]) albedo = np.random.uniform(low=0.0, high=1.0, size=tensor_shape + [3]) direction_incoming_light = np.random.uniform( low=-1.0, high=1.0, size=tensor_shape + [3]) direction_outgoing_light = np.random.uniform( low=-1.0, high=1.0, size=tensor_shape + [3]) surface_normal = np.array((0.0, 1.0, 1.0)) direction_incoming_light[..., 1:3] = incoming_yz direction_outgoing_light[..., 1:3] = outgoing_yz direction_incoming_light = direction_incoming_light / np.linalg.norm( direction_incoming_light, axis=-1, keepdims=True) direction_outgoing_light = direction_outgoing_light / np.linalg.norm( direction_outgoing_light, axis=-1, keepdims=True) surface_normal = surface_normal / np.linalg.norm( surface_normal, axis=-1, keepdims=True) gt = albedo * ratio pred = phong.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo) self.assertAllClose(gt, pred) def test_brdf_exceptions_raised(self): """Tests that the exceptions are raised correctly.""" direction_incoming_light = np.random.uniform(-1.0, 1.0, size=(3,)) direction_outgoing_light = np.random.uniform(-1.0, 1.0, size=(3,)) surface_normal = np.random.uniform(-1.0, 1.0, size=(3,)) shininess = np.random.uniform(0.0, 1.0, size=(1,)) albedo = np.random.uniform(0.0, 1.0, (3,)) with self.subTest(name="assert_on_direction_incoming_light_not_normalized"): with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( phong.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo)) direction_incoming_light /= np.linalg.norm( direction_incoming_light, axis=-1) with self.subTest(name="assert_on_direction_outgoing_light_not_normalized"): with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( phong.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo)) direction_outgoing_light /= np.linalg.norm( direction_outgoing_light, axis=-1) with self.subTest(name="assert_on_surface_normal_not_normalized"): with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( phong.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo)) surface_normal /= np.linalg.norm(surface_normal, axis=-1) with self.subTest(name="assert_on_albedo_not_normalized"): albedo = np.random.uniform(-10.0, -sys.float_info.epsilon, (3,)) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( phong.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo)) albedo = np.random.uniform(sys.float_info.epsilon, 10.0, (3,)) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( phong.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo)) @parameterized.parameters( ((3,), (3,), (3,), (1,), (3,)), ((None, 3), (None, 3), (None, 3), (None, 1), (None, 3)), ((1, 3), (1, 3), (1, 3), (1, 1), (1, 3)), ((2, 3), (2, 3), (2, 3), (2, 1), (2, 3)), ((1, 3), (1, 2, 3), (1, 2, 1, 3), (1, 2, 1), (1, 3)), ((3,), (1, 3), (1, 2, 3), (1, 2, 2, 1), (1, 2, 2, 2, 3)), ((1, 2, 2, 2, 3), (1, 2, 2, 3), (1, 2, 3), (1, 1), (3,)), ) def test_brdf_shape_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(phong.brdf, shape) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (1,), (3,), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (2,), (3,), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (4,), (3,), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (1,), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (2,), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (4,), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (1,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (2,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (4,), (1,), (3,)), ("must have exactly 1 dimensions in axis -1", (3,), (3,), (3,), (2,), (3,)), ("must have exactly 1 dimensions in axis -1", (3,), (3,), (3,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (3,), (1,), (4,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (3,), (1,), (2,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (3,), (1,), (1,)), ("Not all batch dimensions are broadcast-compatible.", (2, 3), (3, 3), (3,), (1,), (3,)), ) def test_brdf_shape_exception_raised(self, error_msg, *shape): """Tests that the shape exception is raised.""" self.assert_exception_is_raised(phong.brdf, error_msg, shape) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for Phong reflectance.""" import math import sys from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.rendering.reflectance import phong from tensorflow_graphics.util import test_case class PhongTest(test_case.TestCase): @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_brdf_jacobian_random(self): """Tests the Jacobian of brdf.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() direction_incoming_light_init = np.random.uniform( -1.0, 1.0, size=tensor_shape + [3]) direction_outgoing_light_init = np.random.uniform( -1.0, 1.0, size=tensor_shape + [3]) surface_normal_init = np.random.uniform(-1.0, 1.0, size=tensor_shape + [3]) shininess_init = np.random.uniform(size=tensor_shape + [1]) albedo_init = np.random.random(tensor_shape + [3]) self.assert_jacobian_is_correct_fn( phong.brdf, [ direction_incoming_light_init, direction_outgoing_light_init, surface_normal_init, shininess_init, albedo_init ], atol=1e-5, delta=1e-9) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_brdf_jacobian_preset(self): delta = 1e-5 direction_incoming_light_init = np.array((delta, -1.0, 0.0)) direction_outgoing_light_init = np.array((delta, 1.0, 0.0)) surface_normal_init = np.array((1.0, 0.0, 0.0)) shininess_init = np.array((1.0,)) albedo_init = np.array((1.0, 1.0, 1.0)) self.assert_jacobian_is_correct_fn( phong.brdf, [ direction_incoming_light_init, direction_outgoing_light_init, surface_normal_init, shininess_init, albedo_init ], delta=delta / 10.0) @parameterized.parameters( (-1.0, 1.0, 1.0 / math.pi), (1.0, 1.0, 0.0), (-1.0, -1.0, 0.0), (1.0, -1.0, 0.0), ) def test_brdf_random(self, incoming_yz, outgoing_yz, ratio): tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() shininess = np.zeros(shape=tensor_shape + [1]) albedo = np.random.uniform(low=0.0, high=1.0, size=tensor_shape + [3]) direction_incoming_light = np.random.uniform( low=-1.0, high=1.0, size=tensor_shape + [3]) direction_outgoing_light = np.random.uniform( low=-1.0, high=1.0, size=tensor_shape + [3]) surface_normal = np.array((0.0, 1.0, 1.0)) direction_incoming_light[..., 1:3] = incoming_yz direction_outgoing_light[..., 1:3] = outgoing_yz direction_incoming_light = direction_incoming_light / np.linalg.norm( direction_incoming_light, axis=-1, keepdims=True) direction_outgoing_light = direction_outgoing_light / np.linalg.norm( direction_outgoing_light, axis=-1, keepdims=True) surface_normal = surface_normal / np.linalg.norm( surface_normal, axis=-1, keepdims=True) gt = albedo * ratio pred = phong.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo) self.assertAllClose(gt, pred) def test_brdf_exceptions_raised(self): """Tests that the exceptions are raised correctly.""" direction_incoming_light = np.random.uniform(-1.0, 1.0, size=(3,)) direction_outgoing_light = np.random.uniform(-1.0, 1.0, size=(3,)) surface_normal = np.random.uniform(-1.0, 1.0, size=(3,)) shininess = np.random.uniform(0.0, 1.0, size=(1,)) albedo = np.random.uniform(0.0, 1.0, (3,)) with self.subTest(name="assert_on_direction_incoming_light_not_normalized"): with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( phong.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo)) direction_incoming_light /= np.linalg.norm( direction_incoming_light, axis=-1) with self.subTest(name="assert_on_direction_outgoing_light_not_normalized"): with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( phong.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo)) direction_outgoing_light /= np.linalg.norm( direction_outgoing_light, axis=-1) with self.subTest(name="assert_on_surface_normal_not_normalized"): with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( phong.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo)) surface_normal /= np.linalg.norm(surface_normal, axis=-1) with self.subTest(name="assert_on_albedo_not_normalized"): albedo = np.random.uniform(-10.0, -sys.float_info.epsilon, (3,)) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( phong.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo)) albedo = np.random.uniform(sys.float_info.epsilon, 10.0, (3,)) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( phong.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo)) @parameterized.parameters( ((3,), (3,), (3,), (1,), (3,)), ((None, 3), (None, 3), (None, 3), (None, 1), (None, 3)), ((1, 3), (1, 3), (1, 3), (1, 1), (1, 3)), ((2, 3), (2, 3), (2, 3), (2, 1), (2, 3)), ((1, 3), (1, 2, 3), (1, 2, 1, 3), (1, 2, 1), (1, 3)), ((3,), (1, 3), (1, 2, 3), (1, 2, 2, 1), (1, 2, 2, 2, 3)), ((1, 2, 2, 2, 3), (1, 2, 2, 3), (1, 2, 3), (1, 1), (3,)), ) def test_brdf_shape_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(phong.brdf, shape) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (1,), (3,), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (2,), (3,), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (4,), (3,), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (1,), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (2,), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (4,), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (1,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (2,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (4,), (1,), (3,)), ("must have exactly 1 dimensions in axis -1", (3,), (3,), (3,), (2,), (3,)), ("must have exactly 1 dimensions in axis -1", (3,), (3,), (3,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (3,), (1,), (4,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (3,), (1,), (2,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (3,), (1,), (1,)), ("Not all batch dimensions are broadcast-compatible.", (2, 3), (3, 3), (3,), (1,), (3,)), ) def test_brdf_shape_exception_raised(self, error_msg, *shape): """Tests that the shape exception is raised.""" self.assert_exception_is_raised(phong.brdf, error_msg, shape) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/math/interpolation/slerp.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow.graphics slerp interpolation module. Spherical linear interpolation (slerp) is defined for both quaternions and for regular M-D vectors, and act slightly differently because of inherent ambiguity of quaternions. This module has two functions returning the interpolation weights for quaternions (quaternion_weights) and for vectors (vector_weights), which can then be used in a weighted sum to calculate the final interpolated quaternions and vectors. A helper interpolate function is also provided. The main differences between two methods are: vector_weights: can get any M-D tensor as input, does not expect normalized vectors as input, returns unnormalized outputs (in general) for unnormalized inputs. quaternion_weights: expects M-D tensors with a last dimension of 4, assumes normalized input, checks for ambiguity by looking at the angle between quaternions, returns normalized quaternions naturally. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import enum import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape class InterpolationType(enum.Enum): """Defines interpolation methods for slerp module.""" VECTOR = 0 QUATERNION = 1 def _safe_dot(vector1, vector2, eps): """Calculates dot product while ensuring it is in the range [-1, 1].""" dot_product = vector.dot(vector1, vector2) # Safely shrink to make sure machine precision does not cause the dot # product to be outside the [-1.0, 1.0] range. return safe_ops.safe_shrink( vector=dot_product, minval=-1.0, maxval=1.0, open_bounds=False, eps=eps) def interpolate(vector1, vector2, percent, method=InterpolationType.QUATERNION, eps=None, name=None): """Applies slerp to vectors or quaternions. Args: vector1: A tensor of shape `[A1, ... , An, M]`, which stores a normalized vector in its last dimension. vector2: A tensor of shape `[A1, ... , An, M]`, which stores a normalized vector in its last dimension. percent: A `float` or a tensor with shape broadcastable to the shape of input vectors. method: An enumerated constant from the class InterpolationType, which is either InterpolationType.QUATERNION (default) if the input vectors are 4-D quaternions, or InterpolationType.VECTOR if they are regular M-D vectors. eps: A small float for operation safety. If left None, its value is automatically selected using dtype of input vectors. name: A name for this op. Defaults to "vector_weights" or "quaternion_weights" depending on the method. Returns: A tensor of shape [A1, ... , An, M]` which stores the result of the interpolation. Raises: ValueError: if method is not amongst enumerated constants defined in InterpolationType. """ if method == InterpolationType.QUATERNION: weight1, weight2 = quaternion_weights( vector1, vector2, percent, eps=eps, name=name) elif method == InterpolationType.VECTOR: weight1, weight2 = vector_weights( vector1, vector2, percent, eps=eps, name=name) else: raise ValueError("Unknown interpolation type supplied.") return interpolate_with_weights(vector1, vector2, weight1, weight2) def interpolate_with_weights(vector1, vector2, weight1, weight2, name=None): """Interpolates vectors by taking their weighted sum. Interpolation for all variants of slerp is a simple weighted sum over inputs. Therefore this function simply returns weight1 * vector1 + weight2 * vector2. Note: In the following, A1 to An are optional batch dimensions. Args: vector1: A tensor of shape `[A1, ... , An, M]`, which stores a normalized vector in its last dimension. vector2: A tensor of shape `[A1, ... , An, M]`, which stores a normalized vector in its last dimension. weight1: A `float` or a tensor describing weights for the `vector1` and with a shape broadcastable to the shape of the input vectors. weight2: A `float` or a tensor describing weights for the `vector2` and with a shape broadcastable to the shape of the input vectors. name: A name for this op. Defaults to "interpolate_with_weights". Returns: A tensor of shape `[A1, ... , An, M]` containing the result of the interpolation. """ with tf.compat.v1.name_scope(name, "interpolate_with_weights", [vector1, vector2, weight1, weight2]): return weight1 * vector1 + weight2 * vector2 def quaternion_weights(quaternion1, quaternion2, percent, eps=None, name=None): """Calculates slerp weights for two normalized quaternions. Given a percent and two normalized quaternions, this function returns the slerp weights. It can also produce extrapolation weights when percent is outside of the [0, 1] range. It reduces to lerp when input quaternions are almost parallel or anti-parallel. Input quaternions are assumed to be normalized. The tf.graphics debug flag TFG_ADD_ASSERTS_TO_GRAPH defined in tfg_flags.py can be set to add assertions to the graph that check whether the inputs are normalized, and whether Inf or Nan values are produced. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion1: A tensor of shape `[A1, ... , An, 4]` storing normalized quaternions in its last dimension. quaternion2: A tensor of shape `[A1, ... , An, 4]` storing normalized quaternions in its last dimension. percent: A `float` or a tensor with a shape broadcastable to the shape `[A1, ... , An]`. eps: A `float` used to make operations safe. When left as None, the function automatically picks the best epsilon based on the dtype and the operation. name: A name for this op. Defaults to "quaternion_weights". Raises: ValueError: If the shapes of quaternions do not match, if the last dimensions of quaternions are not 4, or if percent is neither a float, nor a tensor with last dimension 1. Returns: Two tensors of shape `[A1, ... , An, 1]` each, which are the two slerp weights for each quaternion. """ with tf.compat.v1.name_scope(name, "quaternion_weights", [quaternion1, quaternion2, percent]): quaternion1 = tf.convert_to_tensor(value=quaternion1) quaternion2 = tf.convert_to_tensor(value=quaternion2) percent = tf.convert_to_tensor(value=percent, dtype=quaternion1.dtype) if percent.shape.ndims == 0: percent = tf.expand_dims(percent, axis=0) shape.check_static( tensor=quaternion1, tensor_name="quaternion1", has_dim_equals=(-1, 4)) shape.check_static( tensor=quaternion2, tensor_name="quaternion2", has_dim_equals=(-1, 4)) shape.compare_batch_dimensions( tensors=(quaternion1, quaternion2, percent), last_axes=(-2, -2, -1), broadcast_compatible=True, tensor_names=("quaternion1", "quaternion2", "percent")) quaternion1 = asserts.assert_normalized(quaternion1) quaternion2 = asserts.assert_normalized(quaternion2) dot_product = _safe_dot(quaternion1, quaternion2, eps) # Take the shorter path theta = tf.acos(tf.abs(dot_product)) # safe_sinpx_div_sinx returns p for very small x, which means slerp reduces # to lerp automatically. scale1 = safe_ops.safe_sinpx_div_sinx(theta, 1.0 - percent, eps) scale2 = safe_ops.safe_sinpx_div_sinx(theta, percent, eps) # Flip the sign of scale1 if quaternions are in different hemispheres. # tf.sign can make scale1 zero if quaternions are orthogonal. scale1 *= safe_ops.nonzero_sign(dot_product) return scale1, scale2 def vector_weights(vector1, vector2, percent, eps=None, name=None): """Spherical linear interpolation (slerp) between two unnormalized vectors. This function applies geometric slerp to unnormalized vectors by first normalizing them to return the interpolation weights. It reduces to lerp when input vectors are exactly anti-parallel. Note: In the following, A1 to An are optional batch dimensions. Args: vector1: A tensor of shape `[A1, ... , An, M]`, which stores a normalized vector in its last dimension. vector2: A tensor of shape `[A1, ... , An, M]`, which stores a normalized vector in its last dimension. percent: A `float` or tensor with shape broadcastable to the shape of input vectors. eps: A small float for operation safety. If left None, its value is automatically selected using dtype of input vectors. name: A name for this op. Defaults to "vector_weights". Raises: ValueError: if the shape of `vector1`, `vector2`, or `percent` is not supported. Returns: Two tensors of shape `[A1, ... , An, 1]`, representing interpolation weights for each input vector. """ with tf.compat.v1.name_scope(name, "vector_weights", [vector1, vector2, percent]): vector1 = tf.convert_to_tensor(value=vector1) vector2 = tf.convert_to_tensor(value=vector2) percent = tf.convert_to_tensor(value=percent, dtype=vector1.dtype) if percent.shape.ndims == 0: percent = tf.expand_dims(percent, axis=0) shape.compare_dimensions( tensors=(vector1, vector2), axes=-1, tensor_names=("vector1", "vector2")) shape.compare_batch_dimensions( tensors=(vector1, vector2, percent), last_axes=(-2, -2, -1), broadcast_compatible=True, tensor_names=("vector1", "vector2", "percent")) normalized1 = tf.nn.l2_normalize(vector1, axis=-1) normalized2 = tf.nn.l2_normalize(vector2, axis=-1) dot_product = _safe_dot(normalized1, normalized2, eps) theta = tf.acos(dot_product) scale1 = safe_ops.safe_sinpx_div_sinx(theta, 1.0 - percent, eps) scale2 = safe_ops.safe_sinpx_div_sinx(theta, percent, eps) return scale1, scale2 # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow.graphics slerp interpolation module. Spherical linear interpolation (slerp) is defined for both quaternions and for regular M-D vectors, and act slightly differently because of inherent ambiguity of quaternions. This module has two functions returning the interpolation weights for quaternions (quaternion_weights) and for vectors (vector_weights), which can then be used in a weighted sum to calculate the final interpolated quaternions and vectors. A helper interpolate function is also provided. The main differences between two methods are: vector_weights: can get any M-D tensor as input, does not expect normalized vectors as input, returns unnormalized outputs (in general) for unnormalized inputs. quaternion_weights: expects M-D tensors with a last dimension of 4, assumes normalized input, checks for ambiguity by looking at the angle between quaternions, returns normalized quaternions naturally. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import enum import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape class InterpolationType(enum.Enum): """Defines interpolation methods for slerp module.""" VECTOR = 0 QUATERNION = 1 def _safe_dot(vector1, vector2, eps): """Calculates dot product while ensuring it is in the range [-1, 1].""" dot_product = vector.dot(vector1, vector2) # Safely shrink to make sure machine precision does not cause the dot # product to be outside the [-1.0, 1.0] range. return safe_ops.safe_shrink( vector=dot_product, minval=-1.0, maxval=1.0, open_bounds=False, eps=eps) def interpolate(vector1, vector2, percent, method=InterpolationType.QUATERNION, eps=None, name=None): """Applies slerp to vectors or quaternions. Args: vector1: A tensor of shape `[A1, ... , An, M]`, which stores a normalized vector in its last dimension. vector2: A tensor of shape `[A1, ... , An, M]`, which stores a normalized vector in its last dimension. percent: A `float` or a tensor with shape broadcastable to the shape of input vectors. method: An enumerated constant from the class InterpolationType, which is either InterpolationType.QUATERNION (default) if the input vectors are 4-D quaternions, or InterpolationType.VECTOR if they are regular M-D vectors. eps: A small float for operation safety. If left None, its value is automatically selected using dtype of input vectors. name: A name for this op. Defaults to "vector_weights" or "quaternion_weights" depending on the method. Returns: A tensor of shape [A1, ... , An, M]` which stores the result of the interpolation. Raises: ValueError: if method is not amongst enumerated constants defined in InterpolationType. """ if method == InterpolationType.QUATERNION: weight1, weight2 = quaternion_weights( vector1, vector2, percent, eps=eps, name=name) elif method == InterpolationType.VECTOR: weight1, weight2 = vector_weights( vector1, vector2, percent, eps=eps, name=name) else: raise ValueError("Unknown interpolation type supplied.") return interpolate_with_weights(vector1, vector2, weight1, weight2) def interpolate_with_weights(vector1, vector2, weight1, weight2, name=None): """Interpolates vectors by taking their weighted sum. Interpolation for all variants of slerp is a simple weighted sum over inputs. Therefore this function simply returns weight1 * vector1 + weight2 * vector2. Note: In the following, A1 to An are optional batch dimensions. Args: vector1: A tensor of shape `[A1, ... , An, M]`, which stores a normalized vector in its last dimension. vector2: A tensor of shape `[A1, ... , An, M]`, which stores a normalized vector in its last dimension. weight1: A `float` or a tensor describing weights for the `vector1` and with a shape broadcastable to the shape of the input vectors. weight2: A `float` or a tensor describing weights for the `vector2` and with a shape broadcastable to the shape of the input vectors. name: A name for this op. Defaults to "interpolate_with_weights". Returns: A tensor of shape `[A1, ... , An, M]` containing the result of the interpolation. """ with tf.compat.v1.name_scope(name, "interpolate_with_weights", [vector1, vector2, weight1, weight2]): return weight1 * vector1 + weight2 * vector2 def quaternion_weights(quaternion1, quaternion2, percent, eps=None, name=None): """Calculates slerp weights for two normalized quaternions. Given a percent and two normalized quaternions, this function returns the slerp weights. It can also produce extrapolation weights when percent is outside of the [0, 1] range. It reduces to lerp when input quaternions are almost parallel or anti-parallel. Input quaternions are assumed to be normalized. The tf.graphics debug flag TFG_ADD_ASSERTS_TO_GRAPH defined in tfg_flags.py can be set to add assertions to the graph that check whether the inputs are normalized, and whether Inf or Nan values are produced. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion1: A tensor of shape `[A1, ... , An, 4]` storing normalized quaternions in its last dimension. quaternion2: A tensor of shape `[A1, ... , An, 4]` storing normalized quaternions in its last dimension. percent: A `float` or a tensor with a shape broadcastable to the shape `[A1, ... , An]`. eps: A `float` used to make operations safe. When left as None, the function automatically picks the best epsilon based on the dtype and the operation. name: A name for this op. Defaults to "quaternion_weights". Raises: ValueError: If the shapes of quaternions do not match, if the last dimensions of quaternions are not 4, or if percent is neither a float, nor a tensor with last dimension 1. Returns: Two tensors of shape `[A1, ... , An, 1]` each, which are the two slerp weights for each quaternion. """ with tf.compat.v1.name_scope(name, "quaternion_weights", [quaternion1, quaternion2, percent]): quaternion1 = tf.convert_to_tensor(value=quaternion1) quaternion2 = tf.convert_to_tensor(value=quaternion2) percent = tf.convert_to_tensor(value=percent, dtype=quaternion1.dtype) if percent.shape.ndims == 0: percent = tf.expand_dims(percent, axis=0) shape.check_static( tensor=quaternion1, tensor_name="quaternion1", has_dim_equals=(-1, 4)) shape.check_static( tensor=quaternion2, tensor_name="quaternion2", has_dim_equals=(-1, 4)) shape.compare_batch_dimensions( tensors=(quaternion1, quaternion2, percent), last_axes=(-2, -2, -1), broadcast_compatible=True, tensor_names=("quaternion1", "quaternion2", "percent")) quaternion1 = asserts.assert_normalized(quaternion1) quaternion2 = asserts.assert_normalized(quaternion2) dot_product = _safe_dot(quaternion1, quaternion2, eps) # Take the shorter path theta = tf.acos(tf.abs(dot_product)) # safe_sinpx_div_sinx returns p for very small x, which means slerp reduces # to lerp automatically. scale1 = safe_ops.safe_sinpx_div_sinx(theta, 1.0 - percent, eps) scale2 = safe_ops.safe_sinpx_div_sinx(theta, percent, eps) # Flip the sign of scale1 if quaternions are in different hemispheres. # tf.sign can make scale1 zero if quaternions are orthogonal. scale1 *= safe_ops.nonzero_sign(dot_product) return scale1, scale2 def vector_weights(vector1, vector2, percent, eps=None, name=None): """Spherical linear interpolation (slerp) between two unnormalized vectors. This function applies geometric slerp to unnormalized vectors by first normalizing them to return the interpolation weights. It reduces to lerp when input vectors are exactly anti-parallel. Note: In the following, A1 to An are optional batch dimensions. Args: vector1: A tensor of shape `[A1, ... , An, M]`, which stores a normalized vector in its last dimension. vector2: A tensor of shape `[A1, ... , An, M]`, which stores a normalized vector in its last dimension. percent: A `float` or tensor with shape broadcastable to the shape of input vectors. eps: A small float for operation safety. If left None, its value is automatically selected using dtype of input vectors. name: A name for this op. Defaults to "vector_weights". Raises: ValueError: if the shape of `vector1`, `vector2`, or `percent` is not supported. Returns: Two tensors of shape `[A1, ... , An, 1]`, representing interpolation weights for each input vector. """ with tf.compat.v1.name_scope(name, "vector_weights", [vector1, vector2, percent]): vector1 = tf.convert_to_tensor(value=vector1) vector2 = tf.convert_to_tensor(value=vector2) percent = tf.convert_to_tensor(value=percent, dtype=vector1.dtype) if percent.shape.ndims == 0: percent = tf.expand_dims(percent, axis=0) shape.compare_dimensions( tensors=(vector1, vector2), axes=-1, tensor_names=("vector1", "vector2")) shape.compare_batch_dimensions( tensors=(vector1, vector2, percent), last_axes=(-2, -2, -1), broadcast_compatible=True, tensor_names=("vector1", "vector2", "percent")) normalized1 = tf.nn.l2_normalize(vector1, axis=-1) normalized2 = tf.nn.l2_normalize(vector2, axis=-1) dot_product = _safe_dot(normalized1, normalized2, eps) theta = tf.acos(dot_product) scale1 = safe_ops.safe_sinpx_div_sinx(theta, 1.0 - percent, eps) scale2 = safe_ops.safe_sinpx_div_sinx(theta, percent, eps) return scale1, scale2 # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/transformation/tests/rotation_matrix_common_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for rotation_matrix_common.""" from absl.testing import parameterized from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import test_case class RotationMatrixCommonTest(test_case.TestCase): @parameterized.parameters( ((2, 2),), ((3, 3),), ((4, 4),), ((None, 2, 2),), ((None, 3, 3),), ((None, 4, 4),), ) def test_is_valid_exception_not_raised(self, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_not_raised(rotation_matrix_common.is_valid, shape) @parameterized.parameters( ("must have a rank greater than 1", (2,)), ("must have the same number of dimensions in axes", (1, 2)), ("must have the same number of dimensions in axes", (None, 2)), ) def test_is_valid_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(rotation_matrix_common.is_valid, error_msg, shape) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for rotation_matrix_common.""" from absl.testing import parameterized from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import test_case class RotationMatrixCommonTest(test_case.TestCase): @parameterized.parameters( ((2, 2),), ((3, 3),), ((4, 4),), ((None, 2, 2),), ((None, 3, 3),), ((None, 4, 4),), ) def test_is_valid_exception_not_raised(self, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_not_raised(rotation_matrix_common.is_valid, shape) @parameterized.parameters( ("must have a rank greater than 1", (2,)), ("must have the same number of dimensions in axes", (1, 2)), ("must have the same number of dimensions in axes", (None, 2)), ) def test_is_valid_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(rotation_matrix_common.is_valid, error_msg, shape) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/nn/metric/tests/precision_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the precision metric.""" from absl.testing import parameterized import numpy as np from tensorflow_graphics.nn.metric import precision from tensorflow_graphics.util import test_case def random_tensor(tensor_shape): return np.random.uniform(low=0.0, high=1.0, size=tensor_shape) def random_tensor_shape(): tensor_size = np.random.randint(5) + 1 return np.random.randint(1, 10, size=(tensor_size)).tolist() class PrecisionTest(test_case.TestCase): @parameterized.parameters( # Precision = 0.5. ((0, 1, 1, 1, 1), (1, 1, 0, 0, 0), 0.5), # Precision = 1. ((0, 0, 0, 1, 1, 1, 0, 1), (0, 0, 0, 1, 1, 1, 0, 1), 1), # All-0 predictions, returns 0. ((0, 1, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0), 0), # All-0 ground truth, returns 0. ((0, 0, 0, 0, 0, 0), (0, 0, 0, 1, 0, 1), 0), ) def test_evaluate_preset(self, ground_truth, predictions, expected_precision): tensor_shape = random_tensor_shape() ground_truth_labels = np.tile(ground_truth, tensor_shape + [1]) predicted_labels = np.tile(predictions, tensor_shape + [1]) expected = np.tile(expected_precision, tensor_shape) result = precision.evaluate( ground_truth_labels, predicted_labels, classes=[1]) self.assertAllClose(expected, result) @parameterized.parameters( # Precision for classes 2, 3: [0.5, 0.25] ((2, 0, 3, 1, 2, 2), (2, 3, 3, 2, 3, 3), [2, 3], False, [0.5, 0.25]), # Average precision for classes 2, 3: 0.375 ((2, 0, 3, 1, 2, 2), (2, 3, 3, 2, 3, 3), [2, 3], True, 0.375), # Precision for all classes: [0, 0, 0.5, 1] ((1, 2, 3, 3, 1, 1, 2), (0, 2, 0, 3, 0, 2, 0), None, False, [0, 0, 0.5, 1]), # Average precision for all classes: 1.5 / 4 (0.375) ((1, 2, 3, 3, 1, 1, 2), (0, 2, 0, 3, 0, 2, 0), None, True, 1.5 / 4), ) def test_evaluate_preset_multiclass(self, ground_truth, predictions, classes, reduce_average, expected_precision): tensor_shape = random_tensor_shape() ground_truth_labels = np.tile(ground_truth, tensor_shape + [1]) predicted_labels = np.tile(predictions, tensor_shape + [1]) expected = np.tile(expected_precision, tensor_shape + ([1] if not reduce_average else [])) result = precision.evaluate(ground_truth_labels, predicted_labels, classes, reduce_average) self.assertAllClose(expected, result) @parameterized.parameters( ("Not all batch dimensions are broadcast-compatible.", (1, 5, 3), (4, 3)), ("Not all batch dimensions are broadcast-compatible.", (3, 4), (2, 4, 5)), ) def test_evaluate_shape_exception_raised(self, error_msg, *shape): """Tests that the shape exception is raised.""" self.assert_exception_is_raised(precision.evaluate, error_msg, shape) @parameterized.parameters( ((1, 5, 3), (2, 5, 1)), ((None, 2, 6), (4, 2, None)), ((3, 1, 1, 2), (3, 5, 8, 2)), ) def test_evaluate_shape_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(precision.evaluate, shapes) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the precision metric.""" from absl.testing import parameterized import numpy as np from tensorflow_graphics.nn.metric import precision from tensorflow_graphics.util import test_case def random_tensor(tensor_shape): return np.random.uniform(low=0.0, high=1.0, size=tensor_shape) def random_tensor_shape(): tensor_size = np.random.randint(5) + 1 return np.random.randint(1, 10, size=(tensor_size)).tolist() class PrecisionTest(test_case.TestCase): @parameterized.parameters( # Precision = 0.5. ((0, 1, 1, 1, 1), (1, 1, 0, 0, 0), 0.5), # Precision = 1. ((0, 0, 0, 1, 1, 1, 0, 1), (0, 0, 0, 1, 1, 1, 0, 1), 1), # All-0 predictions, returns 0. ((0, 1, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0), 0), # All-0 ground truth, returns 0. ((0, 0, 0, 0, 0, 0), (0, 0, 0, 1, 0, 1), 0), ) def test_evaluate_preset(self, ground_truth, predictions, expected_precision): tensor_shape = random_tensor_shape() ground_truth_labels = np.tile(ground_truth, tensor_shape + [1]) predicted_labels = np.tile(predictions, tensor_shape + [1]) expected = np.tile(expected_precision, tensor_shape) result = precision.evaluate( ground_truth_labels, predicted_labels, classes=[1]) self.assertAllClose(expected, result) @parameterized.parameters( # Precision for classes 2, 3: [0.5, 0.25] ((2, 0, 3, 1, 2, 2), (2, 3, 3, 2, 3, 3), [2, 3], False, [0.5, 0.25]), # Average precision for classes 2, 3: 0.375 ((2, 0, 3, 1, 2, 2), (2, 3, 3, 2, 3, 3), [2, 3], True, 0.375), # Precision for all classes: [0, 0, 0.5, 1] ((1, 2, 3, 3, 1, 1, 2), (0, 2, 0, 3, 0, 2, 0), None, False, [0, 0, 0.5, 1]), # Average precision for all classes: 1.5 / 4 (0.375) ((1, 2, 3, 3, 1, 1, 2), (0, 2, 0, 3, 0, 2, 0), None, True, 1.5 / 4), ) def test_evaluate_preset_multiclass(self, ground_truth, predictions, classes, reduce_average, expected_precision): tensor_shape = random_tensor_shape() ground_truth_labels = np.tile(ground_truth, tensor_shape + [1]) predicted_labels = np.tile(predictions, tensor_shape + [1]) expected = np.tile(expected_precision, tensor_shape + ([1] if not reduce_average else [])) result = precision.evaluate(ground_truth_labels, predicted_labels, classes, reduce_average) self.assertAllClose(expected, result) @parameterized.parameters( ("Not all batch dimensions are broadcast-compatible.", (1, 5, 3), (4, 3)), ("Not all batch dimensions are broadcast-compatible.", (3, 4), (2, 4, 5)), ) def test_evaluate_shape_exception_raised(self, error_msg, *shape): """Tests that the shape exception is raised.""" self.assert_exception_is_raised(precision.evaluate, error_msg, shape) @parameterized.parameters( ((1, 5, 3), (2, 5, 1)), ((None, 2, 6), (4, 2, None)), ((3, 1, 1, 2), (3, 5, 8, 2)), ) def test_evaluate_shape_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(precision.evaluate, shapes) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/projects/local_implicit_grid/core/model_g2v.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Model for part autoencoder.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow.compat.v1 as tf layers = tf.keras.layers class ResBlock3D(layers.Layer): """3D convolutional Residue Block. Maintains same resolution. """ def __init__(self, neck_channels, out_channels): """Initialization. Args: neck_channels: int, number of channels in bottleneck layer. out_channels: int, number of output channels. """ super(ResBlock3D, self).__init__() self.neck_channels = neck_channels self.out_channels = out_channels self.conv1 = layers.Conv3D(neck_channels, kernel_size=1, strides=1) self.conv2 = layers.Conv3D( neck_channels, kernel_size=3, strides=1, padding="same") self.conv3 = layers.Conv3D(out_channels, kernel_size=1, strides=1) self.bn1 = layers.BatchNormalization(axis=-1) self.bn2 = layers.BatchNormalization(axis=-1) self.bn3 = layers.BatchNormalization(axis=-1) self.shortcut = layers.Conv3D(out_channels, kernel_size=1, strides=1) def call(self, x, training=False): identity = x x = self.conv1(x) x = self.bn1(x, training=training) x = tf.nn.relu(x) x = self.conv2(x) x = self.bn2(x, training=training) x = tf.nn.relu(x) x = self.conv3(x) x = self.bn3(x, training=training) x += self.shortcut(identity) x = tf.nn.relu(x) return x class GridEncoder(layers.Layer): """Grid to vector model for part autoencoding.""" def __init__(self, in_grid_res=32, num_filters=32, codelen=128, name="grid_encoder"): """Initialization. Args: in_grid_res: int, input grid resolution, must be powers of 2. num_filters: int, number of feature layers at smallest grid resolution. codelen: int, length of local latent codes. name: str, name of the layer. """ super(GridEncoder, self).__init__(name=name) self.in_grid_res = in_grid_res self.num_filters = num_filters self.codelen = codelen # number of input levels. self.num_in_level = int(math.log(self.in_grid_res, 2)) # create layers nd = [self.num_filters * (2**i) for i in range(self.num_in_level + 1) ] # feat. in downward path self.conv_in = layers.Conv3D(filters=nd[0], kernel_size=1) self.down_conv = [ResBlock3D(int(n / 2), n) for n in nd[1:]] self.down_pool = [layers.MaxPool3D((2, 2, 2)) for _ in nd[1:]] self.fc_out = layers.Dense(self.codelen) def call(self, x, training=False): """Forward method. Args: x: `[batch, in_grid_res, in_grid_res, in_grid_res, in_features]` tensor, input voxel grid. training: bool, flag indicating whether model is in training mode. Returns: `[batch, codelen]` tensor, output voxel grid. """ x = self.conv_in(x) x = tf.nn.relu(x) for conv, pool in zip(self.down_conv, self.down_pool): x = conv(x, training=training) x = pool(x, training=training) # [batch, res, res, res, c] x = tf.squeeze(x, axis=(1, 2, 3)) # [batch, c] x = self.fc_out(x) # [batch, code_len] return x class GridEncoderVAE(layers.Layer): """Grid to vector model for part autoencoding.""" def __init__(self, in_grid_res=32, num_filters=32, codelen=128, name="grid_encoder_vae"): """Initialization. Args: in_grid_res: int, input grid resolution, must be powers of 2. num_filters: int, number of feature layers at smallest grid resolution. codelen: int, length of local latent codes. name: str, name of the layer. """ super(GridEncoderVAE, self).__init__(name=name) self.in_grid_res = in_grid_res self.num_filters = num_filters self.codelen = codelen # number of input levels self.num_in_level = int(math.log(self.in_grid_res, 2)) # create layers # feat. in downward path nd = [self.num_filters * (2**i) for i in range(self.num_in_level + 1)] self.conv_in = layers.Conv3D(filters=nd[0], kernel_size=1) self.down_conv = [ResBlock3D(int(n / 2), n) for n in nd[1:]] self.down_pool = layers.MaxPool3D((2, 2, 2)) self.fc_out = layers.Dense(self.codelen * 2) def call(self, x, training=False): """Forward method. Args: x: `[batch, in_grid_res, in_grid_res, in_grid_res, in_features]` tensor, input voxel grid. training: bool, flag indicating whether model is in training mode. Returns: `[batch, codelen]` tensor, output voxel grid. """ x = self.conv_in(x) x = tf.nn.relu(x) for conv in self.down_conv: x = conv(x, training=training) x = self.down_pool(x, training=training) # [batch, res, res, res, c] x = tf.squeeze(x, axis=(1, 2, 3)) # [batch, c] x = self.fc_out(x) # [batch, code_len*2] mu, logvar = x[:, :self.codelen], x[:, self.codelen:] noise = tf.random.normal(mu.shape) std = tf.exp(0.5 * logvar) x_out = mu + noise * std return x_out, mu, logvar
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Model for part autoencoder.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow.compat.v1 as tf layers = tf.keras.layers class ResBlock3D(layers.Layer): """3D convolutional Residue Block. Maintains same resolution. """ def __init__(self, neck_channels, out_channels): """Initialization. Args: neck_channels: int, number of channels in bottleneck layer. out_channels: int, number of output channels. """ super(ResBlock3D, self).__init__() self.neck_channels = neck_channels self.out_channels = out_channels self.conv1 = layers.Conv3D(neck_channels, kernel_size=1, strides=1) self.conv2 = layers.Conv3D( neck_channels, kernel_size=3, strides=1, padding="same") self.conv3 = layers.Conv3D(out_channels, kernel_size=1, strides=1) self.bn1 = layers.BatchNormalization(axis=-1) self.bn2 = layers.BatchNormalization(axis=-1) self.bn3 = layers.BatchNormalization(axis=-1) self.shortcut = layers.Conv3D(out_channels, kernel_size=1, strides=1) def call(self, x, training=False): identity = x x = self.conv1(x) x = self.bn1(x, training=training) x = tf.nn.relu(x) x = self.conv2(x) x = self.bn2(x, training=training) x = tf.nn.relu(x) x = self.conv3(x) x = self.bn3(x, training=training) x += self.shortcut(identity) x = tf.nn.relu(x) return x class GridEncoder(layers.Layer): """Grid to vector model for part autoencoding.""" def __init__(self, in_grid_res=32, num_filters=32, codelen=128, name="grid_encoder"): """Initialization. Args: in_grid_res: int, input grid resolution, must be powers of 2. num_filters: int, number of feature layers at smallest grid resolution. codelen: int, length of local latent codes. name: str, name of the layer. """ super(GridEncoder, self).__init__(name=name) self.in_grid_res = in_grid_res self.num_filters = num_filters self.codelen = codelen # number of input levels. self.num_in_level = int(math.log(self.in_grid_res, 2)) # create layers nd = [self.num_filters * (2**i) for i in range(self.num_in_level + 1) ] # feat. in downward path self.conv_in = layers.Conv3D(filters=nd[0], kernel_size=1) self.down_conv = [ResBlock3D(int(n / 2), n) for n in nd[1:]] self.down_pool = [layers.MaxPool3D((2, 2, 2)) for _ in nd[1:]] self.fc_out = layers.Dense(self.codelen) def call(self, x, training=False): """Forward method. Args: x: `[batch, in_grid_res, in_grid_res, in_grid_res, in_features]` tensor, input voxel grid. training: bool, flag indicating whether model is in training mode. Returns: `[batch, codelen]` tensor, output voxel grid. """ x = self.conv_in(x) x = tf.nn.relu(x) for conv, pool in zip(self.down_conv, self.down_pool): x = conv(x, training=training) x = pool(x, training=training) # [batch, res, res, res, c] x = tf.squeeze(x, axis=(1, 2, 3)) # [batch, c] x = self.fc_out(x) # [batch, code_len] return x class GridEncoderVAE(layers.Layer): """Grid to vector model for part autoencoding.""" def __init__(self, in_grid_res=32, num_filters=32, codelen=128, name="grid_encoder_vae"): """Initialization. Args: in_grid_res: int, input grid resolution, must be powers of 2. num_filters: int, number of feature layers at smallest grid resolution. codelen: int, length of local latent codes. name: str, name of the layer. """ super(GridEncoderVAE, self).__init__(name=name) self.in_grid_res = in_grid_res self.num_filters = num_filters self.codelen = codelen # number of input levels self.num_in_level = int(math.log(self.in_grid_res, 2)) # create layers # feat. in downward path nd = [self.num_filters * (2**i) for i in range(self.num_in_level + 1)] self.conv_in = layers.Conv3D(filters=nd[0], kernel_size=1) self.down_conv = [ResBlock3D(int(n / 2), n) for n in nd[1:]] self.down_pool = layers.MaxPool3D((2, 2, 2)) self.fc_out = layers.Dense(self.codelen * 2) def call(self, x, training=False): """Forward method. Args: x: `[batch, in_grid_res, in_grid_res, in_grid_res, in_features]` tensor, input voxel grid. training: bool, flag indicating whether model is in training mode. Returns: `[batch, codelen]` tensor, output voxel grid. """ x = self.conv_in(x) x = tf.nn.relu(x) for conv in self.down_conv: x = conv(x, training=training) x = self.down_pool(x, training=training) # [batch, res, res, res, c] x = tf.squeeze(x, axis=(1, 2, 3)) # [batch, c] x = self.fc_out(x) # [batch, code_len*2] mu, logvar = x[:, :self.codelen], x[:, self.codelen:] noise = tf.random.normal(mu.shape) std = tf.exp(0.5 * logvar) x_out = mu + noise * std return x_out, mu, logvar
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/rendering/light/tests/point_light_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for point light.""" import math from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.rendering.light import point_light from tensorflow_graphics.util import test_case def fake_brdf(incoming_light_direction, outgoing_light_direction, surface_point_normal): del incoming_light_direction, surface_point_normal # Unused. return outgoing_light_direction def returning_zeros_brdf(incoming_light_direction, outgoing_light_direction, surface_point_normal): del incoming_light_direction, outgoing_light_direction # Unused. return tf.zeros_like(surface_point_normal) def random_tensor(tensor_shape): return np.random.uniform(low=-100.0, high=100.0, size=tensor_shape) class PointLightTest(test_case.TestCase): @parameterized.parameters( # Light direction is parallel to the surface normal. ([1.], [[0., 0., 1.]], [2., 0., 0.], [1.0 / (4. * math.pi), 0., 0.]), # Light direction is parallel to the surface normal and the reflected # light fall off is included in the calculation. ([1.], [[0., 0., 1.]], [2., 0., 0.], \ [0.25 / (4. * math.pi), 0., 0.], True), # Light direction is perpendicular to the surface normal. ([1.], [[3., 0., 0.]], [1., 2., 3.], [0., 0., 0.]), # Angle between surface normal and the incoming light direction is pi/3. ([1.], [[math.sqrt(3), 0., 1.]], \ [0., 1., 0.], [0., 0.125 / (4. * math.pi), 0.]), # Angle between surface normal and the incoming light direction is pi/4. ([1.], [[0., 1., 1.]], [1., 1., 0.], [0.25 / (4. * math.pi), 0.25 / (4. * math.pi), 0.]), # Light has 3 radiances. ([2., 4., 1.], [[0., 1., 1.]], [1., 1., 0.], [0.5 / (4. * math.pi), 1. / (4. * math.pi), 0.]), # Light is behind the surface. ([1.], [[0., 0., -2.]], [7., 0., 0.], [0., 0., 0.]), # Observation point is behind the surface. ([1.], [[0., 0., 2.]], [5., 0., -2.], [0., 0., 0.]), # Light and observation point are behind the surface. ([1.], [[0., 0., -2.]], [5., 0., -2.], [0., 0., 0.]), ) def test_estimate_radiance_preset(self, light_radiance, light_pos, observation_pos, expected_result, reflected_light_fall_off=False): """Tests the output of estimate radiance function with various parameters. In this test the point on the surface is always [0, 0, 0] ,the surface normal is [0, 0, 1] and the fake brdf function returns the (normalized) direction of the outgoing light as its output. Args: light_radiance: An array of size K representing the point light radiances. light_pos: An array of size [3,] representing the point light positions. observation_pos: An array of size [3,] representing the observation point. expected_result: An array of size [3,] representing the expected result of the estimated reflected radiance function. reflected_light_fall_off: A boolean specifying whether or not to include the fall off of the reflected light in the calculation. Defaults to False. """ tensor_size = np.random.randint(1, 3) + 1 tensor_shape = np.random.randint(1, 10, size=tensor_size).tolist() lights_tensor_size = np.random.randint(1, 3) + 1 lights_tensor_shape = np.random.randint( 1, 10, size=lights_tensor_size).tolist() point_light_radiance = np.tile(light_radiance, lights_tensor_shape + [1]) point_light_position = np.tile(light_pos, lights_tensor_shape + [1]) surface_point_normal = np.tile([0.0, 0.0, 1.0], tensor_shape + [1]) surface_point_position = np.tile([0.0, 0.0, 0.0], tensor_shape + [1]) observation_point = np.tile(observation_pos, tensor_shape + [1]) expected = np.tile(expected_result, tensor_shape + lights_tensor_shape + [1]) pred = point_light.estimate_radiance( point_light_radiance, point_light_position, surface_point_position, surface_point_normal, observation_point, fake_brdf, reflected_light_fall_off=reflected_light_fall_off) self.assertAllClose(expected, pred) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_estimate_radiance_jacobian_random(self): """Tests the Jacobian of the point lighting equation.""" tensor_size = np.random.randint(1, 3) tensor_shape = np.random.randint(1, 10, size=tensor_size).tolist() light_tensor_size = np.random.randint(1, 3) lights_tensor_shape = np.random.randint( 1, 10, size=light_tensor_size).tolist() point_light_radiance_init = random_tensor(lights_tensor_shape + [1]) point_light_position_init = random_tensor(lights_tensor_shape + [3]) surface_point_position_init = random_tensor(tensor_shape + [3]) surface_point_normal_init = random_tensor(tensor_shape + [3]) observation_point_init = random_tensor(tensor_shape + [3]) def estimate_radiance_fn(point_light_position, surface_point_position, surface_point_normal, observation_point): return point_light.estimate_radiance(point_light_radiance_init, point_light_position, surface_point_position, surface_point_normal, observation_point, fake_brdf) self.assert_jacobian_is_correct_fn(estimate_radiance_fn, [ point_light_position_init, surface_point_position_init, surface_point_normal_init, observation_point_init ]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_estimate_radiance_jacobian_preset(self): """Tests the Jacobian of the point lighting equation. Verifies that the Jacobian of the point lighting equation is correct when the light direction is orthogonal to the surface normal. """ delta = 1e-5 point_light_radiance_init = np.array(1.0).reshape((1, 1)) point_light_position_init = np.array((delta, 1.0, 0.0)).reshape((1, 3)) surface_point_position_init = np.array((0.0, 0.0, 0.0)) surface_point_normal_init = np.array((1.0, 0.0, 0.0)) observation_point_init = np.array((delta, 3.0, 0.0)) def estimate_radiance_fn(point_light_position, surface_point_position, surface_point_normal, observation_point): return point_light.estimate_radiance(point_light_radiance_init, point_light_position, surface_point_position, surface_point_normal, observation_point, fake_brdf) self.assert_jacobian_is_correct_fn(estimate_radiance_fn, [ point_light_position_init, surface_point_position_init, surface_point_normal_init, observation_point_init ]) @parameterized.parameters( ((1, 1), (1, 3), (3,), (3,), (3,)), ((4, 1, 1), (4, 1, 3), (1, 3), (1, 3), (1, 3)), ((3, 2, 1), (3, 2, 3), (2, 3), (2, 3), (2, 3)), ((1, 1), (3,), (1, 3), (1, 2, 3), (1, 3)), ((4, 5, 1), (3, 4, 5, 3), (1, 3), (1, 2, 2, 3), (1, 2, 3)), ((1,), (1, 2, 2, 3), (1, 2, 3), (1, 3), (3,)), ) def test_estimate_radiance_shape_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( point_light.estimate_radiance, shape, brdf=returning_zeros_brdf) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 1), (3,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (5, 1), (5, 2), (3,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 4), (3,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (1,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (2,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (4,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (3,), (2,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (3,), (4,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (3,), (3,), (4,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (3,), (3,), (2,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (3,), (3,), (1,)), ("Not all batch dimensions are broadcast-compatible.", (1, 3, 1), (1, 3, 3), (2, 3), (4, 3), (3,)), ("Not all batch dimensions are broadcast-compatible.", (1, 3, 1), (1, 4, 3), (2, 3), (3,), (3,)), ) def test_estimate_radiance_shape_exception_raised(self, error_msg, *shape): """Tests that the shape exception is raised.""" self.assert_exception_is_raised( point_light.estimate_radiance, error_msg, shape, brdf=returning_zeros_brdf) def test_estimate_radiance_value_exceptions_raised(self): """Tests that the value exceptions are raised correctly.""" point_light_radiance = random_tensor(tensor_shape=(1, 1)) point_light_position = random_tensor(tensor_shape=(1, 3)) surface_point_position = random_tensor(tensor_shape=(3,)) surface_point_normal = random_tensor(tensor_shape=(3,)) observation_point = random_tensor(tensor_shape=(3,)) # Verify that an InvalidArgumentError is raised as the given # surface_point_normal is not normalized. with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( point_light.estimate_radiance(point_light_radiance, point_light_position, surface_point_position, surface_point_normal, observation_point, returning_zeros_brdf)) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for point light.""" import math from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.rendering.light import point_light from tensorflow_graphics.util import test_case def fake_brdf(incoming_light_direction, outgoing_light_direction, surface_point_normal): del incoming_light_direction, surface_point_normal # Unused. return outgoing_light_direction def returning_zeros_brdf(incoming_light_direction, outgoing_light_direction, surface_point_normal): del incoming_light_direction, outgoing_light_direction # Unused. return tf.zeros_like(surface_point_normal) def random_tensor(tensor_shape): return np.random.uniform(low=-100.0, high=100.0, size=tensor_shape) class PointLightTest(test_case.TestCase): @parameterized.parameters( # Light direction is parallel to the surface normal. ([1.], [[0., 0., 1.]], [2., 0., 0.], [1.0 / (4. * math.pi), 0., 0.]), # Light direction is parallel to the surface normal and the reflected # light fall off is included in the calculation. ([1.], [[0., 0., 1.]], [2., 0., 0.], \ [0.25 / (4. * math.pi), 0., 0.], True), # Light direction is perpendicular to the surface normal. ([1.], [[3., 0., 0.]], [1., 2., 3.], [0., 0., 0.]), # Angle between surface normal and the incoming light direction is pi/3. ([1.], [[math.sqrt(3), 0., 1.]], \ [0., 1., 0.], [0., 0.125 / (4. * math.pi), 0.]), # Angle between surface normal and the incoming light direction is pi/4. ([1.], [[0., 1., 1.]], [1., 1., 0.], [0.25 / (4. * math.pi), 0.25 / (4. * math.pi), 0.]), # Light has 3 radiances. ([2., 4., 1.], [[0., 1., 1.]], [1., 1., 0.], [0.5 / (4. * math.pi), 1. / (4. * math.pi), 0.]), # Light is behind the surface. ([1.], [[0., 0., -2.]], [7., 0., 0.], [0., 0., 0.]), # Observation point is behind the surface. ([1.], [[0., 0., 2.]], [5., 0., -2.], [0., 0., 0.]), # Light and observation point are behind the surface. ([1.], [[0., 0., -2.]], [5., 0., -2.], [0., 0., 0.]), ) def test_estimate_radiance_preset(self, light_radiance, light_pos, observation_pos, expected_result, reflected_light_fall_off=False): """Tests the output of estimate radiance function with various parameters. In this test the point on the surface is always [0, 0, 0] ,the surface normal is [0, 0, 1] and the fake brdf function returns the (normalized) direction of the outgoing light as its output. Args: light_radiance: An array of size K representing the point light radiances. light_pos: An array of size [3,] representing the point light positions. observation_pos: An array of size [3,] representing the observation point. expected_result: An array of size [3,] representing the expected result of the estimated reflected radiance function. reflected_light_fall_off: A boolean specifying whether or not to include the fall off of the reflected light in the calculation. Defaults to False. """ tensor_size = np.random.randint(1, 3) + 1 tensor_shape = np.random.randint(1, 10, size=tensor_size).tolist() lights_tensor_size = np.random.randint(1, 3) + 1 lights_tensor_shape = np.random.randint( 1, 10, size=lights_tensor_size).tolist() point_light_radiance = np.tile(light_radiance, lights_tensor_shape + [1]) point_light_position = np.tile(light_pos, lights_tensor_shape + [1]) surface_point_normal = np.tile([0.0, 0.0, 1.0], tensor_shape + [1]) surface_point_position = np.tile([0.0, 0.0, 0.0], tensor_shape + [1]) observation_point = np.tile(observation_pos, tensor_shape + [1]) expected = np.tile(expected_result, tensor_shape + lights_tensor_shape + [1]) pred = point_light.estimate_radiance( point_light_radiance, point_light_position, surface_point_position, surface_point_normal, observation_point, fake_brdf, reflected_light_fall_off=reflected_light_fall_off) self.assertAllClose(expected, pred) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_estimate_radiance_jacobian_random(self): """Tests the Jacobian of the point lighting equation.""" tensor_size = np.random.randint(1, 3) tensor_shape = np.random.randint(1, 10, size=tensor_size).tolist() light_tensor_size = np.random.randint(1, 3) lights_tensor_shape = np.random.randint( 1, 10, size=light_tensor_size).tolist() point_light_radiance_init = random_tensor(lights_tensor_shape + [1]) point_light_position_init = random_tensor(lights_tensor_shape + [3]) surface_point_position_init = random_tensor(tensor_shape + [3]) surface_point_normal_init = random_tensor(tensor_shape + [3]) observation_point_init = random_tensor(tensor_shape + [3]) def estimate_radiance_fn(point_light_position, surface_point_position, surface_point_normal, observation_point): return point_light.estimate_radiance(point_light_radiance_init, point_light_position, surface_point_position, surface_point_normal, observation_point, fake_brdf) self.assert_jacobian_is_correct_fn(estimate_radiance_fn, [ point_light_position_init, surface_point_position_init, surface_point_normal_init, observation_point_init ]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_estimate_radiance_jacobian_preset(self): """Tests the Jacobian of the point lighting equation. Verifies that the Jacobian of the point lighting equation is correct when the light direction is orthogonal to the surface normal. """ delta = 1e-5 point_light_radiance_init = np.array(1.0).reshape((1, 1)) point_light_position_init = np.array((delta, 1.0, 0.0)).reshape((1, 3)) surface_point_position_init = np.array((0.0, 0.0, 0.0)) surface_point_normal_init = np.array((1.0, 0.0, 0.0)) observation_point_init = np.array((delta, 3.0, 0.0)) def estimate_radiance_fn(point_light_position, surface_point_position, surface_point_normal, observation_point): return point_light.estimate_radiance(point_light_radiance_init, point_light_position, surface_point_position, surface_point_normal, observation_point, fake_brdf) self.assert_jacobian_is_correct_fn(estimate_radiance_fn, [ point_light_position_init, surface_point_position_init, surface_point_normal_init, observation_point_init ]) @parameterized.parameters( ((1, 1), (1, 3), (3,), (3,), (3,)), ((4, 1, 1), (4, 1, 3), (1, 3), (1, 3), (1, 3)), ((3, 2, 1), (3, 2, 3), (2, 3), (2, 3), (2, 3)), ((1, 1), (3,), (1, 3), (1, 2, 3), (1, 3)), ((4, 5, 1), (3, 4, 5, 3), (1, 3), (1, 2, 2, 3), (1, 2, 3)), ((1,), (1, 2, 2, 3), (1, 2, 3), (1, 3), (3,)), ) def test_estimate_radiance_shape_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( point_light.estimate_radiance, shape, brdf=returning_zeros_brdf) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 1), (3,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (5, 1), (5, 2), (3,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 4), (3,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (1,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (2,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (4,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (3,), (2,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (3,), (4,), (3,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (3,), (3,), (4,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (3,), (3,), (2,)), ("must have exactly 3 dimensions in axis -1", (1, 1), (1, 3), (3,), (3,), (1,)), ("Not all batch dimensions are broadcast-compatible.", (1, 3, 1), (1, 3, 3), (2, 3), (4, 3), (3,)), ("Not all batch dimensions are broadcast-compatible.", (1, 3, 1), (1, 4, 3), (2, 3), (3,), (3,)), ) def test_estimate_radiance_shape_exception_raised(self, error_msg, *shape): """Tests that the shape exception is raised.""" self.assert_exception_is_raised( point_light.estimate_radiance, error_msg, shape, brdf=returning_zeros_brdf) def test_estimate_radiance_value_exceptions_raised(self): """Tests that the value exceptions are raised correctly.""" point_light_radiance = random_tensor(tensor_shape=(1, 1)) point_light_position = random_tensor(tensor_shape=(1, 3)) surface_point_position = random_tensor(tensor_shape=(3,)) surface_point_normal = random_tensor(tensor_shape=(3,)) observation_point = random_tensor(tensor_shape=(3,)) # Verify that an InvalidArgumentError is raised as the given # surface_point_normal is not normalized. with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( point_light.estimate_radiance(point_light_radiance, point_light_position, surface_point_position, surface_point_normal, observation_point, returning_zeros_brdf)) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/transformation/tests/look_at_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for OpenGL lookAt functions.""" from absl.testing import parameterized import numpy as np from tensorflow_graphics.geometry.transformation import look_at from tensorflow_graphics.util import test_case class LookAtTest(test_case.TestCase): def test_look_at_right_handed_preset(self): """Tests that look_at_right_handed generates expected results.""" camera_position = ((0.0, 0.0, 0.0), (0.1, 0.2, 0.3)) look_at_point = ((0.0, 0.0, 1.0), (0.4, 0.5, 0.6)) up_vector = ((0.0, 1.0, 0.0), (0.7, 0.8, 0.9)) pred = look_at.right_handed(camera_position, look_at_point, up_vector) gt = (((-1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, -1.0, 0.0), (0.0, 0.0, 0.0, 1.0)), ((4.08248186e-01, -8.16496551e-01, 4.08248395e-01, -2.98023224e-08), (-7.07106888e-01, 1.19209290e-07, 7.07106769e-01, -1.41421378e-01), (-5.77350318e-01, -5.77350318e-01, -5.77350318e-01, 3.46410215e-01), (0.0, 0.0, 0.0, 1.0))) self.assertAllClose(pred, gt) @parameterized.parameters( ((3,), (3,), (3,)), ((None, 3), (None, 3), (None, 3)), ((None, 2, 3), (None, 2, 3), (None, 2, 3)), ) def test_look_at_right_handed_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(look_at.right_handed, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (2,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (2,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (1,)), ("Not all batch dimensions are identical", (3,), (3, 3), (3, 3)), ) def test_look_at_right_handed_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(look_at.right_handed, error_msg, shapes) def test_look_at_right_handed_jacobian_preset(self): """Tests the Jacobian of look_at_right_handed.""" camera_position_init = np.array(((0.0, 0.0, 0.0), (0.1, 0.2, 0.3))) look_at_init = np.array(((0.0, 0.0, 1.0), (0.4, 0.5, 0.6))) up_vector_init = np.array(((0.0, 1.0, 0.0), (0.7, 0.8, 0.9))) self.assert_jacobian_is_correct_fn( look_at.right_handed, [camera_position_init, look_at_init, up_vector_init]) def test_look_at_right_handed_jacobian_random(self): """Tests the Jacobian of look_at_right_handed.""" tensor_size = np.random.randint(1, 3) tensor_shape = np.random.randint(1, 5, size=(tensor_size)).tolist() camera_position_init = np.random.uniform(size=tensor_shape + [3]) look_at_init = np.random.uniform(size=tensor_shape + [3]) up_vector_init = np.random.uniform(size=tensor_shape + [3]) self.assert_jacobian_is_correct_fn( look_at.right_handed, [camera_position_init, look_at_init, up_vector_init])
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for OpenGL lookAt functions.""" from absl.testing import parameterized import numpy as np from tensorflow_graphics.geometry.transformation import look_at from tensorflow_graphics.util import test_case class LookAtTest(test_case.TestCase): def test_look_at_right_handed_preset(self): """Tests that look_at_right_handed generates expected results.""" camera_position = ((0.0, 0.0, 0.0), (0.1, 0.2, 0.3)) look_at_point = ((0.0, 0.0, 1.0), (0.4, 0.5, 0.6)) up_vector = ((0.0, 1.0, 0.0), (0.7, 0.8, 0.9)) pred = look_at.right_handed(camera_position, look_at_point, up_vector) gt = (((-1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, -1.0, 0.0), (0.0, 0.0, 0.0, 1.0)), ((4.08248186e-01, -8.16496551e-01, 4.08248395e-01, -2.98023224e-08), (-7.07106888e-01, 1.19209290e-07, 7.07106769e-01, -1.41421378e-01), (-5.77350318e-01, -5.77350318e-01, -5.77350318e-01, 3.46410215e-01), (0.0, 0.0, 0.0, 1.0))) self.assertAllClose(pred, gt) @parameterized.parameters( ((3,), (3,), (3,)), ((None, 3), (None, 3), (None, 3)), ((None, 2, 3), (None, 2, 3), (None, 2, 3)), ) def test_look_at_right_handed_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(look_at.right_handed, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (2,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (2,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (1,)), ("Not all batch dimensions are identical", (3,), (3, 3), (3, 3)), ) def test_look_at_right_handed_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(look_at.right_handed, error_msg, shapes) def test_look_at_right_handed_jacobian_preset(self): """Tests the Jacobian of look_at_right_handed.""" camera_position_init = np.array(((0.0, 0.0, 0.0), (0.1, 0.2, 0.3))) look_at_init = np.array(((0.0, 0.0, 1.0), (0.4, 0.5, 0.6))) up_vector_init = np.array(((0.0, 1.0, 0.0), (0.7, 0.8, 0.9))) self.assert_jacobian_is_correct_fn( look_at.right_handed, [camera_position_init, look_at_init, up_vector_init]) def test_look_at_right_handed_jacobian_random(self): """Tests the Jacobian of look_at_right_handed.""" tensor_size = np.random.randint(1, 3) tensor_shape = np.random.randint(1, 5, size=(tensor_size)).tolist() camera_position_init = np.random.uniform(size=tensor_shape + [3]) look_at_init = np.random.uniform(size=tensor_shape + [3]) up_vector_init = np.random.uniform(size=tensor_shape + [3]) self.assert_jacobian_is_correct_fn( look_at.right_handed, [camera_position_init, look_at_init, up_vector_init])
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/math/interpolation/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/image/color_space/tests/srgb_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for srgb.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np from tensorflow_graphics.image.color_space import linear_rgb from tensorflow_graphics.image.color_space import srgb from tensorflow_graphics.util import test_case class SrgbTest(test_case.TestCase): def test_cycle_linear_rgb_srgb_linear_rgb_for_random_input(self): """Tests loop from linear RGB to sRGB and back for random inputs.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() linear_input = np.random.uniform(size=tensor_shape + [3]) srgb_output = srgb.from_linear_rgb(linear_input) linear_reverse = linear_rgb.from_srgb(srgb_output) self.assertAllClose(linear_input, linear_reverse) @parameterized.parameters( (((0., 0.5, 1.), (0.00312, 0.0031308, 0.00314)), ((0., 0.735357, 1.), (0.04031, 0.04045, 0.040567))),) def test_from_linear_rgb_preset(self, test_inputs, test_outputs): """Tests conversion from linear to sRGB color space for preset inputs.""" self.assert_output_is_correct(srgb.from_linear_rgb, (test_inputs,), (test_outputs,)) def test_from_linear_rgb_jacobian_random(self): """Tests the Jacobian of the from_linear_rgb function for random inputs.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() linear_random_init = np.random.uniform(size=tensor_shape + [3]) self.assert_jacobian_is_correct_fn(srgb.from_linear_rgb, [linear_random_init]) @parameterized.parameters((np.array((0., 0.001, 0.002)),), (np.array( (0.004, 0.005, 1.)),), (np.array((0.00312, 0.004, 0.00314)),)) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_linear_rgb_jacobian_preset(self, inputs_init): """Tests the Jacobian of the from_linear_rgb function for preset inputs.""" self.assert_jacobian_is_correct_fn(srgb.from_linear_rgb, [inputs_init]) @parameterized.parameters( ((3,),), ((None, None, None, 3),), ) def test_from_linear_rgb_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(srgb.from_linear_rgb, shape) @parameterized.parameters( ("must have a rank greater than 0", ()), ("must have exactly 3 dimensions in axis -1", (2, 3, 4)), ) def test_from_linear_rgb_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(srgb.from_linear_rgb, error_msg, shape) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for srgb.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np from tensorflow_graphics.image.color_space import linear_rgb from tensorflow_graphics.image.color_space import srgb from tensorflow_graphics.util import test_case class SrgbTest(test_case.TestCase): def test_cycle_linear_rgb_srgb_linear_rgb_for_random_input(self): """Tests loop from linear RGB to sRGB and back for random inputs.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() linear_input = np.random.uniform(size=tensor_shape + [3]) srgb_output = srgb.from_linear_rgb(linear_input) linear_reverse = linear_rgb.from_srgb(srgb_output) self.assertAllClose(linear_input, linear_reverse) @parameterized.parameters( (((0., 0.5, 1.), (0.00312, 0.0031308, 0.00314)), ((0., 0.735357, 1.), (0.04031, 0.04045, 0.040567))),) def test_from_linear_rgb_preset(self, test_inputs, test_outputs): """Tests conversion from linear to sRGB color space for preset inputs.""" self.assert_output_is_correct(srgb.from_linear_rgb, (test_inputs,), (test_outputs,)) def test_from_linear_rgb_jacobian_random(self): """Tests the Jacobian of the from_linear_rgb function for random inputs.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() linear_random_init = np.random.uniform(size=tensor_shape + [3]) self.assert_jacobian_is_correct_fn(srgb.from_linear_rgb, [linear_random_init]) @parameterized.parameters((np.array((0., 0.001, 0.002)),), (np.array( (0.004, 0.005, 1.)),), (np.array((0.00312, 0.004, 0.00314)),)) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_linear_rgb_jacobian_preset(self, inputs_init): """Tests the Jacobian of the from_linear_rgb function for preset inputs.""" self.assert_jacobian_is_correct_fn(srgb.from_linear_rgb, [inputs_init]) @parameterized.parameters( ((3,),), ((None, None, None, 3),), ) def test_from_linear_rgb_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(srgb.from_linear_rgb, shape) @parameterized.parameters( ("must have a rank greater than 0", ()), ("must have exactly 3 dimensions in axis -1", (2, 3, 4)), ) def test_from_linear_rgb_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(srgb.from_linear_rgb, error_msg, shape) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/datasets/features/trimesh_feature_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for tensorflow_graphics.datasets.features.trimesh_feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np import tensorflow.compat.v2 as tf import tensorflow_datasets as tfds from tensorflow_graphics.datasets.features import trimesh_feature import trimesh _TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'test_data') class TrimeshFeatureTest(tfds.testing.FeatureExpectationsTestCase): def test_trimesh(self): obj_file_path = os.path.join(_TEST_DATA_DIR, 'cube.obj') obj_file = tf.io.gfile.GFile(obj_file_path) obj_mesh = trimesh.load(obj_file_path) expected_vertices = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0]]) expected_faces = np.array( [[0, 6, 4], [0, 2, 6], [0, 3, 2], [0, 1, 3], [2, 7, 6], [2, 3, 7], [4, 6, 7], [4, 7, 5], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 3]], dtype=np.uint64) expected_trimesh = {'vertices': expected_vertices, 'faces': expected_faces} # Create a scene with two cubes. scene = trimesh.Scene() scene.add_geometry(obj_mesh) scene.add_geometry(obj_mesh) # The expected TriangleFeature for the scene. expected_scene_feature = { 'vertices': np.tile(expected_vertices, [2, 1]).astype(np.float32), 'faces': np.concatenate( [expected_faces, expected_faces + len(expected_vertices)], axis=0) } self.assertFeature( feature=trimesh_feature.TriangleMesh(), shape={ 'vertices': (None, 3), 'faces': (None, 3) }, dtype={ 'vertices': tf.float32, 'faces': tf.uint64 }, tests=[ # File path tfds.testing.FeatureExpectationItem( value=obj_file_path, expected=expected_trimesh, ), # File object tfds.testing.FeatureExpectationItem( value=obj_file, expected=expected_trimesh, ), # Trimesh tfds.testing.FeatureExpectationItem( value=obj_mesh, expected=expected_trimesh, ), # Scene tfds.testing.FeatureExpectationItem( value=scene, expected=expected_scene_feature, ), # FeaturesDict tfds.testing.FeatureExpectationItem( value=expected_scene_feature, expected=expected_scene_feature, ), # Invalid type tfds.testing.FeatureExpectationItem( value=np.random.rand(80, 3), raise_cls=ValueError, raise_msg='obj should be either a Trimesh or a Scene', ), ], ) if __name__ == '__main__': tfds.testing.test_main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for tensorflow_graphics.datasets.features.trimesh_feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np import tensorflow.compat.v2 as tf import tensorflow_datasets as tfds from tensorflow_graphics.datasets.features import trimesh_feature import trimesh _TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'test_data') class TrimeshFeatureTest(tfds.testing.FeatureExpectationsTestCase): def test_trimesh(self): obj_file_path = os.path.join(_TEST_DATA_DIR, 'cube.obj') obj_file = tf.io.gfile.GFile(obj_file_path) obj_mesh = trimesh.load(obj_file_path) expected_vertices = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0]]) expected_faces = np.array( [[0, 6, 4], [0, 2, 6], [0, 3, 2], [0, 1, 3], [2, 7, 6], [2, 3, 7], [4, 6, 7], [4, 7, 5], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 3]], dtype=np.uint64) expected_trimesh = {'vertices': expected_vertices, 'faces': expected_faces} # Create a scene with two cubes. scene = trimesh.Scene() scene.add_geometry(obj_mesh) scene.add_geometry(obj_mesh) # The expected TriangleFeature for the scene. expected_scene_feature = { 'vertices': np.tile(expected_vertices, [2, 1]).astype(np.float32), 'faces': np.concatenate( [expected_faces, expected_faces + len(expected_vertices)], axis=0) } self.assertFeature( feature=trimesh_feature.TriangleMesh(), shape={ 'vertices': (None, 3), 'faces': (None, 3) }, dtype={ 'vertices': tf.float32, 'faces': tf.uint64 }, tests=[ # File path tfds.testing.FeatureExpectationItem( value=obj_file_path, expected=expected_trimesh, ), # File object tfds.testing.FeatureExpectationItem( value=obj_file, expected=expected_trimesh, ), # Trimesh tfds.testing.FeatureExpectationItem( value=obj_mesh, expected=expected_trimesh, ), # Scene tfds.testing.FeatureExpectationItem( value=scene, expected=expected_scene_feature, ), # FeaturesDict tfds.testing.FeatureExpectationItem( value=expected_scene_feature, expected=expected_scene_feature, ), # Invalid type tfds.testing.FeatureExpectationItem( value=np.random.rand(80, 3), raise_cls=ValueError, raise_msg='obj should be either a Trimesh or a Scene', ), ], ) if __name__ == '__main__': tfds.testing.test_main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/util/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/util/doc.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Query environment variable for documentation building.""" import os def _import_tfg_docs(): """Checks if __init__.py imports should be executed (for buildling docs).""" return os.getenv("TFG_DOC_IMPORTS", "0") == "1" def enable_tfg_doc_imports(): """Re-enables the imports in the __init__.py so that docs can be built.""" os.environ["TFG_DOC_IMPORTS"] = "1"
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Query environment variable for documentation building.""" import os def _import_tfg_docs(): """Checks if __init__.py imports should be executed (for buildling docs).""" return os.getenv("TFG_DOC_IMPORTS", "0") == "1" def enable_tfg_doc_imports(): """Re-enables the imports in the __init__.py so that docs can be built.""" os.environ["TFG_DOC_IMPORTS"] = "1"
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/representation/mesh/tests/sampler_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for uniform mesh sampler.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.representation.mesh import sampler from tensorflow_graphics.geometry.representation.mesh.tests import mesh_test_utils from tensorflow_graphics.util import test_case class MeshSamplerTest(test_case.TestCase): def setUp(self): """Sets up default parameters.""" super(MeshSamplerTest, self).setUp() self._test_sigma_compare_tolerance = 4.0 def compare_poisson_equivalence(self, expected, actual): """Performs equivalence check on Poisson-distributed random variables.""" delta = np.sqrt(expected) * self._test_sigma_compare_tolerance self.assertAllClose(expected, actual, atol=delta) # Tests for generate_random_face_indices @parameterized.parameters( (((), (2,)), (tf.int32, tf.float32)), (((), (None, 1)), (tf.int64, tf.float32)), (((), (None, 3, 4)), (tf.int64, tf.float64)), ) def test_random_face_indices_exception_not_raised(self, shapes, dtypes): """Tests that shape exceptions are not raised for random_face_indices.""" self.assert_exception_is_not_raised(sampler.generate_random_face_indices, shapes, dtypes) @parameterized.parameters( ("face_weights must have a rank greater than 0.", (), ()), ("num_samples must have a rank of 0.", (None,), (1, 2)), ("num_samples must have a rank of 0.", (4, 2), (1,)), ) def test_random_face_indices_shape_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised for random_face_indices.""" self.assert_exception_is_raised( sampler.generate_random_face_indices, error_msg, shapes) def test_negative_weights_random_face_indices_exception(self): """Test for exception for random_face_indices with negative weights.""" face_wts = np.array([0.1, -0.1], dtype=np.float32) num_samples = 10 error_msg = "Condition x >= y did not hold." with self.assertRaisesRegexp(tf.errors.InvalidArgumentError, error_msg): sampler.generate_random_face_indices(num_samples, face_weights=face_wts) @parameterized.parameters( ((0., 0.), 10, (5, 5)), ((0., 0.0, 0.001), 100, (0, 0, 100)), ((0.1, 0.2, 0.3), 1000, (167, 333, 500)), ) def test_random_face_indices(self, face_weights, num_samples, expected): """Test for generate_random_face_indices.""" face_weights = np.array(face_weights, dtype=np.float32) expected = np.array(expected, dtype=np.intp) sample_faces = sampler.generate_random_face_indices( num_samples, face_weights) self.assertEqual(sample_faces.shape[0], num_samples) self.compare_poisson_equivalence(expected, tf.math.bincount(sample_faces)) # Tests for generate_random_barycentric_coordinates @parameterized.parameters( ((1,), (tf.int32)), ((None,), (tf.int64)), ) def test_random_barycentric_coordinates_exception_not_raised( self, shapes, dtypes): """Tests that shape exceptions are not raised for random_barycentric_coordinates.""" self.assert_exception_is_not_raised( sampler.generate_random_barycentric_coordinates, shapes, dtypes) @parameterized.parameters( ("sample_shape must have a rank of 1.", ()), ("sample_shape must have a rank of 1.", (4, None)), ) def test_random_barycentric_coordinates_shape_exception_raised( self, error_msg, *shapes): """Tests that the shape exceptions are properly raised for random_barycentric_coordinates.""" self.assert_exception_is_raised( sampler.generate_random_barycentric_coordinates, error_msg, shapes) @parameterized.parameters( ((5,),), ((10, 1, 3),), ) def test_random_barycentric_coordinates(self, sample_shape): """Test for generate_random_barycentric_coordinates.""" sample_shape = np.array(sample_shape, dtype=np.intp) random_coordinates = sampler.generate_random_barycentric_coordinates( sample_shape=sample_shape) coordinate_sum = tf.reduce_sum(input_tensor=random_coordinates, axis=-1) expected_coordinate_sum = np.ones(shape=sample_shape) self.assertAllClose(expected_coordinate_sum, coordinate_sum) # Tests for weighted_random_sample_triangle_mesh @parameterized.parameters( (((4, 3), (5, 3), (), (5,)), (tf.float32, tf.int32, tf.int32, tf.float32)), (((None, 3), (None, 3), (), (None,)), (tf.float32, tf.int32, tf.int32, tf.float32)), (((3, None, 3), (3, None, 3), (), (3, None)), (tf.float32, tf.int64, tf.int64, tf.float64)), (((3, 6, 5), (3, 5, 3), (), (3, 5)), (tf.float64, tf.int32, tf.int32, tf.float32)), ) def test_weighted_sampler_exception_not_raised(self, shapes, dtypes): """Tests that the shape exceptions are not raised for weighted sampler.""" self.assert_exception_is_not_raised( sampler.weighted_random_sample_triangle_mesh, shapes, dtypes) @parameterized.parameters( ("vertex_attributes must have a rank greater than 1.", (3,), (None, 3), (), (None, 3)), ("faces must have a rank greater than 1.", (5, 2), (None,), (), (None,)), ("face_weights must have a rank greater than 0.", (1, None, 3), (None, 3), (), ()), ("Not all batch dimensions are identical", (4, 4, 2), (3, 5, 3), (), (3, 5)), ("Not all batch dimensions are identical", (4, 2), (5, 3), (), (4,)), ) def test_weighted_sampler_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised for weighted sampler.""" self.assert_exception_is_raised( sampler.weighted_random_sample_triangle_mesh, error_msg, shapes) def test_weighted_sampler_negative_weights(self): """Test for exception with negative weights.""" vertices, faces = mesh_test_utils.create_square_triangle_mesh() face_wts = np.array([-0.3, 0.1, 0.5, 0.6], dtype=np.float32) num_samples = 10 error_msg = "Condition x >= y did not hold." with self.assertRaisesRegexp(tf.errors.InvalidArgumentError, error_msg): sampler.weighted_random_sample_triangle_mesh( vertices, faces, num_samples, face_weights=face_wts) def test_weighted_random_sample(self): """Test for provided face weights.""" faces = np.array([[0, 1, 2], [2, 1, 3]], dtype=np.int32) vertex_attributes = np.array([[0.], [0.], [1.], [1.]], dtype=np.float32) # Equal face weights, mean of sampled attributes = 0.5. expected_mean = np.array([0.5], dtype=np.float32) sample_pts, _ = sampler.weighted_random_sample_triangle_mesh( vertex_attributes, faces, num_samples=1000000, face_weights=(0.5, 0.5)) self.assertAllClose( expected_mean, tf.reduce_mean(input_tensor=sample_pts, axis=-2), atol=1e-3) # Face weights biased towards second face, mean > 0.5 sample_pts, _ = sampler.weighted_random_sample_triangle_mesh( vertex_attributes, faces, num_samples=1000000, face_weights=(0.2, 0.8)) self.assertGreater( tf.reduce_mean(input_tensor=sample_pts, axis=-2), expected_mean) def test_weighted_sampler_jacobian_random(self): """Test the Jacobian of weighted triangle random sampler.""" tensor_vertex_size = np.random.randint(1, 3) tensor_out_shape = np.random.randint(1, 5, size=tensor_vertex_size) tensor_out_shape = tensor_out_shape.tolist() vertex_axis = np.array(((0., 0., 1), (1., 0., 0.), (0., 1., 0.), (0., 0., -1.), (-1., 0., 0.), (0., -1., 0.)), dtype=np.float32) vertex_axis = vertex_axis.reshape([1] * tensor_vertex_size + [6, 3]) faces = np.array(((0, 1, 2), (0, 2, 4), (0, 4, 5), (0, 5, 1), (3, 2, 1), (3, 4, 2), (3, 5, 4), (3, 1, 5)), dtype=np.int32) faces = faces.reshape([1] * tensor_vertex_size + [8, 3]) index_init = np.tile(faces, tensor_out_shape + [1, 1]) vertex_scale = np.random.uniform(0.5, 5., tensor_out_shape + [1] * 2) vertex_init = vertex_axis * vertex_scale index_tensor = tf.convert_to_tensor(value=index_init) face_weights = np.random.uniform( size=index_init.shape[:index_init.ndim - 1]) weights_tensor = tf.convert_to_tensor(value=face_weights) num_samples = np.random.randint(10, 100) def sampler_fn(vertices): sample_pts, _ = sampler.weighted_random_sample_triangle_mesh( vertices, index_tensor, num_samples, weights_tensor, seed=[0, 1], stateless=True) return sample_pts self.assert_jacobian_is_correct_fn( sampler_fn, [vertex_init], atol=1e-4, delta=1e-4) # Tests for area_weighted_random_sample_triangle_mesh @parameterized.parameters( (((4, 3), (5, 3), ()), (tf.float32, tf.int32, tf.int32)), (((None, 3), (None, 3), ()), (tf.float32, tf.int32, tf.int32)), (((3, None, 3), (3, None, 3), ()), (tf.float32, tf.int64, tf.int64)), # Test for vertex attributes + positions (((3, 6, 5), (3, 5, 3), (), (3, 6, 3)), (tf.float64, tf.int32, tf.int32, tf.float32)), ) def test_area_sampler_exception_not_raised(self, shapes, dtypes): """Tests that the shape exceptions are not raised for area weighted sampler.""" self.assert_exception_is_not_raised( sampler.area_weighted_random_sample_triangle_mesh, shapes, dtypes) @parameterized.parameters( ("vertices must have a rank greater than 1.", (3,), (None, 3), ()), ("vertices must have greater than 2 dimensions in axis -1.", (5, 2), (None, 3), ()), ("vertex_positions must have exactly 3 dimensions in axis -1.", (5, 3), (None, 3), (), (3, 2)), ) def test_area_sampler_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised for area weighted sampler.""" self.assert_exception_is_raised( sampler.area_weighted_random_sample_triangle_mesh, error_msg, shapes) def test_area_sampler_distribution(self): """Test for area weighted sampler distribution.""" vertices, faces = mesh_test_utils.create_single_triangle_mesh() vertices = np.repeat(np.expand_dims(vertices, axis=0), 3, axis=0) faces = np.repeat(np.expand_dims(faces, axis=0), 3, axis=0) num_samples = 5000 sample_pts, _ = sampler.area_weighted_random_sample_triangle_mesh( vertices, faces, num_samples) for i in range(3): samples = sample_pts[i, ...] self.assertEqual(samples.shape[-2], num_samples) # Test distribution in 4 quadrants of [0,1]x[0,1] v = samples[:, :2] < [0.5, 0.5] not_v = tf.logical_not(v) quad00 = tf.math.count_nonzero(tf.reduce_all(input_tensor=v, axis=-1)) quad11 = tf.math.count_nonzero(tf.reduce_all(input_tensor=not_v, axis=-1)) quad01 = tf.math.count_nonzero(tf.reduce_all( input_tensor=tf.stack((v[:, 0], not_v[:, 1]), axis=1), axis=-1)) quad10 = tf.math.count_nonzero(tf.reduce_all( input_tensor=tf.stack((not_v[:, 0], v[:, 1]), axis=1), axis=-1)) counts = tf.stack((quad00, quad01, quad10, quad11), axis=0) expected = np.array( [num_samples / 2, num_samples / 4, num_samples / 4, 0], dtype=np.float32) self.compare_poisson_equivalence(expected, counts) def test_face_distribution(self): """Test for distribution of face indices with area weighted sampler.""" vertices, faces = mesh_test_utils.create_square_triangle_mesh() num_samples = 1000 _, sample_faces = sampler.area_weighted_random_sample_triangle_mesh( vertices, faces, num_samples) # All points should be approx poisson distributed among the 4 faces. self.assertEqual(sample_faces.shape[0], num_samples) num_faces = faces.shape[0] expected = np.array([num_samples / num_faces] * num_faces, dtype=np.intp) self.compare_poisson_equivalence(expected, tf.math.bincount(sample_faces)) def test_area_sampler_jacobian_random(self): """Test the Jacobian of area weighted triangle random sampler.""" tensor_vertex_size = np.random.randint(1, 3) tensor_out_shape = np.random.randint(1, 5, size=tensor_vertex_size) tensor_out_shape = tensor_out_shape.tolist() vertex_axis = np.array(((0., 0., 1), (1., 0., 0.), (0., 1., 0.), (0., 0., -1.), (-1., 0., 0.), (0., -1., 0.)), dtype=np.float32) vertex_axis = vertex_axis.reshape([1] * tensor_vertex_size + [6, 3]) faces = np.array(((0, 1, 2), (0, 2, 4), (0, 4, 5), (0, 5, 1), (3, 2, 1), (3, 4, 2), (3, 5, 4), (3, 1, 5)), dtype=np.int32) faces = faces.reshape([1] * tensor_vertex_size + [8, 3]) index_init = np.tile(faces, tensor_out_shape + [1, 1]) vertex_scale = np.random.uniform(0.5, 5., tensor_out_shape + [1] * 2) vertex_init = vertex_axis * vertex_scale index_tensor = tf.convert_to_tensor(value=index_init) num_samples = np.random.randint(10, 100) def sampler_fn(vertices): sample_pts, _ = sampler.area_weighted_random_sample_triangle_mesh( vertices, index_tensor, num_samples, seed=[0, 1], stateless=True) return sample_pts self.assert_jacobian_is_correct_fn( sampler_fn, [vertex_init], atol=1e-4, delta=1e-4) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for uniform mesh sampler.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.representation.mesh import sampler from tensorflow_graphics.geometry.representation.mesh.tests import mesh_test_utils from tensorflow_graphics.util import test_case class MeshSamplerTest(test_case.TestCase): def setUp(self): """Sets up default parameters.""" super(MeshSamplerTest, self).setUp() self._test_sigma_compare_tolerance = 4.0 def compare_poisson_equivalence(self, expected, actual): """Performs equivalence check on Poisson-distributed random variables.""" delta = np.sqrt(expected) * self._test_sigma_compare_tolerance self.assertAllClose(expected, actual, atol=delta) # Tests for generate_random_face_indices @parameterized.parameters( (((), (2,)), (tf.int32, tf.float32)), (((), (None, 1)), (tf.int64, tf.float32)), (((), (None, 3, 4)), (tf.int64, tf.float64)), ) def test_random_face_indices_exception_not_raised(self, shapes, dtypes): """Tests that shape exceptions are not raised for random_face_indices.""" self.assert_exception_is_not_raised(sampler.generate_random_face_indices, shapes, dtypes) @parameterized.parameters( ("face_weights must have a rank greater than 0.", (), ()), ("num_samples must have a rank of 0.", (None,), (1, 2)), ("num_samples must have a rank of 0.", (4, 2), (1,)), ) def test_random_face_indices_shape_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised for random_face_indices.""" self.assert_exception_is_raised( sampler.generate_random_face_indices, error_msg, shapes) def test_negative_weights_random_face_indices_exception(self): """Test for exception for random_face_indices with negative weights.""" face_wts = np.array([0.1, -0.1], dtype=np.float32) num_samples = 10 error_msg = "Condition x >= y did not hold." with self.assertRaisesRegexp(tf.errors.InvalidArgumentError, error_msg): sampler.generate_random_face_indices(num_samples, face_weights=face_wts) @parameterized.parameters( ((0., 0.), 10, (5, 5)), ((0., 0.0, 0.001), 100, (0, 0, 100)), ((0.1, 0.2, 0.3), 1000, (167, 333, 500)), ) def test_random_face_indices(self, face_weights, num_samples, expected): """Test for generate_random_face_indices.""" face_weights = np.array(face_weights, dtype=np.float32) expected = np.array(expected, dtype=np.intp) sample_faces = sampler.generate_random_face_indices( num_samples, face_weights) self.assertEqual(sample_faces.shape[0], num_samples) self.compare_poisson_equivalence(expected, tf.math.bincount(sample_faces)) # Tests for generate_random_barycentric_coordinates @parameterized.parameters( ((1,), (tf.int32)), ((None,), (tf.int64)), ) def test_random_barycentric_coordinates_exception_not_raised( self, shapes, dtypes): """Tests that shape exceptions are not raised for random_barycentric_coordinates.""" self.assert_exception_is_not_raised( sampler.generate_random_barycentric_coordinates, shapes, dtypes) @parameterized.parameters( ("sample_shape must have a rank of 1.", ()), ("sample_shape must have a rank of 1.", (4, None)), ) def test_random_barycentric_coordinates_shape_exception_raised( self, error_msg, *shapes): """Tests that the shape exceptions are properly raised for random_barycentric_coordinates.""" self.assert_exception_is_raised( sampler.generate_random_barycentric_coordinates, error_msg, shapes) @parameterized.parameters( ((5,),), ((10, 1, 3),), ) def test_random_barycentric_coordinates(self, sample_shape): """Test for generate_random_barycentric_coordinates.""" sample_shape = np.array(sample_shape, dtype=np.intp) random_coordinates = sampler.generate_random_barycentric_coordinates( sample_shape=sample_shape) coordinate_sum = tf.reduce_sum(input_tensor=random_coordinates, axis=-1) expected_coordinate_sum = np.ones(shape=sample_shape) self.assertAllClose(expected_coordinate_sum, coordinate_sum) # Tests for weighted_random_sample_triangle_mesh @parameterized.parameters( (((4, 3), (5, 3), (), (5,)), (tf.float32, tf.int32, tf.int32, tf.float32)), (((None, 3), (None, 3), (), (None,)), (tf.float32, tf.int32, tf.int32, tf.float32)), (((3, None, 3), (3, None, 3), (), (3, None)), (tf.float32, tf.int64, tf.int64, tf.float64)), (((3, 6, 5), (3, 5, 3), (), (3, 5)), (tf.float64, tf.int32, tf.int32, tf.float32)), ) def test_weighted_sampler_exception_not_raised(self, shapes, dtypes): """Tests that the shape exceptions are not raised for weighted sampler.""" self.assert_exception_is_not_raised( sampler.weighted_random_sample_triangle_mesh, shapes, dtypes) @parameterized.parameters( ("vertex_attributes must have a rank greater than 1.", (3,), (None, 3), (), (None, 3)), ("faces must have a rank greater than 1.", (5, 2), (None,), (), (None,)), ("face_weights must have a rank greater than 0.", (1, None, 3), (None, 3), (), ()), ("Not all batch dimensions are identical", (4, 4, 2), (3, 5, 3), (), (3, 5)), ("Not all batch dimensions are identical", (4, 2), (5, 3), (), (4,)), ) def test_weighted_sampler_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised for weighted sampler.""" self.assert_exception_is_raised( sampler.weighted_random_sample_triangle_mesh, error_msg, shapes) def test_weighted_sampler_negative_weights(self): """Test for exception with negative weights.""" vertices, faces = mesh_test_utils.create_square_triangle_mesh() face_wts = np.array([-0.3, 0.1, 0.5, 0.6], dtype=np.float32) num_samples = 10 error_msg = "Condition x >= y did not hold." with self.assertRaisesRegexp(tf.errors.InvalidArgumentError, error_msg): sampler.weighted_random_sample_triangle_mesh( vertices, faces, num_samples, face_weights=face_wts) def test_weighted_random_sample(self): """Test for provided face weights.""" faces = np.array([[0, 1, 2], [2, 1, 3]], dtype=np.int32) vertex_attributes = np.array([[0.], [0.], [1.], [1.]], dtype=np.float32) # Equal face weights, mean of sampled attributes = 0.5. expected_mean = np.array([0.5], dtype=np.float32) sample_pts, _ = sampler.weighted_random_sample_triangle_mesh( vertex_attributes, faces, num_samples=1000000, face_weights=(0.5, 0.5)) self.assertAllClose( expected_mean, tf.reduce_mean(input_tensor=sample_pts, axis=-2), atol=1e-3) # Face weights biased towards second face, mean > 0.5 sample_pts, _ = sampler.weighted_random_sample_triangle_mesh( vertex_attributes, faces, num_samples=1000000, face_weights=(0.2, 0.8)) self.assertGreater( tf.reduce_mean(input_tensor=sample_pts, axis=-2), expected_mean) def test_weighted_sampler_jacobian_random(self): """Test the Jacobian of weighted triangle random sampler.""" tensor_vertex_size = np.random.randint(1, 3) tensor_out_shape = np.random.randint(1, 5, size=tensor_vertex_size) tensor_out_shape = tensor_out_shape.tolist() vertex_axis = np.array(((0., 0., 1), (1., 0., 0.), (0., 1., 0.), (0., 0., -1.), (-1., 0., 0.), (0., -1., 0.)), dtype=np.float32) vertex_axis = vertex_axis.reshape([1] * tensor_vertex_size + [6, 3]) faces = np.array(((0, 1, 2), (0, 2, 4), (0, 4, 5), (0, 5, 1), (3, 2, 1), (3, 4, 2), (3, 5, 4), (3, 1, 5)), dtype=np.int32) faces = faces.reshape([1] * tensor_vertex_size + [8, 3]) index_init = np.tile(faces, tensor_out_shape + [1, 1]) vertex_scale = np.random.uniform(0.5, 5., tensor_out_shape + [1] * 2) vertex_init = vertex_axis * vertex_scale index_tensor = tf.convert_to_tensor(value=index_init) face_weights = np.random.uniform( size=index_init.shape[:index_init.ndim - 1]) weights_tensor = tf.convert_to_tensor(value=face_weights) num_samples = np.random.randint(10, 100) def sampler_fn(vertices): sample_pts, _ = sampler.weighted_random_sample_triangle_mesh( vertices, index_tensor, num_samples, weights_tensor, seed=[0, 1], stateless=True) return sample_pts self.assert_jacobian_is_correct_fn( sampler_fn, [vertex_init], atol=1e-4, delta=1e-4) # Tests for area_weighted_random_sample_triangle_mesh @parameterized.parameters( (((4, 3), (5, 3), ()), (tf.float32, tf.int32, tf.int32)), (((None, 3), (None, 3), ()), (tf.float32, tf.int32, tf.int32)), (((3, None, 3), (3, None, 3), ()), (tf.float32, tf.int64, tf.int64)), # Test for vertex attributes + positions (((3, 6, 5), (3, 5, 3), (), (3, 6, 3)), (tf.float64, tf.int32, tf.int32, tf.float32)), ) def test_area_sampler_exception_not_raised(self, shapes, dtypes): """Tests that the shape exceptions are not raised for area weighted sampler.""" self.assert_exception_is_not_raised( sampler.area_weighted_random_sample_triangle_mesh, shapes, dtypes) @parameterized.parameters( ("vertices must have a rank greater than 1.", (3,), (None, 3), ()), ("vertices must have greater than 2 dimensions in axis -1.", (5, 2), (None, 3), ()), ("vertex_positions must have exactly 3 dimensions in axis -1.", (5, 3), (None, 3), (), (3, 2)), ) def test_area_sampler_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised for area weighted sampler.""" self.assert_exception_is_raised( sampler.area_weighted_random_sample_triangle_mesh, error_msg, shapes) def test_area_sampler_distribution(self): """Test for area weighted sampler distribution.""" vertices, faces = mesh_test_utils.create_single_triangle_mesh() vertices = np.repeat(np.expand_dims(vertices, axis=0), 3, axis=0) faces = np.repeat(np.expand_dims(faces, axis=0), 3, axis=0) num_samples = 5000 sample_pts, _ = sampler.area_weighted_random_sample_triangle_mesh( vertices, faces, num_samples) for i in range(3): samples = sample_pts[i, ...] self.assertEqual(samples.shape[-2], num_samples) # Test distribution in 4 quadrants of [0,1]x[0,1] v = samples[:, :2] < [0.5, 0.5] not_v = tf.logical_not(v) quad00 = tf.math.count_nonzero(tf.reduce_all(input_tensor=v, axis=-1)) quad11 = tf.math.count_nonzero(tf.reduce_all(input_tensor=not_v, axis=-1)) quad01 = tf.math.count_nonzero(tf.reduce_all( input_tensor=tf.stack((v[:, 0], not_v[:, 1]), axis=1), axis=-1)) quad10 = tf.math.count_nonzero(tf.reduce_all( input_tensor=tf.stack((not_v[:, 0], v[:, 1]), axis=1), axis=-1)) counts = tf.stack((quad00, quad01, quad10, quad11), axis=0) expected = np.array( [num_samples / 2, num_samples / 4, num_samples / 4, 0], dtype=np.float32) self.compare_poisson_equivalence(expected, counts) def test_face_distribution(self): """Test for distribution of face indices with area weighted sampler.""" vertices, faces = mesh_test_utils.create_square_triangle_mesh() num_samples = 1000 _, sample_faces = sampler.area_weighted_random_sample_triangle_mesh( vertices, faces, num_samples) # All points should be approx poisson distributed among the 4 faces. self.assertEqual(sample_faces.shape[0], num_samples) num_faces = faces.shape[0] expected = np.array([num_samples / num_faces] * num_faces, dtype=np.intp) self.compare_poisson_equivalence(expected, tf.math.bincount(sample_faces)) def test_area_sampler_jacobian_random(self): """Test the Jacobian of area weighted triangle random sampler.""" tensor_vertex_size = np.random.randint(1, 3) tensor_out_shape = np.random.randint(1, 5, size=tensor_vertex_size) tensor_out_shape = tensor_out_shape.tolist() vertex_axis = np.array(((0., 0., 1), (1., 0., 0.), (0., 1., 0.), (0., 0., -1.), (-1., 0., 0.), (0., -1., 0.)), dtype=np.float32) vertex_axis = vertex_axis.reshape([1] * tensor_vertex_size + [6, 3]) faces = np.array(((0, 1, 2), (0, 2, 4), (0, 4, 5), (0, 5, 1), (3, 2, 1), (3, 4, 2), (3, 5, 4), (3, 1, 5)), dtype=np.int32) faces = faces.reshape([1] * tensor_vertex_size + [8, 3]) index_init = np.tile(faces, tensor_out_shape + [1, 1]) vertex_scale = np.random.uniform(0.5, 5., tensor_out_shape + [1] * 2) vertex_init = vertex_axis * vertex_scale index_tensor = tf.convert_to_tensor(value=index_init) num_samples = np.random.randint(10, 100) def sampler_fn(vertices): sample_pts, _ = sampler.area_weighted_random_sample_triangle_mesh( vertices, index_tensor, num_samples, seed=[0, 1], stateless=True) return sample_pts self.assert_jacobian_is_correct_fn( sampler_fn, [vertex_init], atol=1e-4, delta=1e-4) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./.git/hooks/pre-push.sample
#!/bin/sh # An example hook script to verify what is about to be pushed. Called by "git # push" after it has checked the remote status, but before anything has been # pushed. If this script exits with a non-zero status nothing will be pushed. # # This hook is called with the following parameters: # # $1 -- Name of the remote to which the push is being done # $2 -- URL to which the push is being done # # If pushing without using a named remote those arguments will be equal. # # Information about the commits which are being pushed is supplied as lines to # the standard input in the form: # # <local ref> <local sha1> <remote ref> <remote sha1> # # This sample shows how to prevent push of commits where the log message starts # with "WIP" (work in progress). remote="$1" url="$2" z40=0000000000000000000000000000000000000000 while read local_ref local_sha remote_ref remote_sha do if [ "$local_sha" = $z40 ] then # Handle delete : else if [ "$remote_sha" = $z40 ] then # New branch, examine all commits range="$local_sha" else # Update to existing branch, examine new commits range="$remote_sha..$local_sha" fi # Check for WIP commit commit=`git rev-list -n 1 --grep '^WIP' "$range"` if [ -n "$commit" ] then echo >&2 "Found WIP commit in $local_ref, not pushing" exit 1 fi fi done exit 0
#!/bin/sh # An example hook script to verify what is about to be pushed. Called by "git # push" after it has checked the remote status, but before anything has been # pushed. If this script exits with a non-zero status nothing will be pushed. # # This hook is called with the following parameters: # # $1 -- Name of the remote to which the push is being done # $2 -- URL to which the push is being done # # If pushing without using a named remote those arguments will be equal. # # Information about the commits which are being pushed is supplied as lines to # the standard input in the form: # # <local ref> <local sha1> <remote ref> <remote sha1> # # This sample shows how to prevent push of commits where the log message starts # with "WIP" (work in progress). remote="$1" url="$2" z40=0000000000000000000000000000000000000000 while read local_ref local_sha remote_ref remote_sha do if [ "$local_sha" = $z40 ] then # Handle delete : else if [ "$remote_sha" = $z40 ] then # New branch, examine all commits range="$local_sha" else # Update to existing branch, examine new commits range="$remote_sha..$local_sha" fi # Check for WIP commit commit=`git rev-list -n 1 --grep '^WIP' "$range"` if [ -n "$commit" ] then echo >&2 "Found WIP commit in $local_ref, not pushing" exit 1 fi fi done exit 0
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/math/interpolation/tests/slerp_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for slerp.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.math.interpolation import slerp from tensorflow_graphics.util import test_case _SQRT2_DIV2 = np.sqrt(2.0).astype(np.float32) * 0.5 class SlerpTest(test_case.TestCase): def _pick_random_quaternion(self): """Creates a random quaternion with random shape.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() return np.random.normal(size=tensor_shape + [4]) def _quaternion_slerp_helper(self, q1, q2, p): """Calls interpolate function for quaternions.""" return slerp.interpolate(q1, q2, p, slerp.InterpolationType.QUATERNION) def _vector_slerp_helper(self, q1, q2, p): """Calls interpolate function for vectors.""" return slerp.interpolate(q1, q2, p, slerp.InterpolationType.VECTOR) def test_interpolate_raises_exceptions(self): """Tests if unknown methods raise exceptions.""" vector1 = self._pick_random_quaternion() self.assert_exception_is_raised( slerp.interpolate, error_msg="Unknown interpolation type supplied.", shapes=[], vector1=vector1, vector2=-vector1, percent=0.1, method=2) def test_interpolate_with_weights_quaternion_preset(self): """Compares interpolate to quaternion_weights + interpolate_with_weights.""" q1 = self._pick_random_quaternion() q2 = q1 + tf.ones_like(q1) q1 = tf.nn.l2_normalize(q1, axis=-1) q2 = tf.nn.l2_normalize(q2, axis=-1) weight1, weight2 = slerp.quaternion_weights(q1, q2, 0.25) qf = slerp.interpolate_with_weights(q1, q2, weight1, weight2) qi = slerp.interpolate( q1, q2, 0.25, method=slerp.InterpolationType.QUATERNION) self.assertAllClose(qf, qi, atol=1e-9) def test_interpolate_with_weights_vector_preset(self): """Compares interpolate to vector_weights + interpolate_with_weights.""" # Any quaternion is a valid vector q1 = self._pick_random_quaternion() q2 = q1 + tf.ones_like(q1) weight1, weight2 = slerp.vector_weights(q1, q2, 0.75) qf = slerp.interpolate_with_weights(q1, q2, weight1, weight2) qi = slerp.interpolate(q1, q2, 0.75, method=slerp.InterpolationType.VECTOR) self.assertAllClose(qf, qi, atol=1e-9) @parameterized.parameters( # Orthogonal, same hemisphere (((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.5,)), ((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0),)), (((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.5, 0.5, 0.5, 0.5),)), # Same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.408248290463863, 0.0, 0.816496580927726, 0.408248290463863),)), # Same quaternions (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.75,)), ((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0),)), # Anti-polar - small percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.2,)), ((-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0),)), # Anti-polar - large percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.8,)), ((-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0),)), # Extrapolation - same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (-0.5,)), ((0.408248290463863, -0.408248290463863, 0.816496580927726, 0.0),)), # Extrapolation - opposite hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (-0.5,)), ((-0.408248290463863, -0.408248290463863, -0.816496580927726, 0.0),)), ) def test_quaternion_slerp_preset(self, test_inputs, test_outputs): """Tests the accuracy of qslerp against numpy-quaternion values.""" test_inputs = [np.array(test_input).astype(np.float32) for test_input in test_inputs] self.assert_output_is_correct(self._quaternion_slerp_helper, test_inputs, test_outputs, tile=False) def test_unnormalized_quaternion_weights_exception_raised(self): """Tests if quaternion_weights raise exceptions for unnormalized input.""" q1 = self._pick_random_quaternion() q2 = tf.nn.l2_normalize(q1, axis=-1) p = tf.constant((0.5), dtype=q1.dtype) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate(slerp.quaternion_weights(q1, q2, p)) @parameterized.parameters( ((4,), (4,), (1,)), ((None, 4), (None, 4), (None, 1)), ((None, 4), (None, 4), (None, 4)), ) def test_quaternion_weights_exception_not_raised(self, *shapes): """Tests that valid input shapes do not raise exceptions for qslerp.""" self.assert_exception_is_not_raised(slerp.quaternion_weights, shapes) @parameterized.parameters( ("must have exactly 4 dimensions in axis -1", (3,), (4,), (1,)), ("must have exactly 4 dimensions in axis -1", (4,), (3,), (1,)), ("Not all batch dimensions are broadcast-compatible.", (2, 4), (3, 4), (1,)), ("Not all batch dimensions are broadcast-compatible.", (1, 4), (3, 4), (2,)), ) def test_quaternion_weights_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised for qslerp.""" self.assert_exception_is_raised(slerp.quaternion_weights, error_msg, shapes) @parameterized.parameters( # Same quaternions (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.75,)), ( (0.25,), (0.75,), )), # Anti-polar - small percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.2,)), ( (-0.8,), (0.2,), )), # Anti-polar - large percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.8,)), ( (-0.2,), (0.8,), )), ) def test_quaternion_weights_preset(self, test_inputs, test_outputs): """Tests the accuracy of quaternion_weights for problem cases.""" test_inputs = [np.array(test_input).astype(np.float32) for test_input in test_inputs] self.assert_output_is_correct(slerp.quaternion_weights, test_inputs, test_outputs, tile=False) @parameterized.parameters( ((3,), (3,), (1,)), ((None, 4), (None, 4), (None, 1)), ) def test_vector_weights_exception_not_raised(self, *shapes): """Tests that valid inputs do not raise exceptions for vector_weights.""" self.assert_exception_is_not_raised(slerp.vector_weights, shapes) @parameterized.parameters( ("must have the same number of dimensions in axes", (None, 3), (None, 4), (1,)), ("must have the same number of dimensions in axes", (2, 3), (2, 4), (1,)), ("Not all batch dimensions are broadcast-compatible.", (2, 3), (3, 3), (1,)), ("Not all batch dimensions are broadcast-compatible.", (1, 3), (3, 3), (2,)), ) def test_vector_weights_exception_raised(self, error_msg, *shapes): """Tests that shape exceptions are properly raised for vector_weights.""" self.assert_exception_is_raised(slerp.vector_weights, error_msg, shapes) @parameterized.parameters( # Orthogonal, same hemisphere (((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.5,)), ((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0),)), (((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.5, 0.5, 0.5, 0.5),)), # Same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.408248290463863, 0.0, 0.816496580927726, 0.408248290463863),)), # Same vectors (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.75,)), ((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0),)), # Anti-polar - equal weights (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.5,)), ((0.0, 0.0, 0.0, 0.0),)), # Anti-polar - small percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.25,)), ((0.5, 0.0, 0.5, 0.0),)), # Extrapolation - same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (-1.0,)), ((0.0, -_SQRT2_DIV2, _SQRT2_DIV2, 0.0),)), # Extrapolation - opposite hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (1.5,)), ((-_SQRT2_DIV2, -0.0, -_SQRT2_DIV2, 0.0),)), # Unnormalized vectors (((4.0, 0.0), (0.0, 1.0), (0.5,)), ((2.82842712, _SQRT2_DIV2),)), ) def test_vector_slerp_preset(self, test_inputs, test_outputs): """Tests the accuracy of vector slerp results.""" test_inputs = [np.array(test_input).astype(np.float32) for test_input in test_inputs] self.assert_output_is_correct(self._vector_slerp_helper, test_inputs, test_outputs, tile=False) def test_vector_weights_reduce_to_lerp_preset(self): """Tests if vector slerp reduces to lerp for identical vectors as input.""" q1 = tf.constant((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0)) q2 = tf.constant((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0)) p = tf.constant((0.75,), dtype=q1.dtype) w1, w2 = slerp.vector_weights(q1, q2, p) self.assertAllClose(w1, (0.25,), rtol=1e-6) self.assertAllClose(w2, (0.75,), rtol=1e-6) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for slerp.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.math.interpolation import slerp from tensorflow_graphics.util import test_case _SQRT2_DIV2 = np.sqrt(2.0).astype(np.float32) * 0.5 class SlerpTest(test_case.TestCase): def _pick_random_quaternion(self): """Creates a random quaternion with random shape.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() return np.random.normal(size=tensor_shape + [4]) def _quaternion_slerp_helper(self, q1, q2, p): """Calls interpolate function for quaternions.""" return slerp.interpolate(q1, q2, p, slerp.InterpolationType.QUATERNION) def _vector_slerp_helper(self, q1, q2, p): """Calls interpolate function for vectors.""" return slerp.interpolate(q1, q2, p, slerp.InterpolationType.VECTOR) def test_interpolate_raises_exceptions(self): """Tests if unknown methods raise exceptions.""" vector1 = self._pick_random_quaternion() self.assert_exception_is_raised( slerp.interpolate, error_msg="Unknown interpolation type supplied.", shapes=[], vector1=vector1, vector2=-vector1, percent=0.1, method=2) def test_interpolate_with_weights_quaternion_preset(self): """Compares interpolate to quaternion_weights + interpolate_with_weights.""" q1 = self._pick_random_quaternion() q2 = q1 + tf.ones_like(q1) q1 = tf.nn.l2_normalize(q1, axis=-1) q2 = tf.nn.l2_normalize(q2, axis=-1) weight1, weight2 = slerp.quaternion_weights(q1, q2, 0.25) qf = slerp.interpolate_with_weights(q1, q2, weight1, weight2) qi = slerp.interpolate( q1, q2, 0.25, method=slerp.InterpolationType.QUATERNION) self.assertAllClose(qf, qi, atol=1e-9) def test_interpolate_with_weights_vector_preset(self): """Compares interpolate to vector_weights + interpolate_with_weights.""" # Any quaternion is a valid vector q1 = self._pick_random_quaternion() q2 = q1 + tf.ones_like(q1) weight1, weight2 = slerp.vector_weights(q1, q2, 0.75) qf = slerp.interpolate_with_weights(q1, q2, weight1, weight2) qi = slerp.interpolate(q1, q2, 0.75, method=slerp.InterpolationType.VECTOR) self.assertAllClose(qf, qi, atol=1e-9) @parameterized.parameters( # Orthogonal, same hemisphere (((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.5,)), ((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0),)), (((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.5, 0.5, 0.5, 0.5),)), # Same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.408248290463863, 0.0, 0.816496580927726, 0.408248290463863),)), # Same quaternions (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.75,)), ((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0),)), # Anti-polar - small percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.2,)), ((-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0),)), # Anti-polar - large percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.8,)), ((-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0),)), # Extrapolation - same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (-0.5,)), ((0.408248290463863, -0.408248290463863, 0.816496580927726, 0.0),)), # Extrapolation - opposite hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (-0.5,)), ((-0.408248290463863, -0.408248290463863, -0.816496580927726, 0.0),)), ) def test_quaternion_slerp_preset(self, test_inputs, test_outputs): """Tests the accuracy of qslerp against numpy-quaternion values.""" test_inputs = [np.array(test_input).astype(np.float32) for test_input in test_inputs] self.assert_output_is_correct(self._quaternion_slerp_helper, test_inputs, test_outputs, tile=False) def test_unnormalized_quaternion_weights_exception_raised(self): """Tests if quaternion_weights raise exceptions for unnormalized input.""" q1 = self._pick_random_quaternion() q2 = tf.nn.l2_normalize(q1, axis=-1) p = tf.constant((0.5), dtype=q1.dtype) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate(slerp.quaternion_weights(q1, q2, p)) @parameterized.parameters( ((4,), (4,), (1,)), ((None, 4), (None, 4), (None, 1)), ((None, 4), (None, 4), (None, 4)), ) def test_quaternion_weights_exception_not_raised(self, *shapes): """Tests that valid input shapes do not raise exceptions for qslerp.""" self.assert_exception_is_not_raised(slerp.quaternion_weights, shapes) @parameterized.parameters( ("must have exactly 4 dimensions in axis -1", (3,), (4,), (1,)), ("must have exactly 4 dimensions in axis -1", (4,), (3,), (1,)), ("Not all batch dimensions are broadcast-compatible.", (2, 4), (3, 4), (1,)), ("Not all batch dimensions are broadcast-compatible.", (1, 4), (3, 4), (2,)), ) def test_quaternion_weights_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised for qslerp.""" self.assert_exception_is_raised(slerp.quaternion_weights, error_msg, shapes) @parameterized.parameters( # Same quaternions (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.75,)), ( (0.25,), (0.75,), )), # Anti-polar - small percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.2,)), ( (-0.8,), (0.2,), )), # Anti-polar - large percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.8,)), ( (-0.2,), (0.8,), )), ) def test_quaternion_weights_preset(self, test_inputs, test_outputs): """Tests the accuracy of quaternion_weights for problem cases.""" test_inputs = [np.array(test_input).astype(np.float32) for test_input in test_inputs] self.assert_output_is_correct(slerp.quaternion_weights, test_inputs, test_outputs, tile=False) @parameterized.parameters( ((3,), (3,), (1,)), ((None, 4), (None, 4), (None, 1)), ) def test_vector_weights_exception_not_raised(self, *shapes): """Tests that valid inputs do not raise exceptions for vector_weights.""" self.assert_exception_is_not_raised(slerp.vector_weights, shapes) @parameterized.parameters( ("must have the same number of dimensions in axes", (None, 3), (None, 4), (1,)), ("must have the same number of dimensions in axes", (2, 3), (2, 4), (1,)), ("Not all batch dimensions are broadcast-compatible.", (2, 3), (3, 3), (1,)), ("Not all batch dimensions are broadcast-compatible.", (1, 3), (3, 3), (2,)), ) def test_vector_weights_exception_raised(self, error_msg, *shapes): """Tests that shape exceptions are properly raised for vector_weights.""" self.assert_exception_is_raised(slerp.vector_weights, error_msg, shapes) @parameterized.parameters( # Orthogonal, same hemisphere (((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.5,)), ((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0),)), (((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.5, 0.5, 0.5, 0.5),)), # Same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.408248290463863, 0.0, 0.816496580927726, 0.408248290463863),)), # Same vectors (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.75,)), ((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0),)), # Anti-polar - equal weights (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.5,)), ((0.0, 0.0, 0.0, 0.0),)), # Anti-polar - small percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.25,)), ((0.5, 0.0, 0.5, 0.0),)), # Extrapolation - same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (-1.0,)), ((0.0, -_SQRT2_DIV2, _SQRT2_DIV2, 0.0),)), # Extrapolation - opposite hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (1.5,)), ((-_SQRT2_DIV2, -0.0, -_SQRT2_DIV2, 0.0),)), # Unnormalized vectors (((4.0, 0.0), (0.0, 1.0), (0.5,)), ((2.82842712, _SQRT2_DIV2),)), ) def test_vector_slerp_preset(self, test_inputs, test_outputs): """Tests the accuracy of vector slerp results.""" test_inputs = [np.array(test_input).astype(np.float32) for test_input in test_inputs] self.assert_output_is_correct(self._vector_slerp_helper, test_inputs, test_outputs, tile=False) def test_vector_weights_reduce_to_lerp_preset(self): """Tests if vector slerp reduces to lerp for identical vectors as input.""" q1 = tf.constant((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0)) q2 = tf.constant((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0)) p = tf.constant((0.75,), dtype=q1.dtype) w1, w2 = slerp.vector_weights(q1, q2, p) self.assertAllClose(w1, (0.25,), rtol=1e-6) self.assertAllClose(w2, (0.75,), rtol=1e-6) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/datasets/shapenet/shapenet.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Shapenet Core dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import csv import json import os import textwrap import tensorflow.compat.v2 as tf import tensorflow_datasets as tfds from tensorflow_datasets import features as tfds_features from tensorflow_graphics.datasets import features as tfg_features _CITATION = """ @techreport{shapenet2015, title = {{ShapeNet: An Information-Rich 3D Model Repository}}, author = {Chang, Angel X. and Funkhouser, Thomas and Guibas, Leonidas and Hanrahan, Pat and Huang, Qixing and Li, Zimo and Savarese, Silvio and Savva, Manolis and Song, Shuran and Su, Hao and Xiao, Jianxiong and Yi, Li and Yu, Fisher}, number = {arXiv:1512.03012 [cs.GR]}, institution = {Stanford University --- Princeton University --- Toyota Technological Institute at Chicago}, year = {2015} } """ _DESCRIPTION = """ ShapeNetCore is a densely annotated subset of ShapeNet covering 55 common object categories with ~51,300 unique 3D models. Each model in ShapeNetCore is linked to an appropriate synset in WordNet (version 3.0). The synsets will be extracted from the taxonomy.json file in the ShapeNetCore.v2.zip archive and the splits from http://shapenet.cs.stanford.edu/shapenet/obj-zip/SHREC16/all.csv """ _TAXONOMY_FILE_NAME = 'taxonomy.json' _SPLIT_FILE_URL = \ 'http://shapenet.cs.stanford.edu/shapenet/obj-zip/SHREC16/all.csv' class ShapenetConfig(tfds.core.BuilderConfig): """Base class for Shapenet BuilderConfigs. The Shapenet database builder delegates the implementation of info, split_generators and generate_examples to the specified ShapenetConfig. This is done to allow multiple versions of the dataset. """ def info(self, dataset_builder): """Delegated Shapenet._info.""" raise NotImplementedError('Abstract method') def split_generators(self, dl_manager, dataset_builder): """Delegated Shapenet._split_generators.""" raise NotImplementedError('Abstract method') def generate_examples(self, **kwargs): """Delegated Shapenet._generate_examples.""" raise NotImplementedError('Abstract method') class MeshConfig(ShapenetConfig): """A Shapenet config for loading the original .obj files.""" _MODEL_SUBPATH = os.path.join('models', 'model_normalized.obj') def __init__(self, model_subpath=_MODEL_SUBPATH): super(MeshConfig, self).__init__( name='shapenet_trimesh', description=_DESCRIPTION, version=tfds.core.Version('1.0.0')) self.model_subpath = model_subpath def info(self, dataset_builder): return tfds.core.DatasetInfo( builder=dataset_builder, description=_DESCRIPTION, features=tfds_features.FeaturesDict({ 'trimesh': tfg_features.TriangleMesh(), 'label': tfds_features.ClassLabel(num_classes=353), 'model_id': tfds_features.Text(), }), supervised_keys=('trimesh', 'label'), # Homepage of the dataset for documentation homepage='https://shapenet.org/', citation=_CITATION, ) def split_generators(self, dl_manager, dataset_builder): # Extract the synset ids from the taxonomy file and update the ClassLabel # feature. with tf.io.gfile.GFile( os.path.join(dl_manager.manual_dir, _TAXONOMY_FILE_NAME)) as taxonomy_file: labels = [x['synsetId'] for x in json.loads(taxonomy_file.read())] # Remove duplicate labels (the json file contains two identical entries # for synset '04591713'). labels = list(collections.OrderedDict.fromkeys(labels)) dataset_builder.info.features['label'].names = labels split_file = dl_manager.download(_SPLIT_FILE_URL) fieldnames = ['id', 'synset', 'sub_synset', 'model_id', 'split'] model_items = collections.defaultdict(list) with tf.io.gfile.GFile(split_file) as csvfile: for row in csv.DictReader(csvfile, fieldnames): model_items[row['split']].append(row) return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, gen_kwargs={ 'base_dir': dl_manager.manual_dir, 'models': model_items['train'] }, ), tfds.core.SplitGenerator( name=tfds.Split.TEST, gen_kwargs={ 'base_dir': dl_manager.manual_dir, 'models': model_items['test'] }, ), tfds.core.SplitGenerator( name=tfds.Split.VALIDATION, gen_kwargs={ 'base_dir': dl_manager.manual_dir, 'models': model_items['val'] }, ), ] def generate_examples(self, base_dir, models): """Yields examples. The structure of the examples: { 'trimesh': tensorflow_graphics.datasets.features.TriangleMesh 'label': tensorflow_datasets.features.ClassLabel 'model_id': tensorflow_datasets.features.Text } Args: base_dir: The base directory of shapenet. models: The list of models in the split. """ for model in models: synset = model['synset'] model_id = model['model_id'] model_filepath = os.path.join(base_dir, synset, model_id, self.model_subpath) # If the model doesn't exist, skip it. if not tf.io.gfile.exists(model_filepath): continue yield model_id, { 'trimesh': model_filepath, 'label': synset, 'model_id': model_id, } class Shapenet(tfds.core.GeneratorBasedBuilder): """ShapeNetCore V2. Example usage of the dataset: import tensorflow_datasets as tfds from tensorflow_graphics.datasets.shapenet import Shapenet data_set = Shapenet.load( split='train', download_and_prepare_kwargs={ 'download_config': tfds.download.DownloadConfig(manual_dir='~/shapenet_base') }) for example in data_set.take(1): trimesh, label, model_id = example['trimesh'], example['label'], example['model_id'] """ BUILDER_CONFIGS = [MeshConfig()] VERSION = tfds.core.Version('1.0.0') @staticmethod def load(*args, **kwargs): return tfds.load('shapenet', *args, **kwargs) # pytype: disable=wrong-arg-count MANUAL_DOWNLOAD_INSTRUCTIONS = textwrap.dedent("""\ manual_dir should contain the extracted ShapeNetCore.v2.zip archive. You need to register on https://shapenet.org/download/shapenetcore in order to get the link to download the dataset. """) def _info(self): return self.builder_config.info(self) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" return self.builder_config.split_generators(dl_manager, self) def _generate_examples(self, **kwargs): """Yields examples.""" return self.builder_config.generate_examples(**kwargs)
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Shapenet Core dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import csv import json import os import textwrap import tensorflow.compat.v2 as tf import tensorflow_datasets as tfds from tensorflow_datasets import features as tfds_features from tensorflow_graphics.datasets import features as tfg_features _CITATION = """ @techreport{shapenet2015, title = {{ShapeNet: An Information-Rich 3D Model Repository}}, author = {Chang, Angel X. and Funkhouser, Thomas and Guibas, Leonidas and Hanrahan, Pat and Huang, Qixing and Li, Zimo and Savarese, Silvio and Savva, Manolis and Song, Shuran and Su, Hao and Xiao, Jianxiong and Yi, Li and Yu, Fisher}, number = {arXiv:1512.03012 [cs.GR]}, institution = {Stanford University --- Princeton University --- Toyota Technological Institute at Chicago}, year = {2015} } """ _DESCRIPTION = """ ShapeNetCore is a densely annotated subset of ShapeNet covering 55 common object categories with ~51,300 unique 3D models. Each model in ShapeNetCore is linked to an appropriate synset in WordNet (version 3.0). The synsets will be extracted from the taxonomy.json file in the ShapeNetCore.v2.zip archive and the splits from http://shapenet.cs.stanford.edu/shapenet/obj-zip/SHREC16/all.csv """ _TAXONOMY_FILE_NAME = 'taxonomy.json' _SPLIT_FILE_URL = \ 'http://shapenet.cs.stanford.edu/shapenet/obj-zip/SHREC16/all.csv' class ShapenetConfig(tfds.core.BuilderConfig): """Base class for Shapenet BuilderConfigs. The Shapenet database builder delegates the implementation of info, split_generators and generate_examples to the specified ShapenetConfig. This is done to allow multiple versions of the dataset. """ def info(self, dataset_builder): """Delegated Shapenet._info.""" raise NotImplementedError('Abstract method') def split_generators(self, dl_manager, dataset_builder): """Delegated Shapenet._split_generators.""" raise NotImplementedError('Abstract method') def generate_examples(self, **kwargs): """Delegated Shapenet._generate_examples.""" raise NotImplementedError('Abstract method') class MeshConfig(ShapenetConfig): """A Shapenet config for loading the original .obj files.""" _MODEL_SUBPATH = os.path.join('models', 'model_normalized.obj') def __init__(self, model_subpath=_MODEL_SUBPATH): super(MeshConfig, self).__init__( name='shapenet_trimesh', description=_DESCRIPTION, version=tfds.core.Version('1.0.0')) self.model_subpath = model_subpath def info(self, dataset_builder): return tfds.core.DatasetInfo( builder=dataset_builder, description=_DESCRIPTION, features=tfds_features.FeaturesDict({ 'trimesh': tfg_features.TriangleMesh(), 'label': tfds_features.ClassLabel(num_classes=353), 'model_id': tfds_features.Text(), }), supervised_keys=('trimesh', 'label'), # Homepage of the dataset for documentation homepage='https://shapenet.org/', citation=_CITATION, ) def split_generators(self, dl_manager, dataset_builder): # Extract the synset ids from the taxonomy file and update the ClassLabel # feature. with tf.io.gfile.GFile( os.path.join(dl_manager.manual_dir, _TAXONOMY_FILE_NAME)) as taxonomy_file: labels = [x['synsetId'] for x in json.loads(taxonomy_file.read())] # Remove duplicate labels (the json file contains two identical entries # for synset '04591713'). labels = list(collections.OrderedDict.fromkeys(labels)) dataset_builder.info.features['label'].names = labels split_file = dl_manager.download(_SPLIT_FILE_URL) fieldnames = ['id', 'synset', 'sub_synset', 'model_id', 'split'] model_items = collections.defaultdict(list) with tf.io.gfile.GFile(split_file) as csvfile: for row in csv.DictReader(csvfile, fieldnames): model_items[row['split']].append(row) return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, gen_kwargs={ 'base_dir': dl_manager.manual_dir, 'models': model_items['train'] }, ), tfds.core.SplitGenerator( name=tfds.Split.TEST, gen_kwargs={ 'base_dir': dl_manager.manual_dir, 'models': model_items['test'] }, ), tfds.core.SplitGenerator( name=tfds.Split.VALIDATION, gen_kwargs={ 'base_dir': dl_manager.manual_dir, 'models': model_items['val'] }, ), ] def generate_examples(self, base_dir, models): """Yields examples. The structure of the examples: { 'trimesh': tensorflow_graphics.datasets.features.TriangleMesh 'label': tensorflow_datasets.features.ClassLabel 'model_id': tensorflow_datasets.features.Text } Args: base_dir: The base directory of shapenet. models: The list of models in the split. """ for model in models: synset = model['synset'] model_id = model['model_id'] model_filepath = os.path.join(base_dir, synset, model_id, self.model_subpath) # If the model doesn't exist, skip it. if not tf.io.gfile.exists(model_filepath): continue yield model_id, { 'trimesh': model_filepath, 'label': synset, 'model_id': model_id, } class Shapenet(tfds.core.GeneratorBasedBuilder): """ShapeNetCore V2. Example usage of the dataset: import tensorflow_datasets as tfds from tensorflow_graphics.datasets.shapenet import Shapenet data_set = Shapenet.load( split='train', download_and_prepare_kwargs={ 'download_config': tfds.download.DownloadConfig(manual_dir='~/shapenet_base') }) for example in data_set.take(1): trimesh, label, model_id = example['trimesh'], example['label'], example['model_id'] """ BUILDER_CONFIGS = [MeshConfig()] VERSION = tfds.core.Version('1.0.0') @staticmethod def load(*args, **kwargs): return tfds.load('shapenet', *args, **kwargs) # pytype: disable=wrong-arg-count MANUAL_DOWNLOAD_INSTRUCTIONS = textwrap.dedent("""\ manual_dir should contain the extracted ShapeNetCore.v2.zip archive. You need to register on https://shapenet.org/download/shapenetcore in order to get the link to download the dataset. """) def _info(self): return self.builder_config.info(self) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" return self.builder_config.split_generators(dl_manager, self) def _generate_examples(self, **kwargs): """Yields examples.""" return self.builder_config.generate_examples(**kwargs)
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/datasets/shapenet/fakes/02691156/a98038807a61926abce962d6c4b37336/models/model_normalized.obj
# Training data. # g cube v 0.0 0.0 0.0 v 0.0 0.0 1.0 v 0.0 1.0 0.0 v 0.0 1.0 1.0 v 1.0 0.0 0.0 v 1.0 0.0 1.0 v 1.0 1.0 0.0 v 1.0 1.0 1.0 f 1 7 5 f 1 3 7 f 1 4 3 f 1 2 4 f 3 8 7 f 3 4 8 f 5 7 8 f 5 8 6 f 1 5 6 f 1 6 2 f 2 6 8 f 2 8 4
# Training data. # g cube v 0.0 0.0 0.0 v 0.0 0.0 1.0 v 0.0 1.0 0.0 v 0.0 1.0 1.0 v 1.0 0.0 0.0 v 1.0 0.0 1.0 v 1.0 1.0 0.0 v 1.0 1.0 1.0 f 1 7 5 f 1 3 7 f 1 4 3 f 1 2 4 f 3 8 7 f 3 4 8 f 5 7 8 f 5 8 6 f 1 5 6 f 1 6 2 f 2 6 8 f 2 8 4
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/projects/pointnet/augment.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data augmentation utility functions.""" import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_3d def jitter(points, stddev=0.01, clip=0.05): """Randomly jitters points with (clipped) Gaussian noise.""" assert (stddev > 0), "jitter needs a positive sigma" assert (clip > 0), "jitter needs a positive clip" noise = tf.random.normal(points.shape, stddev=stddev) noise = tf.clip_by_value(noise, -clip, +clip) return points + noise def rotate(points): """Randomly rotates a point cloud around the Y axis (UP).""" axis = tf.constant([[0, 1, 0]], dtype=tf.float32) # [1, 3] angle = tf.random.uniform((1, 1), minval=0., maxval=2 * np.pi) # [1, 1] matrix = rotation_matrix_3d.from_axis_angle(axis, angle) # [3, 3] return rotation_matrix_3d.rotate(points, matrix) # [N, 3]
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data augmentation utility functions.""" import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_3d def jitter(points, stddev=0.01, clip=0.05): """Randomly jitters points with (clipped) Gaussian noise.""" assert (stddev > 0), "jitter needs a positive sigma" assert (clip > 0), "jitter needs a positive clip" noise = tf.random.normal(points.shape, stddev=stddev) noise = tf.clip_by_value(noise, -clip, +clip) return points + noise def rotate(points): """Randomly rotates a point cloud around the Y axis (UP).""" axis = tf.constant([[0, 1, 0]], dtype=tf.float32) # [1, 3] angle = tf.random.uniform((1, 1), minval=0., maxval=2 * np.pi) # [1, 1] matrix = rotation_matrix_3d.from_axis_angle(axis, angle) # [3, 3] return rotation_matrix_3d.rotate(points, matrix) # [N, 3]
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/math/vector.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow vector utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def cross(vector1, vector2, axis=-1, name=None): """Computes the cross product between two tensors along an axis. Note: In the following, A1 to An are optional batch dimensions, which should be broadcast compatible. Args: vector1: A tensor of shape `[A1, ..., Ai = 3, ..., An]`, where the dimension i = axis represents a 3d vector. vector2: A tensor of shape `[A1, ..., Ai = 3, ..., An]`, where the dimension i = axis represents a 3d vector. axis: The dimension along which to compute the cross product. name: A name for this op which defaults to "vector_cross". Returns: A tensor of shape `[A1, ..., Ai = 3, ..., An]`, where the dimension i = axis represents the result of the cross product. """ with tf.compat.v1.name_scope(name, "vector_cross", [vector1, vector2]): vector1 = tf.convert_to_tensor(value=vector1) vector2 = tf.convert_to_tensor(value=vector2) shape.check_static( tensor=vector1, tensor_name="vector1", has_dim_equals=(axis, 3)) shape.check_static( tensor=vector2, tensor_name="vector2", has_dim_equals=(axis, 3)) shape.compare_batch_dimensions( tensors=(vector1, vector2), last_axes=-1, broadcast_compatible=True) vector1_x, vector1_y, vector1_z = tf.unstack(vector1, axis=axis) vector2_x, vector2_y, vector2_z = tf.unstack(vector2, axis=axis) n_x = vector1_y * vector2_z - vector1_z * vector2_y n_y = vector1_z * vector2_x - vector1_x * vector2_z n_z = vector1_x * vector2_y - vector1_y * vector2_x return tf.stack((n_x, n_y, n_z), axis=axis) def dot(vector1, vector2, axis=-1, keepdims=True, name=None): """Computes the dot product between two tensors along an axis. Note: In the following, A1 to An are optional batch dimensions, which should be broadcast compatible. Args: vector1: Tensor of rank R and shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a vector. vector2: Tensor of rank R and shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a vector. axis: The dimension along which to compute the dot product. keepdims: If True, retains reduced dimensions with length 1. name: A name for this op which defaults to "vector_dot". Returns: A tensor of shape `[A1, ..., Ai = 1, ..., An]`, where the dimension i = axis represents the result of the dot product. """ with tf.compat.v1.name_scope(name, "vector_dot", [vector1, vector2]): vector1 = tf.convert_to_tensor(value=vector1) vector2 = tf.convert_to_tensor(value=vector2) shape.compare_batch_dimensions( tensors=(vector1, vector2), last_axes=-1, broadcast_compatible=True) shape.compare_dimensions( tensors=(vector1, vector2), axes=axis, tensor_names=("vector1", "vector2")) return tf.reduce_sum( input_tensor=vector1 * vector2, axis=axis, keepdims=keepdims) def reflect(vector, normal, axis=-1, name=None): r"""Computes the reflection direction for an incident vector. For an incident vector \\(\mathbf{v}\\) and normal $$\mathbf{n}$$ this function computes the reflected vector as \\(\mathbf{r} = \mathbf{v} - 2(\mathbf{n}^T\mathbf{v})\mathbf{n}\\). Note: In the following, A1 to An are optional batch dimensions, which should be broadcast compatible. Args: vector: A tensor of shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a vector. normal: A tensor of shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a normal around which the vector needs to be reflected. The normal vector needs to be normalized. axis: The dimension along which to compute the reflection. name: A name for this op which defaults to "vector_reflect". Returns: A tensor of shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a reflected vector. """ with tf.compat.v1.name_scope(name, "vector_reflect", [vector, normal]): vector = tf.convert_to_tensor(value=vector) normal = tf.convert_to_tensor(value=normal) shape.compare_dimensions( tensors=(vector, normal), axes=axis, tensor_names=("vector", "normal")) shape.compare_batch_dimensions( tensors=(vector, normal), last_axes=-1, broadcast_compatible=True) normal = asserts.assert_normalized(normal, axis=axis) dot_product = dot(vector, normal, axis=axis) return vector - 2.0 * dot_product * normal # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow vector utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def cross(vector1, vector2, axis=-1, name=None): """Computes the cross product between two tensors along an axis. Note: In the following, A1 to An are optional batch dimensions, which should be broadcast compatible. Args: vector1: A tensor of shape `[A1, ..., Ai = 3, ..., An]`, where the dimension i = axis represents a 3d vector. vector2: A tensor of shape `[A1, ..., Ai = 3, ..., An]`, where the dimension i = axis represents a 3d vector. axis: The dimension along which to compute the cross product. name: A name for this op which defaults to "vector_cross". Returns: A tensor of shape `[A1, ..., Ai = 3, ..., An]`, where the dimension i = axis represents the result of the cross product. """ with tf.compat.v1.name_scope(name, "vector_cross", [vector1, vector2]): vector1 = tf.convert_to_tensor(value=vector1) vector2 = tf.convert_to_tensor(value=vector2) shape.check_static( tensor=vector1, tensor_name="vector1", has_dim_equals=(axis, 3)) shape.check_static( tensor=vector2, tensor_name="vector2", has_dim_equals=(axis, 3)) shape.compare_batch_dimensions( tensors=(vector1, vector2), last_axes=-1, broadcast_compatible=True) vector1_x, vector1_y, vector1_z = tf.unstack(vector1, axis=axis) vector2_x, vector2_y, vector2_z = tf.unstack(vector2, axis=axis) n_x = vector1_y * vector2_z - vector1_z * vector2_y n_y = vector1_z * vector2_x - vector1_x * vector2_z n_z = vector1_x * vector2_y - vector1_y * vector2_x return tf.stack((n_x, n_y, n_z), axis=axis) def dot(vector1, vector2, axis=-1, keepdims=True, name=None): """Computes the dot product between two tensors along an axis. Note: In the following, A1 to An are optional batch dimensions, which should be broadcast compatible. Args: vector1: Tensor of rank R and shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a vector. vector2: Tensor of rank R and shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a vector. axis: The dimension along which to compute the dot product. keepdims: If True, retains reduced dimensions with length 1. name: A name for this op which defaults to "vector_dot". Returns: A tensor of shape `[A1, ..., Ai = 1, ..., An]`, where the dimension i = axis represents the result of the dot product. """ with tf.compat.v1.name_scope(name, "vector_dot", [vector1, vector2]): vector1 = tf.convert_to_tensor(value=vector1) vector2 = tf.convert_to_tensor(value=vector2) shape.compare_batch_dimensions( tensors=(vector1, vector2), last_axes=-1, broadcast_compatible=True) shape.compare_dimensions( tensors=(vector1, vector2), axes=axis, tensor_names=("vector1", "vector2")) return tf.reduce_sum( input_tensor=vector1 * vector2, axis=axis, keepdims=keepdims) def reflect(vector, normal, axis=-1, name=None): r"""Computes the reflection direction for an incident vector. For an incident vector \\(\mathbf{v}\\) and normal $$\mathbf{n}$$ this function computes the reflected vector as \\(\mathbf{r} = \mathbf{v} - 2(\mathbf{n}^T\mathbf{v})\mathbf{n}\\). Note: In the following, A1 to An are optional batch dimensions, which should be broadcast compatible. Args: vector: A tensor of shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a vector. normal: A tensor of shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a normal around which the vector needs to be reflected. The normal vector needs to be normalized. axis: The dimension along which to compute the reflection. name: A name for this op which defaults to "vector_reflect". Returns: A tensor of shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a reflected vector. """ with tf.compat.v1.name_scope(name, "vector_reflect", [vector, normal]): vector = tf.convert_to_tensor(value=vector) normal = tf.convert_to_tensor(value=normal) shape.compare_dimensions( tensors=(vector, normal), axes=axis, tensor_names=("vector", "normal")) shape.compare_batch_dimensions( tensors=(vector, normal), last_axes=-1, broadcast_compatible=True) normal = asserts.assert_normalized(normal, axis=axis) dot_product = dot(vector, normal, axis=axis) return vector - 2.0 * dot_product * normal # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/notebooks/reflectance.ipynb
{ "cells": [ { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Udb-wL0GEJ5j" }, "source": [ "##### Copyright 2019 Google LLC." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "cellView": "form", "colab": {}, "colab_type": "code", "id": "5oYucXhdRXlW" }, "outputs": [], "source": [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "3GzW9UkQRg7L" }, "source": [ "# Light interaction with materials\n", "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n", " \u003ctd\u003e\n", " \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/graphics/blob/master/tensorflow_graphics/notebooks/reflectance.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n", " \u003c/td\u003e\n", " \u003ctd\u003e\n", " \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/graphics/blob/master/tensorflow_graphics/notebooks/reflectance.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n", " \u003c/td\u003e\n", "\u003c/table\u003e" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "N78wnH25iV5m" }, "source": [ "The world around us is very complex and is made of a wide array of materials ranging from glass to wood. Each material possesses its own intrinsic properties and interacts differently with light. For instance, some are diffuse (e.g. paper or marble) and given a lighting condition, look the same from any angle. Other materials (e.g. metal) have an appearance that can vary significantly and exhibit view dependent effects such as specularities.\n", "\n", "Modelling exactly how light interacts with materials is a complex process that involves effects like sub-surface scattering (e.g. skin) and refraction (e.g. water). In this Colab, we focus on the most common effect which is reflection. [Bidirectional reflectance distribution functions (BRDF)](https://en.wikipedia.org/wiki/Bidirectional_reflectance_distribution_function) is the method of choice when it comes to modelling reflectance. Given the direction of incoming light, BRDFs control the amount of light that bounces in the direction the surface is being observed (any gray vector in the image below).\n", "\n", "![](https://storage.googleapis.com/tensorflow-graphics/notebooks/reflectance/brdf.jpg)\n", "\n", "In this Colab, a light we be shone onto three spheres, each with a material described in the image above, where the specular material is going to be modelled with the [Phong specular model](https://en.wikipedia.org/wiki/Phong_reflection_model).\n", "\n", "**Note**: This Colab covers an advanced topic and hence focuses on providing a controllable toy example to form a high level understanding of BRDFs rather than providing step by step details. For those interested, these details are nevertheless available in the code." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "E87e3hO5SWN9" }, "source": [ "## Setup \u0026 Imports\n", "If Tensorflow Graphics is not installed on your system, the following cell can install the Tensorflow Graphics package for you." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "t60P7UZASZTy" }, "outputs": [], "source": [ "!pip install tensorflow_graphics" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Fx_oEf1ySc-V" }, "source": [ "Now that Tensorflow Graphics is installed, let's import everything needed to run the demo contained in this notebook." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "D8jOq5AMcB8b" }, "outputs": [], "source": [ "import math as m\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import tensorflow as tf\n", "\n", "from tensorflow_graphics.rendering.reflectance import lambertian\n", "from tensorflow_graphics.rendering.reflectance import phong\n", "from tensorflow_graphics.rendering.camera import orthographic\n", "from tensorflow_graphics.geometry.representation import grid\n", "from tensorflow_graphics.geometry.representation import ray\n", "from tensorflow_graphics.geometry.representation import vector" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "n5SYoy4pXRms" }, "source": [ "## Controllable lighting of a sphere" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "cellView": "form", "colab": {}, "colab_type": "code", "id": "fAbPR3iyv_z7" }, "outputs": [], "source": [ "###############\n", "# UI controls #\n", "###############\n", "#@title Controls { vertical-output: false, run: \"auto\" }\n", "light_x_position = -0.4 #@param { type: \"slider\", min: -1, max: 1 , step: 0.05 }\n", "albedo_red = 0.7 #@param { type: \"slider\", min: 0.0, max: 1.0 , step: 0.1 }\n", "albedo_green = 1 #@param { type: \"slider\", min: 0.0, max: 1.0 , step: 0.1 }\n", "albedo_blue = 1 #@param { type: \"slider\", min: 0.0, max: 1.0 , step: 0.1 }\n", "light_red = 1 #@param { type: \"slider\", min: 0.0, max: 1.0 , step: 0.1 }\n", "light_green = 1 #@param { type: \"slider\", min: 0.0, max: 1.0 , step: 0.1 }\n", "light_blue = 1 #@param { type: \"slider\", min: 0.0, max: 1.0 , step: 0.1 }\n", "specular_percentage = 0.25 #@param { type: \"slider\", min: 0, max: 1 , step: 0.01 }\n", "shininess = 4 #@param { type: \"slider\", min: 0, max: 10, step: 1 }\n", "diffuse_percentage = 1.0 - specular_percentage\n", "dtype = np.float64\n", "albedo = np.array((albedo_red, albedo_green, albedo_blue), dtype=dtype)\n", "\n", "def compute_intersection_normal_sphere(image_width, image_height, sphere_radius,\n", " sphere_center, dtype):\n", " pixel_grid_start = np.array((0.5, 0.5), dtype=dtype)\n", " pixel_grid_end = np.array((image_width - 0.5, image_height - 0.5), dtype=dtype)\n", " pixel_nb = np.array((image_width, image_height))\n", " pixels = grid.generate(pixel_grid_start, pixel_grid_end, pixel_nb)\n", "\n", " pixel_ray = tf.math.l2_normalize(orthographic.ray(pixels), axis=-1)\n", " zero_depth = np.zeros([image_width, image_height, 1])\n", " pixels_3d = orthographic.unproject(pixels, zero_depth)\n", "\n", " intersections_points, normals = ray.intersection_ray_sphere(\n", " sphere_center, sphere_radius, pixel_ray, pixels_3d)\n", " intersections_points = np.nan_to_num(intersections_points)\n", " normals = np.nan_to_num(normals)\n", " return intersections_points[0, :, :, :], normals[0, :, :, :]\n", "\n", "#####################################\n", "# Setup the image, sphere and light #\n", "#####################################\n", "# Image dimensions\n", "image_width = 400\n", "image_height = 300\n", "\n", "# Sphere center and radius\n", "sphere_radius = np.array((100.0,), dtype=dtype)\n", "sphere_center = np.array((image_width / 2.0, image_height / 2.0, 300.0),\n", " dtype=dtype)\n", "\n", "# Set the light along the image plane\n", "light_position = np.array((image_width / 2.0 + light_x_position * image_width,\n", " image_height / 2.0, 0.0),\n", " dtype=dtype)\n", "vector_light_to_sphere_center = light_position - sphere_center\n", "light_intensity_scale = vector.dot(\n", " vector_light_to_sphere_center, vector_light_to_sphere_center,\n", " axis=-1) * 4.0 * m.pi\n", "light_intensity = np.array(\n", " (light_red, light_green, light_blue)) * light_intensity_scale\n", "\n", "################################################################################################\n", "# For each pixel in the image, estimate the corresponding surface point and associated normal. #\n", "################################################################################################\n", "intersection_3d, surface_normal = compute_intersection_normal_sphere(\n", " image_width, image_height, sphere_radius, sphere_center, dtype)\n", "\n", "#######################################\n", "# Reflectance and radiance estimation #\n", "#######################################\n", "incoming_light_direction = tf.math.l2_normalize(\n", " intersection_3d - light_position, axis=-1)\n", "outgoing_ray = np.array((0.0, 0.0, -1.0), dtype=dtype)\n", "albedo = tf.broadcast_to(albedo, tf.shape(surface_normal))\n", "\n", "# Lambertian BRDF\n", "brdf_lambertian = diffuse_percentage * lambertian.brdf(incoming_light_direction, outgoing_ray,\n", " surface_normal, albedo)\n", "# Phong BRDF\n", "brdf_phong = specular_percentage * phong.brdf(incoming_light_direction, outgoing_ray, surface_normal,\n", " np.array((shininess,), dtype=dtype), albedo)\n", "# Composite BRDF\n", "brdf_composite = brdf_lambertian + brdf_phong\n", "# Irradiance\n", "cosine_term = vector.dot(surface_normal, -incoming_light_direction)\n", "cosine_term = tf.math.maximum(tf.zeros_like(cosine_term), cosine_term)\n", "vector_light_to_surface = intersection_3d - light_position\n", "light_to_surface_distance_squared = vector.dot(\n", " vector_light_to_surface, vector_light_to_surface, axis=-1)\n", "irradiance = light_intensity / (4 * m.pi *\n", " light_to_surface_distance_squared) * cosine_term\n", "# Rendering equation\n", "zeros = tf.zeros(intersection_3d.shape)\n", "radiance = brdf_composite * irradiance\n", "radiance_lambertian = brdf_lambertian * irradiance\n", "radiance_phong = brdf_phong * irradiance\n", "\n", "###############################\n", "# Display the rendered sphere #\n", "###############################\n", "# Saturates radiances at 1 for rendering purposes.\n", "radiance = np.minimum(radiance, 1.0)\n", "radiance_lambertian = np.minimum(radiance_lambertian, 1.0)\n", "radiance_phong = np.minimum(radiance_phong, 1.0)\n", "# Gamma correction\n", "radiance = np.power(radiance, 1.0 / 2.2)\n", "radiance_lambertian = np.power(radiance_lambertian, 1.0 / 2.2)\n", "radiance_phong = np.power(radiance_phong, 1.0 / 2.2)\n", "\n", "plt.figure(figsize=(20, 20))\n", "\n", "# Diffuse\n", "radiance_lambertian = np.transpose(radiance_lambertian, (1, 0, 2))\n", "ax = plt.subplot(\"131\")\n", "ax.axes.get_xaxis().set_visible(False)\n", "ax.axes.get_yaxis().set_visible(False)\n", "ax.grid(False)\n", "ax.set_title(\"Lambertian\")\n", "_ = ax.imshow(radiance_lambertian)\n", "\n", "# Specular\n", "radiance_phong = np.transpose(radiance_phong, (1, 0, 2))\n", "ax = plt.subplot(\"132\")\n", "ax.axes.get_xaxis().set_visible(False)\n", "ax.axes.get_yaxis().set_visible(False)\n", "ax.grid(False)\n", "ax.set_title(\"Specular - Phong\")\n", "_ = ax.imshow(radiance_phong)\n", "\n", "# Diffuse + specular\n", "radiance = np.transpose(radiance, (1, 0, 2))\n", "ax = plt.subplot(\"133\")\n", "ax.axes.get_xaxis().set_visible(False)\n", "ax.axes.get_yaxis().set_visible(False)\n", "ax.grid(False)\n", "ax.set_title(\"Combined lambertian and specular\")\n", "_ = ax.imshow(radiance)" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "reflectance.ipynb", "provenance": [], "toc_visible": true, "private_outputs": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }
{ "cells": [ { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Udb-wL0GEJ5j" }, "source": [ "##### Copyright 2019 Google LLC." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "cellView": "form", "colab": {}, "colab_type": "code", "id": "5oYucXhdRXlW" }, "outputs": [], "source": [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "3GzW9UkQRg7L" }, "source": [ "# Light interaction with materials\n", "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n", " \u003ctd\u003e\n", " \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/graphics/blob/master/tensorflow_graphics/notebooks/reflectance.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n", " \u003c/td\u003e\n", " \u003ctd\u003e\n", " \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/graphics/blob/master/tensorflow_graphics/notebooks/reflectance.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n", " \u003c/td\u003e\n", "\u003c/table\u003e" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "N78wnH25iV5m" }, "source": [ "The world around us is very complex and is made of a wide array of materials ranging from glass to wood. Each material possesses its own intrinsic properties and interacts differently with light. For instance, some are diffuse (e.g. paper or marble) and given a lighting condition, look the same from any angle. Other materials (e.g. metal) have an appearance that can vary significantly and exhibit view dependent effects such as specularities.\n", "\n", "Modelling exactly how light interacts with materials is a complex process that involves effects like sub-surface scattering (e.g. skin) and refraction (e.g. water). In this Colab, we focus on the most common effect which is reflection. [Bidirectional reflectance distribution functions (BRDF)](https://en.wikipedia.org/wiki/Bidirectional_reflectance_distribution_function) is the method of choice when it comes to modelling reflectance. Given the direction of incoming light, BRDFs control the amount of light that bounces in the direction the surface is being observed (any gray vector in the image below).\n", "\n", "![](https://storage.googleapis.com/tensorflow-graphics/notebooks/reflectance/brdf.jpg)\n", "\n", "In this Colab, a light we be shone onto three spheres, each with a material described in the image above, where the specular material is going to be modelled with the [Phong specular model](https://en.wikipedia.org/wiki/Phong_reflection_model).\n", "\n", "**Note**: This Colab covers an advanced topic and hence focuses on providing a controllable toy example to form a high level understanding of BRDFs rather than providing step by step details. For those interested, these details are nevertheless available in the code." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "E87e3hO5SWN9" }, "source": [ "## Setup \u0026 Imports\n", "If Tensorflow Graphics is not installed on your system, the following cell can install the Tensorflow Graphics package for you." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "t60P7UZASZTy" }, "outputs": [], "source": [ "!pip install tensorflow_graphics" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Fx_oEf1ySc-V" }, "source": [ "Now that Tensorflow Graphics is installed, let's import everything needed to run the demo contained in this notebook." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "D8jOq5AMcB8b" }, "outputs": [], "source": [ "import math as m\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import tensorflow as tf\n", "\n", "from tensorflow_graphics.rendering.reflectance import lambertian\n", "from tensorflow_graphics.rendering.reflectance import phong\n", "from tensorflow_graphics.rendering.camera import orthographic\n", "from tensorflow_graphics.geometry.representation import grid\n", "from tensorflow_graphics.geometry.representation import ray\n", "from tensorflow_graphics.geometry.representation import vector" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "n5SYoy4pXRms" }, "source": [ "## Controllable lighting of a sphere" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "cellView": "form", "colab": {}, "colab_type": "code", "id": "fAbPR3iyv_z7" }, "outputs": [], "source": [ "###############\n", "# UI controls #\n", "###############\n", "#@title Controls { vertical-output: false, run: \"auto\" }\n", "light_x_position = -0.4 #@param { type: \"slider\", min: -1, max: 1 , step: 0.05 }\n", "albedo_red = 0.7 #@param { type: \"slider\", min: 0.0, max: 1.0 , step: 0.1 }\n", "albedo_green = 1 #@param { type: \"slider\", min: 0.0, max: 1.0 , step: 0.1 }\n", "albedo_blue = 1 #@param { type: \"slider\", min: 0.0, max: 1.0 , step: 0.1 }\n", "light_red = 1 #@param { type: \"slider\", min: 0.0, max: 1.0 , step: 0.1 }\n", "light_green = 1 #@param { type: \"slider\", min: 0.0, max: 1.0 , step: 0.1 }\n", "light_blue = 1 #@param { type: \"slider\", min: 0.0, max: 1.0 , step: 0.1 }\n", "specular_percentage = 0.25 #@param { type: \"slider\", min: 0, max: 1 , step: 0.01 }\n", "shininess = 4 #@param { type: \"slider\", min: 0, max: 10, step: 1 }\n", "diffuse_percentage = 1.0 - specular_percentage\n", "dtype = np.float64\n", "albedo = np.array((albedo_red, albedo_green, albedo_blue), dtype=dtype)\n", "\n", "def compute_intersection_normal_sphere(image_width, image_height, sphere_radius,\n", " sphere_center, dtype):\n", " pixel_grid_start = np.array((0.5, 0.5), dtype=dtype)\n", " pixel_grid_end = np.array((image_width - 0.5, image_height - 0.5), dtype=dtype)\n", " pixel_nb = np.array((image_width, image_height))\n", " pixels = grid.generate(pixel_grid_start, pixel_grid_end, pixel_nb)\n", "\n", " pixel_ray = tf.math.l2_normalize(orthographic.ray(pixels), axis=-1)\n", " zero_depth = np.zeros([image_width, image_height, 1])\n", " pixels_3d = orthographic.unproject(pixels, zero_depth)\n", "\n", " intersections_points, normals = ray.intersection_ray_sphere(\n", " sphere_center, sphere_radius, pixel_ray, pixels_3d)\n", " intersections_points = np.nan_to_num(intersections_points)\n", " normals = np.nan_to_num(normals)\n", " return intersections_points[0, :, :, :], normals[0, :, :, :]\n", "\n", "#####################################\n", "# Setup the image, sphere and light #\n", "#####################################\n", "# Image dimensions\n", "image_width = 400\n", "image_height = 300\n", "\n", "# Sphere center and radius\n", "sphere_radius = np.array((100.0,), dtype=dtype)\n", "sphere_center = np.array((image_width / 2.0, image_height / 2.0, 300.0),\n", " dtype=dtype)\n", "\n", "# Set the light along the image plane\n", "light_position = np.array((image_width / 2.0 + light_x_position * image_width,\n", " image_height / 2.0, 0.0),\n", " dtype=dtype)\n", "vector_light_to_sphere_center = light_position - sphere_center\n", "light_intensity_scale = vector.dot(\n", " vector_light_to_sphere_center, vector_light_to_sphere_center,\n", " axis=-1) * 4.0 * m.pi\n", "light_intensity = np.array(\n", " (light_red, light_green, light_blue)) * light_intensity_scale\n", "\n", "################################################################################################\n", "# For each pixel in the image, estimate the corresponding surface point and associated normal. #\n", "################################################################################################\n", "intersection_3d, surface_normal = compute_intersection_normal_sphere(\n", " image_width, image_height, sphere_radius, sphere_center, dtype)\n", "\n", "#######################################\n", "# Reflectance and radiance estimation #\n", "#######################################\n", "incoming_light_direction = tf.math.l2_normalize(\n", " intersection_3d - light_position, axis=-1)\n", "outgoing_ray = np.array((0.0, 0.0, -1.0), dtype=dtype)\n", "albedo = tf.broadcast_to(albedo, tf.shape(surface_normal))\n", "\n", "# Lambertian BRDF\n", "brdf_lambertian = diffuse_percentage * lambertian.brdf(incoming_light_direction, outgoing_ray,\n", " surface_normal, albedo)\n", "# Phong BRDF\n", "brdf_phong = specular_percentage * phong.brdf(incoming_light_direction, outgoing_ray, surface_normal,\n", " np.array((shininess,), dtype=dtype), albedo)\n", "# Composite BRDF\n", "brdf_composite = brdf_lambertian + brdf_phong\n", "# Irradiance\n", "cosine_term = vector.dot(surface_normal, -incoming_light_direction)\n", "cosine_term = tf.math.maximum(tf.zeros_like(cosine_term), cosine_term)\n", "vector_light_to_surface = intersection_3d - light_position\n", "light_to_surface_distance_squared = vector.dot(\n", " vector_light_to_surface, vector_light_to_surface, axis=-1)\n", "irradiance = light_intensity / (4 * m.pi *\n", " light_to_surface_distance_squared) * cosine_term\n", "# Rendering equation\n", "zeros = tf.zeros(intersection_3d.shape)\n", "radiance = brdf_composite * irradiance\n", "radiance_lambertian = brdf_lambertian * irradiance\n", "radiance_phong = brdf_phong * irradiance\n", "\n", "###############################\n", "# Display the rendered sphere #\n", "###############################\n", "# Saturates radiances at 1 for rendering purposes.\n", "radiance = np.minimum(radiance, 1.0)\n", "radiance_lambertian = np.minimum(radiance_lambertian, 1.0)\n", "radiance_phong = np.minimum(radiance_phong, 1.0)\n", "# Gamma correction\n", "radiance = np.power(radiance, 1.0 / 2.2)\n", "radiance_lambertian = np.power(radiance_lambertian, 1.0 / 2.2)\n", "radiance_phong = np.power(radiance_phong, 1.0 / 2.2)\n", "\n", "plt.figure(figsize=(20, 20))\n", "\n", "# Diffuse\n", "radiance_lambertian = np.transpose(radiance_lambertian, (1, 0, 2))\n", "ax = plt.subplot(\"131\")\n", "ax.axes.get_xaxis().set_visible(False)\n", "ax.axes.get_yaxis().set_visible(False)\n", "ax.grid(False)\n", "ax.set_title(\"Lambertian\")\n", "_ = ax.imshow(radiance_lambertian)\n", "\n", "# Specular\n", "radiance_phong = np.transpose(radiance_phong, (1, 0, 2))\n", "ax = plt.subplot(\"132\")\n", "ax.axes.get_xaxis().set_visible(False)\n", "ax.axes.get_yaxis().set_visible(False)\n", "ax.grid(False)\n", "ax.set_title(\"Specular - Phong\")\n", "_ = ax.imshow(radiance_phong)\n", "\n", "# Diffuse + specular\n", "radiance = np.transpose(radiance, (1, 0, 2))\n", "ax = plt.subplot(\"133\")\n", "ax.axes.get_xaxis().set_visible(False)\n", "ax.axes.get_yaxis().set_visible(False)\n", "ax.grid(False)\n", "ax.set_title(\"Combined lambertian and specular\")\n", "_ = ax.imshow(radiance)" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "reflectance.ipynb", "provenance": [], "toc_visible": true, "private_outputs": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/rendering/opengl/gl_shader_storage_buffer.cc
/* Copyright 2020 The TensorFlow Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "gl_shader_storage_buffer.h" #include <GLES3/gl32.h> #include "tensorflow/core/lib/core/status.h" namespace gl_utils { ShaderStorageBuffer::ShaderStorageBuffer(GLuint buffer) : buffer_(buffer) {} ShaderStorageBuffer::~ShaderStorageBuffer() { glDeleteBuffers(1, &buffer_); } tensorflow::Status ShaderStorageBuffer::Create( std::unique_ptr<ShaderStorageBuffer>* shader_storage_buffer) { GLuint buffer; // Generate one buffer object. TFG_RETURN_IF_EGL_ERROR(glGenBuffers(1, &buffer)); *shader_storage_buffer = std::unique_ptr<ShaderStorageBuffer>(new ShaderStorageBuffer(buffer)); return tensorflow::Status::OK(); } tensorflow::Status ShaderStorageBuffer::BindBufferBase(GLuint index) const { TFG_RETURN_IF_EGL_ERROR( glBindBufferBase(GL_SHADER_STORAGE_BUFFER, index, buffer_)); return tensorflow::Status::OK(); } } // namespace gl_utils
/* Copyright 2020 The TensorFlow Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "gl_shader_storage_buffer.h" #include <GLES3/gl32.h> #include "tensorflow/core/lib/core/status.h" namespace gl_utils { ShaderStorageBuffer::ShaderStorageBuffer(GLuint buffer) : buffer_(buffer) {} ShaderStorageBuffer::~ShaderStorageBuffer() { glDeleteBuffers(1, &buffer_); } tensorflow::Status ShaderStorageBuffer::Create( std::unique_ptr<ShaderStorageBuffer>* shader_storage_buffer) { GLuint buffer; // Generate one buffer object. TFG_RETURN_IF_EGL_ERROR(glGenBuffers(1, &buffer)); *shader_storage_buffer = std::unique_ptr<ShaderStorageBuffer>(new ShaderStorageBuffer(buffer)); return tensorflow::Status::OK(); } tensorflow::Status ShaderStorageBuffer::BindBufferBase(GLuint index) const { TFG_RETURN_IF_EGL_ERROR( glBindBufferBase(GL_SHADER_STORAGE_BUFFER, index, buffer_)); return tensorflow::Status::OK(); } } // namespace gl_utils
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/representation/triangle.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow triangle utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def normal(v0, v1, v2, clockwise=False, normalize=True, name=None): """Computes face normals (triangles). Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: v0: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vertex of a triangle. v1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vertex of a triangle. v2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the third vertex of a triangle. clockwise: Winding order to determine front-facing triangles. normalize: A `bool` indicating whether output normals should be normalized by the function. name: A name for this op. Defaults to "triangle_normal". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized vector. Raises: ValueError: If the shape of `v0`, `v1`, or `v2` is not supported. """ with tf.compat.v1.name_scope(name, "triangle_normal", [v0, v1, v2]): v0 = tf.convert_to_tensor(value=v0) v1 = tf.convert_to_tensor(value=v1) v2 = tf.convert_to_tensor(value=v2) shape.check_static(tensor=v0, tensor_name="v0", has_dim_equals=(-1, 3)) shape.check_static(tensor=v1, tensor_name="v1", has_dim_equals=(-1, 3)) shape.check_static(tensor=v2, tensor_name="v2", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(v0, v1, v2), last_axes=-2, broadcast_compatible=True) normal_vector = vector.cross(v1 - v0, v2 - v0, axis=-1) normal_vector = asserts.assert_nonzero_norm(normal_vector) if not clockwise: normal_vector *= -1.0 if normalize: return tf.nn.l2_normalize(normal_vector, axis=-1) return normal_vector def area(v0, v1, v2, name=None): """Computes triangle areas. Note: Computed triangle area = 0.5 * | e1 x e2 | where e1 and e2 are edges of triangle. A degenerate triangle will return 0 area, whereas the normal for a degenerate triangle is not defined. In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: v0: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vertex of a triangle. v1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vertex of a triangle. v2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the third vertex of a triangle. name: A name for this op. Defaults to "triangle_area". Returns: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a normalized vector. """ with tf.compat.v1.name_scope(name, "triangle_area", [v0, v1, v2]): v0 = tf.convert_to_tensor(value=v0) v1 = tf.convert_to_tensor(value=v1) v2 = tf.convert_to_tensor(value=v2) shape.check_static(tensor=v0, tensor_name="v0", has_dim_equals=(-1, 3)) shape.check_static(tensor=v1, tensor_name="v1", has_dim_equals=(-1, 3)) shape.check_static(tensor=v2, tensor_name="v2", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(v0, v1, v2), last_axes=-2, broadcast_compatible=True) normals = vector.cross(v1 - v0, v2 - v0, axis=-1) return 0.5 * tf.linalg.norm(tensor=normals, axis=-1, keepdims=True) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow triangle utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def normal(v0, v1, v2, clockwise=False, normalize=True, name=None): """Computes face normals (triangles). Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: v0: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vertex of a triangle. v1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vertex of a triangle. v2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the third vertex of a triangle. clockwise: Winding order to determine front-facing triangles. normalize: A `bool` indicating whether output normals should be normalized by the function. name: A name for this op. Defaults to "triangle_normal". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized vector. Raises: ValueError: If the shape of `v0`, `v1`, or `v2` is not supported. """ with tf.compat.v1.name_scope(name, "triangle_normal", [v0, v1, v2]): v0 = tf.convert_to_tensor(value=v0) v1 = tf.convert_to_tensor(value=v1) v2 = tf.convert_to_tensor(value=v2) shape.check_static(tensor=v0, tensor_name="v0", has_dim_equals=(-1, 3)) shape.check_static(tensor=v1, tensor_name="v1", has_dim_equals=(-1, 3)) shape.check_static(tensor=v2, tensor_name="v2", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(v0, v1, v2), last_axes=-2, broadcast_compatible=True) normal_vector = vector.cross(v1 - v0, v2 - v0, axis=-1) normal_vector = asserts.assert_nonzero_norm(normal_vector) if not clockwise: normal_vector *= -1.0 if normalize: return tf.nn.l2_normalize(normal_vector, axis=-1) return normal_vector def area(v0, v1, v2, name=None): """Computes triangle areas. Note: Computed triangle area = 0.5 * | e1 x e2 | where e1 and e2 are edges of triangle. A degenerate triangle will return 0 area, whereas the normal for a degenerate triangle is not defined. In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: v0: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vertex of a triangle. v1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vertex of a triangle. v2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the third vertex of a triangle. name: A name for this op. Defaults to "triangle_area". Returns: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a normalized vector. """ with tf.compat.v1.name_scope(name, "triangle_area", [v0, v1, v2]): v0 = tf.convert_to_tensor(value=v0) v1 = tf.convert_to_tensor(value=v1) v2 = tf.convert_to_tensor(value=v2) shape.check_static(tensor=v0, tensor_name="v0", has_dim_equals=(-1, 3)) shape.check_static(tensor=v1, tensor_name="v1", has_dim_equals=(-1, 3)) shape.check_static(tensor=v2, tensor_name="v2", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(v0, v1, v2), last_axes=-2, broadcast_compatible=True) normals = vector.cross(v1 - v0, v2 - v0, axis=-1) return 0.5 * tf.linalg.norm(tensor=normals, axis=-1, keepdims=True) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/nn/metric/fscore.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the fscore metric.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.nn.metric import precision as precision_module from tensorflow_graphics.nn.metric import recall as recall_module from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def evaluate(ground_truth, prediction, precision_function=precision_module.evaluate, recall_function=recall_module.evaluate, name=None): """Computes the fscore metric for the given ground truth and predicted labels. The fscore is calculated as 2 * (precision * recall) / (precision + recall) where the precision and recall are evaluated by the given function parameters. The precision and recall functions default to their definition for boolean labels (see https://en.wikipedia.org/wiki/Precision_and_recall for more details). Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: ground_truth: A tensor of shape `[A1, ..., An, N]`, where the last axis represents the ground truth values. prediction: A tensor of shape `[A1, ..., An, N]`, where the last axis represents the predicted values. precision_function: The function to use for evaluating the precision. Defaults to the precision evaluation for binary ground-truth and predictions. recall_function: The function to use for evaluating the recall. Defaults to the recall evaluation for binary ground-truth and prediction. name: A name for this op. Defaults to "fscore_evaluate". Returns: A tensor of shape `[A1, ..., An]` that stores the fscore metric for the given ground truth labels and predictions. Raises: ValueError: if the shape of `ground_truth`, `prediction` is not supported. """ with tf.compat.v1.name_scope(name, "fscore_evaluate", [ground_truth, prediction]): ground_truth = tf.convert_to_tensor(value=ground_truth) prediction = tf.convert_to_tensor(value=prediction) shape.compare_batch_dimensions( tensors=(ground_truth, prediction), tensor_names=("ground_truth", "prediction"), last_axes=-1, broadcast_compatible=True) recall = recall_function(ground_truth, prediction) precision = precision_function(ground_truth, prediction) return safe_ops.safe_signed_div(2 * precision * recall, precision + recall) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the fscore metric.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.nn.metric import precision as precision_module from tensorflow_graphics.nn.metric import recall as recall_module from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def evaluate(ground_truth, prediction, precision_function=precision_module.evaluate, recall_function=recall_module.evaluate, name=None): """Computes the fscore metric for the given ground truth and predicted labels. The fscore is calculated as 2 * (precision * recall) / (precision + recall) where the precision and recall are evaluated by the given function parameters. The precision and recall functions default to their definition for boolean labels (see https://en.wikipedia.org/wiki/Precision_and_recall for more details). Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: ground_truth: A tensor of shape `[A1, ..., An, N]`, where the last axis represents the ground truth values. prediction: A tensor of shape `[A1, ..., An, N]`, where the last axis represents the predicted values. precision_function: The function to use for evaluating the precision. Defaults to the precision evaluation for binary ground-truth and predictions. recall_function: The function to use for evaluating the recall. Defaults to the recall evaluation for binary ground-truth and prediction. name: A name for this op. Defaults to "fscore_evaluate". Returns: A tensor of shape `[A1, ..., An]` that stores the fscore metric for the given ground truth labels and predictions. Raises: ValueError: if the shape of `ground_truth`, `prediction` is not supported. """ with tf.compat.v1.name_scope(name, "fscore_evaluate", [ground_truth, prediction]): ground_truth = tf.convert_to_tensor(value=ground_truth) prediction = tf.convert_to_tensor(value=prediction) shape.compare_batch_dimensions( tensors=(ground_truth, prediction), tensor_names=("ground_truth", "prediction"), last_axes=-1, broadcast_compatible=True) recall = recall_function(ground_truth, prediction) precision = precision_function(ground_truth, prediction) return safe_ops.safe_signed_div(2 * precision * recall, precision + recall) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/util/tests/safe_ops_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for safe_ops.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.util import asserts from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import test_case def _pick_random_vector(): """Creates a random vector with random shape.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() return np.random.normal(size=tensor_shape + [4]) class SafeOpsTest(test_case.TestCase): @parameterized.parameters(tf.float16, tf.float32, tf.float64) def test_safe_unsigned_div_exception_not_raised(self, dtype): """Checks that unsigned division does not cause Inf values.""" vector = tf.convert_to_tensor(value=_pick_random_vector(), dtype=dtype) zero_vector = tf.zeros_like(vector) self.assert_exception_is_not_raised( safe_ops.safe_unsigned_div, shapes=[], a=tf.norm(tensor=vector), b=tf.norm(tensor=zero_vector)) @parameterized.parameters(tf.float16, tf.float32, tf.float64) def test_safe_unsigned_div_exception_raised(self, dtype): """Checks that unsigned division causes Inf values for zero eps.""" vector = tf.convert_to_tensor(value=_pick_random_vector(), dtype=dtype) zero_vector = tf.zeros_like(vector) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( safe_ops.safe_unsigned_div( tf.norm(tensor=vector), tf.norm(tensor=zero_vector), eps=0.0)) @parameterized.parameters(tf.float16, tf.float32, tf.float64) def test_safe_signed_div_exception_not_raised(self, dtype): """Checks that signed division does not cause Inf values.""" vector = tf.convert_to_tensor(value=_pick_random_vector(), dtype=dtype) zero_vector = tf.zeros_like(vector) self.assert_exception_is_not_raised( safe_ops.safe_signed_div, shapes=[], a=tf.norm(tensor=vector), b=tf.sin(zero_vector)) @parameterized.parameters(tf.float16, tf.float32, tf.float64) def test_safe_signed_div_exception_raised(self, dtype): """Checks that signed division causes Inf values for zero eps.""" vector = tf.convert_to_tensor(value=_pick_random_vector(), dtype=dtype) zero_vector = tf.zeros_like(vector) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( safe_ops.safe_unsigned_div( tf.norm(tensor=vector), tf.sin(zero_vector), eps=0.0)) @parameterized.parameters(tf.float32, tf.float64) def test_safe_shrink_exception_not_raised(self, dtype): """Checks whether safe shrinking makes tensor safe for tf.acos(x).""" tensor = tf.convert_to_tensor(value=_pick_random_vector(), dtype=dtype) tensor = tensor * tensor norm_tensor = tensor / tf.reduce_max( input_tensor=tensor, axis=-1, keepdims=True) eps = asserts.select_eps_for_addition(dtype) norm_tensor += eps safe_tensor = safe_ops.safe_shrink(norm_tensor, -1.0, 1.0) self.assert_exception_is_not_raised(tf.acos, shapes=[], x=safe_tensor) @parameterized.parameters(tf.float32, tf.float64) def test_safe_shrink_exception_raised(self, dtype): """Checks whether safe shrinking fails when eps is zero.""" tensor = tf.convert_to_tensor(value=_pick_random_vector(), dtype=dtype) tensor = tensor * tensor norm_tensor = tensor / tf.reduce_max( input_tensor=tensor, axis=-1, keepdims=True) eps = asserts.select_eps_for_addition(dtype) norm_tensor += eps with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate(safe_ops.safe_shrink(norm_tensor, -1.0, 1.0, eps=0.0)) def test_safe_sinpx_div_sinx(self): """Tests for edge cases and continuity for sin(px)/sin(x).""" angle_step = np.pi / 16.0 with self.subTest(name="all_angles"): theta = tf.range(-2.0 * np.pi, 2.0 * np.pi + angle_step / 2.0, angle_step) factor = np.random.uniform(size=(1,)) division = safe_ops.safe_sinpx_div_sinx(theta, factor) division_l = safe_ops.safe_sinpx_div_sinx(theta + 1e-10, factor) division_r = safe_ops.safe_sinpx_div_sinx(theta - 1e-10, factor) self.assertAllClose(division, division_l, rtol=1e-9) self.assertAllClose(division, division_r, rtol=1e-9) with self.subTest(name="theta_is_zero"): theta = 0.0 factor = tf.range(0.0, 1.0, 0.001) division = safe_ops.safe_sinpx_div_sinx(theta, factor) division_l = safe_ops.safe_sinpx_div_sinx(theta + 1e-10, factor) division_r = safe_ops.safe_sinpx_div_sinx(theta - 1e-10, factor) self.assertAllClose(division, division_l, atol=1e-9) self.assertAllClose(division, division_r, atol=1e-9) # According to l'Hopital rule, limit should be factor self.assertAllClose(division, factor, atol=1e-9) with self.subTest(name="theta_is_pi"): theta = np.pi factor = tf.range(0.0, 1.001, 0.001) division = safe_ops.safe_sinpx_div_sinx(theta, factor) division_l = safe_ops.safe_sinpx_div_sinx(theta + 1e-10, factor) division_r = safe_ops.safe_sinpx_div_sinx(theta - 1e-10, factor) self.assertAllClose(division, division_l, atol=1e-9) self.assertAllClose(division, division_r, atol=1e-9) def test_safe_cospx_div_cosx(self): """Tests for edge cases and continuity for cos(px)/cos(x).""" angle_step = np.pi / 16.0 with self.subTest(name="all_angles"): theta = tf.range(-2.0 * np.pi, 2.0 * np.pi + angle_step / 2.0, angle_step) factor = np.random.uniform(size=(1,)) division = safe_ops.safe_cospx_div_cosx(theta, factor) division_l = safe_ops.safe_cospx_div_cosx(theta + 1e-10, factor) division_r = safe_ops.safe_cospx_div_cosx(theta - 1e-10, factor) self.assertAllClose(division, division_l, rtol=1e-9) self.assertAllClose(division, division_r, rtol=1e-9) with self.subTest(name="theta_is_pi_over_two"): theta = np.pi / 2.0 factor = tf.constant(1.0) division = safe_ops.safe_cospx_div_cosx(theta, factor) division_l = safe_ops.safe_cospx_div_cosx(theta + 1e-10, factor) division_r = safe_ops.safe_cospx_div_cosx(theta - 1e-10, factor) self.assertAllClose(division, division_l, atol=1e-9) self.assertAllClose(division, division_r, atol=1e-9) # According to l'Hopital rule, limit should be 1.0 self.assertAllClose(division, 1.0, atol=1e-9) with self.subTest(name="theta_is_three_pi_over_two"): theta = np.pi * 3.0 / 2.0 factor = tf.range(0.0, 1.001, 0.001) division = safe_ops.safe_cospx_div_cosx(theta, factor) division_l = safe_ops.safe_cospx_div_cosx(theta + 1e-10, factor) division_r = safe_ops.safe_cospx_div_cosx(theta - 1e-10, factor) self.assertAllClose(division, division_l, atol=1e-9) self.assertAllClose(division, division_r, atol=1e-9) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for safe_ops.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.util import asserts from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import test_case def _pick_random_vector(): """Creates a random vector with random shape.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() return np.random.normal(size=tensor_shape + [4]) class SafeOpsTest(test_case.TestCase): @parameterized.parameters(tf.float16, tf.float32, tf.float64) def test_safe_unsigned_div_exception_not_raised(self, dtype): """Checks that unsigned division does not cause Inf values.""" vector = tf.convert_to_tensor(value=_pick_random_vector(), dtype=dtype) zero_vector = tf.zeros_like(vector) self.assert_exception_is_not_raised( safe_ops.safe_unsigned_div, shapes=[], a=tf.norm(tensor=vector), b=tf.norm(tensor=zero_vector)) @parameterized.parameters(tf.float16, tf.float32, tf.float64) def test_safe_unsigned_div_exception_raised(self, dtype): """Checks that unsigned division causes Inf values for zero eps.""" vector = tf.convert_to_tensor(value=_pick_random_vector(), dtype=dtype) zero_vector = tf.zeros_like(vector) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( safe_ops.safe_unsigned_div( tf.norm(tensor=vector), tf.norm(tensor=zero_vector), eps=0.0)) @parameterized.parameters(tf.float16, tf.float32, tf.float64) def test_safe_signed_div_exception_not_raised(self, dtype): """Checks that signed division does not cause Inf values.""" vector = tf.convert_to_tensor(value=_pick_random_vector(), dtype=dtype) zero_vector = tf.zeros_like(vector) self.assert_exception_is_not_raised( safe_ops.safe_signed_div, shapes=[], a=tf.norm(tensor=vector), b=tf.sin(zero_vector)) @parameterized.parameters(tf.float16, tf.float32, tf.float64) def test_safe_signed_div_exception_raised(self, dtype): """Checks that signed division causes Inf values for zero eps.""" vector = tf.convert_to_tensor(value=_pick_random_vector(), dtype=dtype) zero_vector = tf.zeros_like(vector) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( safe_ops.safe_unsigned_div( tf.norm(tensor=vector), tf.sin(zero_vector), eps=0.0)) @parameterized.parameters(tf.float32, tf.float64) def test_safe_shrink_exception_not_raised(self, dtype): """Checks whether safe shrinking makes tensor safe for tf.acos(x).""" tensor = tf.convert_to_tensor(value=_pick_random_vector(), dtype=dtype) tensor = tensor * tensor norm_tensor = tensor / tf.reduce_max( input_tensor=tensor, axis=-1, keepdims=True) eps = asserts.select_eps_for_addition(dtype) norm_tensor += eps safe_tensor = safe_ops.safe_shrink(norm_tensor, -1.0, 1.0) self.assert_exception_is_not_raised(tf.acos, shapes=[], x=safe_tensor) @parameterized.parameters(tf.float32, tf.float64) def test_safe_shrink_exception_raised(self, dtype): """Checks whether safe shrinking fails when eps is zero.""" tensor = tf.convert_to_tensor(value=_pick_random_vector(), dtype=dtype) tensor = tensor * tensor norm_tensor = tensor / tf.reduce_max( input_tensor=tensor, axis=-1, keepdims=True) eps = asserts.select_eps_for_addition(dtype) norm_tensor += eps with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate(safe_ops.safe_shrink(norm_tensor, -1.0, 1.0, eps=0.0)) def test_safe_sinpx_div_sinx(self): """Tests for edge cases and continuity for sin(px)/sin(x).""" angle_step = np.pi / 16.0 with self.subTest(name="all_angles"): theta = tf.range(-2.0 * np.pi, 2.0 * np.pi + angle_step / 2.0, angle_step) factor = np.random.uniform(size=(1,)) division = safe_ops.safe_sinpx_div_sinx(theta, factor) division_l = safe_ops.safe_sinpx_div_sinx(theta + 1e-10, factor) division_r = safe_ops.safe_sinpx_div_sinx(theta - 1e-10, factor) self.assertAllClose(division, division_l, rtol=1e-9) self.assertAllClose(division, division_r, rtol=1e-9) with self.subTest(name="theta_is_zero"): theta = 0.0 factor = tf.range(0.0, 1.0, 0.001) division = safe_ops.safe_sinpx_div_sinx(theta, factor) division_l = safe_ops.safe_sinpx_div_sinx(theta + 1e-10, factor) division_r = safe_ops.safe_sinpx_div_sinx(theta - 1e-10, factor) self.assertAllClose(division, division_l, atol=1e-9) self.assertAllClose(division, division_r, atol=1e-9) # According to l'Hopital rule, limit should be factor self.assertAllClose(division, factor, atol=1e-9) with self.subTest(name="theta_is_pi"): theta = np.pi factor = tf.range(0.0, 1.001, 0.001) division = safe_ops.safe_sinpx_div_sinx(theta, factor) division_l = safe_ops.safe_sinpx_div_sinx(theta + 1e-10, factor) division_r = safe_ops.safe_sinpx_div_sinx(theta - 1e-10, factor) self.assertAllClose(division, division_l, atol=1e-9) self.assertAllClose(division, division_r, atol=1e-9) def test_safe_cospx_div_cosx(self): """Tests for edge cases and continuity for cos(px)/cos(x).""" angle_step = np.pi / 16.0 with self.subTest(name="all_angles"): theta = tf.range(-2.0 * np.pi, 2.0 * np.pi + angle_step / 2.0, angle_step) factor = np.random.uniform(size=(1,)) division = safe_ops.safe_cospx_div_cosx(theta, factor) division_l = safe_ops.safe_cospx_div_cosx(theta + 1e-10, factor) division_r = safe_ops.safe_cospx_div_cosx(theta - 1e-10, factor) self.assertAllClose(division, division_l, rtol=1e-9) self.assertAllClose(division, division_r, rtol=1e-9) with self.subTest(name="theta_is_pi_over_two"): theta = np.pi / 2.0 factor = tf.constant(1.0) division = safe_ops.safe_cospx_div_cosx(theta, factor) division_l = safe_ops.safe_cospx_div_cosx(theta + 1e-10, factor) division_r = safe_ops.safe_cospx_div_cosx(theta - 1e-10, factor) self.assertAllClose(division, division_l, atol=1e-9) self.assertAllClose(division, division_r, atol=1e-9) # According to l'Hopital rule, limit should be 1.0 self.assertAllClose(division, 1.0, atol=1e-9) with self.subTest(name="theta_is_three_pi_over_two"): theta = np.pi * 3.0 / 2.0 factor = tf.range(0.0, 1.001, 0.001) division = safe_ops.safe_cospx_div_cosx(theta, factor) division_l = safe_ops.safe_cospx_div_cosx(theta + 1e-10, factor) division_r = safe_ops.safe_cospx_div_cosx(theta - 1e-10, factor) self.assertAllClose(division, division_l, atol=1e-9) self.assertAllClose(division, division_r, atol=1e-9) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/rendering/opengl/egl_offscreen_context.h
/* Copyright 2020 The TensorFlow Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_OPENGL_EGL_OFFSCREEN_CONTEXT_H_ #define THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_OPENGL_EGL_OFFSCREEN_CONTEXT_H_ #include <EGL/egl.h> #include <memory> #include "tensorflow/core/lib/core/status.h" // EGL is an interface between OpenGL ES and the windowing system of the native // platform. The following class provides functionality to manage an EGL // off-screen contexts. class EGLOffscreenContext { public: ~EGLOffscreenContext(); // Creates an EGL display, pixel buffer surface, and context that can be used // for rendering. These objects are created with default parameters // // Arguments: // * egl_offscreen_context: if the method is successful, this object holds a // valid offscreen context. // // Returns: // A tensorflow::Status object storing tensorflow::Status::OK() on success, // and an object of type tensorflow::errors otherwise. static tensorflow::Status Create( std::unique_ptr<EGLOffscreenContext>* egl_offscreen_context); // Creates an EGL display, pixel buffer surface, and context that can be used // for rendering. // // Arguments: // * pixel_buffer_width: width of the pixel buffer surface. // * pixel_buffer_height: height of the pixel buffer surface. // * context: if the method succeeds, this variable returns an object storing // a valid display, context, and pixel buffer surface. // * configuration_attributes: attributes used to build frame buffer // * configurations. // * context_attributes: attributes used to create the EGL context. // * rendering_api: defines the rendering API for the current thread. The // available APIs are EGL_OPENGL_API, EGL_OPENGL_ES_API, and // EGL_OPENVG_API. // * egl_offscreen_context: if the method is successful, this object holds a // valid offscreen context. // // Returns: // A tensorflow::Status object storing tensorflow::Status::OK() on success, // and an object of type tensorflow::errors otherwise. static tensorflow::Status Create( const int pixel_buffer_width, const int pixel_buffer_height, const EGLenum rendering_api, const EGLint* configuration_attributes, const EGLint* context_attributes, std::unique_ptr<EGLOffscreenContext>* egl_offscreen_context); // Binds the EGL context to the current rendering thread and to the pixel // buffer surface. Note that this context must not be current in any other // thread. // // Returns: // A tensorflow::Status object storing tensorflow::Status::OK() on success, // and an object of type tensorflow::errors otherwise. tensorflow::Status MakeCurrent() const; // Un-binds the current EGL rendering context from the current rendering // thread and from the pixel buffer surface. // // Returns: // A tensorflow::Status object storing tensorflow::Status::OK() on success, // and an object of type tensorflow::errors otherwise. tensorflow::Status Release(); private: EGLOffscreenContext() = delete; EGLOffscreenContext(EGLContext context, EGLDisplay display, EGLSurface pixel_buffer_surface); EGLOffscreenContext(const EGLOffscreenContext&) = delete; EGLOffscreenContext(EGLOffscreenContext&&) = delete; EGLOffscreenContext& operator=(const EGLOffscreenContext&) = delete; EGLOffscreenContext& operator=(EGLOffscreenContext&&) = delete; tensorflow::Status Destroy(); EGLContext context_; EGLDisplay display_; EGLSurface pixel_buffer_surface_; }; #endif // THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_OPENGL_EGL_OFFSCREEN_CONTEXT_H_
/* Copyright 2020 The TensorFlow Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_OPENGL_EGL_OFFSCREEN_CONTEXT_H_ #define THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_OPENGL_EGL_OFFSCREEN_CONTEXT_H_ #include <EGL/egl.h> #include <memory> #include "tensorflow/core/lib/core/status.h" // EGL is an interface between OpenGL ES and the windowing system of the native // platform. The following class provides functionality to manage an EGL // off-screen contexts. class EGLOffscreenContext { public: ~EGLOffscreenContext(); // Creates an EGL display, pixel buffer surface, and context that can be used // for rendering. These objects are created with default parameters // // Arguments: // * egl_offscreen_context: if the method is successful, this object holds a // valid offscreen context. // // Returns: // A tensorflow::Status object storing tensorflow::Status::OK() on success, // and an object of type tensorflow::errors otherwise. static tensorflow::Status Create( std::unique_ptr<EGLOffscreenContext>* egl_offscreen_context); // Creates an EGL display, pixel buffer surface, and context that can be used // for rendering. // // Arguments: // * pixel_buffer_width: width of the pixel buffer surface. // * pixel_buffer_height: height of the pixel buffer surface. // * context: if the method succeeds, this variable returns an object storing // a valid display, context, and pixel buffer surface. // * configuration_attributes: attributes used to build frame buffer // * configurations. // * context_attributes: attributes used to create the EGL context. // * rendering_api: defines the rendering API for the current thread. The // available APIs are EGL_OPENGL_API, EGL_OPENGL_ES_API, and // EGL_OPENVG_API. // * egl_offscreen_context: if the method is successful, this object holds a // valid offscreen context. // // Returns: // A tensorflow::Status object storing tensorflow::Status::OK() on success, // and an object of type tensorflow::errors otherwise. static tensorflow::Status Create( const int pixel_buffer_width, const int pixel_buffer_height, const EGLenum rendering_api, const EGLint* configuration_attributes, const EGLint* context_attributes, std::unique_ptr<EGLOffscreenContext>* egl_offscreen_context); // Binds the EGL context to the current rendering thread and to the pixel // buffer surface. Note that this context must not be current in any other // thread. // // Returns: // A tensorflow::Status object storing tensorflow::Status::OK() on success, // and an object of type tensorflow::errors otherwise. tensorflow::Status MakeCurrent() const; // Un-binds the current EGL rendering context from the current rendering // thread and from the pixel buffer surface. // // Returns: // A tensorflow::Status object storing tensorflow::Status::OK() on success, // and an object of type tensorflow::errors otherwise. tensorflow::Status Release(); private: EGLOffscreenContext() = delete; EGLOffscreenContext(EGLContext context, EGLDisplay display, EGLSurface pixel_buffer_surface); EGLOffscreenContext(const EGLOffscreenContext&) = delete; EGLOffscreenContext(EGLOffscreenContext&&) = delete; EGLOffscreenContext& operator=(const EGLOffscreenContext&) = delete; EGLOffscreenContext& operator=(EGLOffscreenContext&&) = delete; tensorflow::Status Destroy(); EGLContext context_; EGLDisplay display_; EGLSurface pixel_buffer_surface_; }; #endif // THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_OPENGL_EGL_OFFSCREEN_CONTEXT_H_
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/rendering/camera/tests/perspective_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for perspective camera functionalities.""" import math import sys from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.rendering.camera import perspective from tensorflow_graphics.util import test_case class PerspectiveTest(test_case.TestCase): @parameterized.parameters( ("must have exactly 4 dimensions in axis -1", (4, 3)), ("must have exactly 4 dimensions in axis -2", (5, 4)), ("must have exactly 4 dimensions in axis -2", (None, 4)), ("must have exactly 4 dimensions in axis -1", (4, None)), ) def test_parameters_from_right_handed_shape_exception_raised( self, error_msg, *shapes): """Checks the inputs of the from_right_handed_shape function.""" self.assert_exception_is_raised(perspective.parameters_from_right_handed, error_msg, shapes) @parameterized.parameters( ((4, 4),), ((None, 4, 4),), ((None, None, 4, 4),), ) def test_parameters_from_right_handed_shape_exception_not_raised( self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( perspective.parameters_from_right_handed, shapes) def test_parameters_from_right_handed_random(self): """Tests that parameters_from_right_handed returns the expected values.""" tensor_size = np.random.randint(2, 4) tensor_shape = np.random.randint(2, 5, size=(tensor_size)).tolist() vertical_field_of_view_gt = np.random.uniform( sys.float_info.epsilon, np.pi - sys.float_info.epsilon, tensor_shape + [1]) aspect_ratio_gt = np.random.uniform(0.1, 10.0, tensor_shape + [1]) near_gt = np.random.uniform(0.1, 100.0, tensor_shape + [1]) far_gt = near_gt + np.random.uniform(0.1, 100.0, tensor_shape + [1]) projection_matrix = perspective.right_handed(vertical_field_of_view_gt, aspect_ratio_gt, near_gt, far_gt) vertical_field_of_view_pred, aspect_ratio_pred, near_pred, far_pred = perspective.parameters_from_right_handed( projection_matrix) with self.subTest(name="vertical_field_of_view"): self.assertAllClose(vertical_field_of_view_gt, vertical_field_of_view_pred) with self.subTest(name="aspect_ratio"): self.assertAllClose(aspect_ratio_gt, aspect_ratio_pred) with self.subTest(name="near_plane"): self.assertAllClose(near_gt, near_pred) with self.subTest(name="far_plane"): self.assertAllClose(far_gt, far_pred) def test_parameters_from_right_handed_jacobian_random(self): """Tests the Jacobian of parameters_from_right_handed.""" tensor_size = np.random.randint(2, 4) tensor_shape = np.random.randint(2, 5, size=(tensor_size)).tolist() vertical_field_of_view = np.random.uniform(sys.float_info.epsilon, np.pi - sys.float_info.epsilon, tensor_shape + [1]) aspect_ratio = np.random.uniform(0.1, 10.0, tensor_shape + [1]) near = np.random.uniform(0.1, 100.0, tensor_shape + [1]) far = near + np.random.uniform(0.1, 100.0, tensor_shape + [1]) projection_matrix = perspective.right_handed(vertical_field_of_view, aspect_ratio, near, far) with self.subTest(name="vertical_field_of_view"): self.assert_jacobian_is_finite_fn( lambda x: perspective.parameters_from_right_handed(x)[0], [projection_matrix]) with self.subTest(name="aspect_ratio"): self.assert_jacobian_is_finite_fn( lambda x: perspective.parameters_from_right_handed(x)[1], [projection_matrix]) with self.subTest(name="near_plane"): self.assert_jacobian_is_finite_fn( lambda x: perspective.parameters_from_right_handed(x)[2], [projection_matrix]) with self.subTest(name="far_plane"): self.assert_jacobian_is_finite_fn( lambda x: perspective.parameters_from_right_handed(x)[3], [projection_matrix]) def test_perspective_right_handed_preset(self): """Tests that perspective_right_handed generates expected results.""" vertical_field_of_view = ((60.0 * math.pi / 180.0,), (50.0 * math.pi / 180.0,)) aspect_ratio = ((1.5,), (1.1,)) near = ((1.0,), (1.2,)) far = ((10.0,), (5.0,)) pred = perspective.right_handed(vertical_field_of_view, aspect_ratio, near, far) gt = (((1.15470052, 0.0, 0.0, 0.0), (0.0, 1.73205066, 0.0, 0.0), (0.0, 0.0, -1.22222221, -2.22222233), (0.0, 0.0, -1.0, 0.0)), ((1.9495517, 0.0, 0.0, 0.0), (0.0, 2.14450693, 0.0, 0.0), (0.0, 0.0, -1.63157892, -3.15789485), (0.0, 0.0, -1.0, 0.0))) self.assertAllClose(pred, gt) @parameterized.parameters( ((1,), (1,), (1,), (1,)), ((None, 1), (None, 1), (None, 1), (None, 1)), ((None, 3, 1), (None, 3, 1), (None, 3, 1), (None, 3, 1)), ) def test_perspective_right_handed_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(perspective.right_handed, shapes) @parameterized.parameters( ("Not all batch dimensions are identical", (1,), (3, 1), (3, 1), (3, 1)), ("Not all batch dimensions are identical", (3, 1), (None, 3, 1), (3, 1), (3, 1)), ) def test_perspective_right_handed_shape_exception_raised( self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(perspective.right_handed, error_msg, shapes) @parameterized.parameters( ((1.0,), (1.0,), np.random.uniform(-1.0, 0.0, size=(1,)).astype(np.float32), (1.0,)), ((1.0,), (1.0,), (0.0,), (1.0,)), ((1.0,), np.random.uniform(-1.0, 0.0, size=(1,)).astype(np.float32), (0.1,), (1.0,)), ((1.0,), (0.0,), (0.1,), (1.0,)), ((1.0,), (1.0,), np.random.uniform(1.0, 2.0, size=(1,)).astype(np.float32), np.random.uniform(0.1, 0.5, size=(1,)).astype(np.float32)), ((1.0,), (1.0,), (0.1,), (0.1,)), (np.random.uniform(-math.pi, 0.0, size=(1,)).astype(np.float32), (1.0,), (0.1,), (1.0,)), (np.random.uniform(math.pi, 2.0 * math.pi, size=(1,)).astype(np.float32), (1.0,), (0.1,), (1.0,)), ((0.0,), (1.0,), (0.1,), (1.0,)), ((math.pi,), (1.0,), (0.1,), (1.0,)), ) def test_perspective_right_handed_valid_range_exception_raised( self, vertical_field_of_view, aspect_ratio, near, far): """Tests that an exception is raised with out of bounds values.""" with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( perspective.right_handed(vertical_field_of_view, aspect_ratio, near, far)) def test_perspective_right_handed_cross_jacobian_preset(self): """Tests the Jacobian of perspective_right_handed.""" vertical_field_of_view_init = np.array((1.0,)) aspect_ratio_init = np.array((1.0,)) near_init = np.array((1.0,)) far_init = np.array((10.0,)) self.assert_jacobian_is_correct_fn( perspective.right_handed, [vertical_field_of_view_init, aspect_ratio_init, near_init, far_init]) def test_perspective_right_handed_cross_jacobian_random(self): """Tests the Jacobian of perspective_right_handed.""" tensor_size = np.random.randint(1, 3) tensor_shape = np.random.randint(1, 5, size=(tensor_size)).tolist() eps = np.finfo(np.float64).eps vertical_field_of_view_init = np.random.uniform( eps, math.pi - eps, size=tensor_shape + [1]) aspect_ratio_init = np.random.uniform(eps, 100.0, size=tensor_shape + [1]) near_init = np.random.uniform(eps, 10.0, size=tensor_shape + [1]) far_init = np.random.uniform(10 + eps, 100.0, size=tensor_shape + [1]) self.assert_jacobian_is_correct_fn( perspective.right_handed, [vertical_field_of_view_init, aspect_ratio_init, near_init, far_init]) @parameterized.parameters( ((3, 3),), ((3, 3, 3),), ((None, 3, 3),), ) def test_intrinsics_from_matrix_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(perspective.intrinsics_from_matrix, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ("must have exactly 3 dimensions in axis -1", (3, None)), ) def test_intrinsics_from_matrix_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(perspective.intrinsics_from_matrix, error_msg, shapes) @parameterized.parameters( ((((0., 0., 0.), (0., 0., 0.), (0., 0., 1.)),), ((0., 0.), (0., 0.))), ((((1., 0., 3.), (0., 2., 4.), (0., 0., 1.)),), ((1., 2.), (3., 4.))), ) def test_intrinsics_from_matrix_preset(self, test_inputs, test_outputs): """Tests that intrinsics_from_matrix gives the correct result.""" self.assert_output_is_correct(perspective.intrinsics_from_matrix, test_inputs, test_outputs) def test_intrinsics_from_matrix_to_intrinsics_random(self): """Tests that converting intrinsics to a matrix and back is consistent.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_focal = np.random.normal(size=tensor_shape + [2]) random_principal_point = np.random.normal(size=tensor_shape + [2]) matrix = perspective.matrix_from_intrinsics(random_focal, random_principal_point) focal, principal_point = perspective.intrinsics_from_matrix(matrix) self.assertAllClose(random_focal, focal, rtol=1e-3) self.assertAllClose(random_principal_point, principal_point, rtol=1e-3) @parameterized.parameters( ((2,), (2,)), ((2, 2), (2, 2)), ((None, 2), (None, 2)), ) def test_matrix_from_intrinsics_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(perspective.matrix_from_intrinsics, shapes) @parameterized.parameters( ("must have exactly 2 dimensions in axis -1", (None,), (2,)), ("must have exactly 2 dimensions in axis -1", (2,), (None,)), ("Not all batch dimensions are identical.", (3, 2), (2, 2)), ) def test_matrix_from_intrinsics_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(perspective.matrix_from_intrinsics, error_msg, shapes) @parameterized.parameters( (((0., 0.), (0., 0.)), (((0., 0., 0.), (0., 0., 0.), (0., 0., 1.)),)), (((1., 2.), (3., 4.)), (((1., 0., 3.), (0., 2., 4.), (0., 0., 1.)),)), ) def test_matrix_from_intrinsics_preset(self, test_inputs, test_outputs): """Tests that matrix_from_intrinsics gives the correct result.""" self.assert_output_is_correct(perspective.matrix_from_intrinsics, test_inputs, test_outputs) def test_matrix_from_intrinsics_to_matrix_random(self): """Tests that converting a matrix to intrinsics and back is consistent.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_focal = np.random.normal(size=tensor_shape + [2]) random_principal_point = np.random.normal(size=tensor_shape + [2]) fx = random_focal[..., 0] fy = random_focal[..., 1] cx = random_principal_point[..., 0] cy = random_principal_point[..., 1] zero = np.zeros_like(fx) one = np.ones_like(fx) random_matrix = np.stack((fx, zero, cx, zero, fy, cy, zero, zero, one), axis=-1).reshape(tensor_shape + [3, 3]) focal, principal_point = perspective.intrinsics_from_matrix(random_matrix) matrix = perspective.matrix_from_intrinsics(focal, principal_point) self.assertAllClose(random_matrix, matrix, rtol=1e-3) @parameterized.parameters( ((3,), (2,), (2,)), ((2, 3), (2, 2), (2, 2)), ((2, 3), (2,), (2,)), ((None, 3), (None, 2), (None, 2)), ) def test_project_exception_not_exception_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(perspective.project, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,), (2,), (2,)), ("must have exactly 2 dimensions in axis -1", (3,), (None,), (2,)), ("must have exactly 2 dimensions in axis -1", (3,), (2,), (None,)), ("Not all batch dimensions are broadcast-compatible.", (3, 3), (2, 2), (2, 2)), ) def test_project_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(perspective.project, error_msg, shape) @parameterized.parameters( (((0., 0., 1.), (1., 1.), (0., 0.)), ((0., 0.),)), (((4., 2., 1.), (1., 1.), (-4., -2.)), ((0., 0.),)), (((4., 2., 10.), (1., 1.), (-.4, -.2)), ((0., 0.),)), (((4., 2., 10.), (2., 1.), (-.8, -.2)), ((0., 0.),)), (((4., 2., 10.), (2., 1.), (-.8, 0.)), ((0., .2),)), ) def test_project_preset(self, test_inputs, test_outputs): """Tests that the project function gives the correct result.""" self.assert_output_is_correct(perspective.project, test_inputs, test_outputs) def test_project_unproject_random(self): """Tests that projecting and unprojecting gives an identity mapping.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_point_3d = np.random.normal(size=tensor_shape + [3]) random_focal = np.random.normal(size=tensor_shape + [2]) random_principal_point = np.random.normal(size=tensor_shape + [2]) random_depth = np.expand_dims(random_point_3d[..., 2], axis=-1) point_2d = perspective.project(random_point_3d, random_focal, random_principal_point) point_3d = perspective.unproject(point_2d, random_depth, random_focal, random_principal_point) self.assertAllClose(random_point_3d, point_3d, rtol=1e-3) def test_project_ray_random(self): """Tests that that ray is pointing toward the correct location.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_point_3d = np.random.normal(size=tensor_shape + [3]) random_focal = np.random.normal(size=tensor_shape + [2]) random_principal_point = np.random.normal(size=tensor_shape + [2]) random_depth = np.expand_dims(random_point_3d[..., 2], axis=-1) point_2d = perspective.project(random_point_3d, random_focal, random_principal_point) ray_3d = perspective.ray(point_2d, random_focal, random_principal_point) ray_3d = random_depth * ray_3d self.assertAllClose(random_point_3d, ray_3d, rtol=1e-3) @parameterized.parameters( ((2,), (2,), (2,)), ((2, 2), (2, 2), (2, 2)), ((3, 2), (1, 2), (2,)), ((None, 2), (None, 2), (None, 2)), ) def test_ray_exception_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(perspective.ray, shapes) @parameterized.parameters( ("must have exactly 2 dimensions in axis -1", (None,), (2,), (2,)), ("must have exactly 2 dimensions in axis -1", (2,), (None,), (2,)), ("must have exactly 2 dimensions in axis -1", (2,), (2,), (None,)), ("Not all batch dimensions are broadcast-compatible.", (3, 2), (1, 2), (2, 2)), ) def test_ray_exception_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(perspective.ray, error_msg, shapes) @parameterized.parameters( (((0., 0.), (1., 1.), (0., 0.)), ((0., 0., 1.),)), (((0., 0.), (1., 1.), (-1., -2.)), ((1., 2., 1.),)), (((0., 0.), (10., 1.), (-1., -2.)), ((.1, 2., 1.),)), (((-2., -4.), (10., 1.), (-3., -6.)), ((.1, 2., 1.),)), ) def test_ray_preset(self, test_inputs, test_outputs): """Tests that the ray function gives the correct result.""" self.assert_output_is_correct(perspective.ray, test_inputs, test_outputs) def test_ray_project_random(self): """Tests that the end point of the ray projects at the good location.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_point_2d = np.random.normal(size=tensor_shape + [2]) random_focal = np.random.normal(size=tensor_shape + [2]) random_principal_point = np.random.normal(size=tensor_shape + [2]) ray_3d = perspective.ray(random_point_2d, random_focal, random_principal_point) point_2d = perspective.project(ray_3d, random_focal, random_principal_point) self.assertAllClose(random_point_2d, point_2d, rtol=1e-3) @parameterized.parameters( ((2,), (1,), (2,), (2,)), ((2, 2), (2, 1), (2, 2), (2, 2)), ((None, 2), (None, 1), (None, 2), (None, 2)), ) def test_unproject_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(perspective.unproject, shapes) @parameterized.parameters( ("must have exactly 2 dimensions in axis -1", (None,), (1,), (2,), (2,)), ("must have exactly 1 dimensions in axis -1", (2,), (None,), (2,), (2,)), ("must have exactly 2 dimensions in axis -1", (2,), (1,), (None,), (2,)), ("must have exactly 2 dimensions in axis -1", (2,), (1,), (2,), (None,)), ("Not all batch dimensions are identical.", (1, 2), (2, 1), (2, 2), (2, 2)), ) def test_unproject_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(perspective.unproject, error_msg, shapes) @parameterized.parameters( (((0., 0.), (1.,), (1., 1.), (0., 0.)), ((0., 0., 1.),)), (((0., 0.), (1.,), (1., 1.), (-4., -2.)), ((4., 2., 1.),)), (((0., 0.), (10.,), (1., 1.), (-.4, -.2)), ((4., 2., 10.),)), (((0., 0.), (10.,), (2., 1.), (-.8, -.2)), ((4., 2., 10.),)), (((0., .2), (10.,), (2., 1.), (-.8, 0.)), ((4., 2., 10.),)), ) def test_unproject_preset(self, test_inputs, test_outputs): """Tests that the unproject function gives the correct result.""" self.assert_output_is_correct(perspective.unproject, test_inputs, test_outputs) def test_unproject_project_random(self): """Tests that unprojecting and projecting gives and identity mapping.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_point_2d = np.random.normal(size=tensor_shape + [2]) random_focal = np.random.normal(size=tensor_shape + [2]) random_principal_point = np.random.normal(size=tensor_shape + [2]) random_depth = np.random.normal(size=tensor_shape + [1]) point_3d = perspective.unproject(random_point_2d, random_depth, random_focal, random_principal_point) point_2d = perspective.project(point_3d, random_focal, random_principal_point) self.assertAllClose(random_point_2d, point_2d, rtol=1e-3) def test_unproject_ray_random(self): """Tests that that ray is pointing toward the correct location.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_point_2d = np.random.normal(size=tensor_shape + [2]) random_focal = np.random.normal(size=tensor_shape + [2]) random_principal_point = np.random.normal(size=tensor_shape + [2]) random_depth = np.random.normal(size=tensor_shape + [1]) point_3d = perspective.unproject(random_point_2d, random_depth, random_focal, random_principal_point) ray_3d = perspective.ray(random_point_2d, random_focal, random_principal_point) ray_3d = random_depth * ray_3d self.assertAllClose(point_3d, ray_3d, rtol=1e-3) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for perspective camera functionalities.""" import math import sys from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.rendering.camera import perspective from tensorflow_graphics.util import test_case class PerspectiveTest(test_case.TestCase): @parameterized.parameters( ("must have exactly 4 dimensions in axis -1", (4, 3)), ("must have exactly 4 dimensions in axis -2", (5, 4)), ("must have exactly 4 dimensions in axis -2", (None, 4)), ("must have exactly 4 dimensions in axis -1", (4, None)), ) def test_parameters_from_right_handed_shape_exception_raised( self, error_msg, *shapes): """Checks the inputs of the from_right_handed_shape function.""" self.assert_exception_is_raised(perspective.parameters_from_right_handed, error_msg, shapes) @parameterized.parameters( ((4, 4),), ((None, 4, 4),), ((None, None, 4, 4),), ) def test_parameters_from_right_handed_shape_exception_not_raised( self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( perspective.parameters_from_right_handed, shapes) def test_parameters_from_right_handed_random(self): """Tests that parameters_from_right_handed returns the expected values.""" tensor_size = np.random.randint(2, 4) tensor_shape = np.random.randint(2, 5, size=(tensor_size)).tolist() vertical_field_of_view_gt = np.random.uniform( sys.float_info.epsilon, np.pi - sys.float_info.epsilon, tensor_shape + [1]) aspect_ratio_gt = np.random.uniform(0.1, 10.0, tensor_shape + [1]) near_gt = np.random.uniform(0.1, 100.0, tensor_shape + [1]) far_gt = near_gt + np.random.uniform(0.1, 100.0, tensor_shape + [1]) projection_matrix = perspective.right_handed(vertical_field_of_view_gt, aspect_ratio_gt, near_gt, far_gt) vertical_field_of_view_pred, aspect_ratio_pred, near_pred, far_pred = perspective.parameters_from_right_handed( projection_matrix) with self.subTest(name="vertical_field_of_view"): self.assertAllClose(vertical_field_of_view_gt, vertical_field_of_view_pred) with self.subTest(name="aspect_ratio"): self.assertAllClose(aspect_ratio_gt, aspect_ratio_pred) with self.subTest(name="near_plane"): self.assertAllClose(near_gt, near_pred) with self.subTest(name="far_plane"): self.assertAllClose(far_gt, far_pred) def test_parameters_from_right_handed_jacobian_random(self): """Tests the Jacobian of parameters_from_right_handed.""" tensor_size = np.random.randint(2, 4) tensor_shape = np.random.randint(2, 5, size=(tensor_size)).tolist() vertical_field_of_view = np.random.uniform(sys.float_info.epsilon, np.pi - sys.float_info.epsilon, tensor_shape + [1]) aspect_ratio = np.random.uniform(0.1, 10.0, tensor_shape + [1]) near = np.random.uniform(0.1, 100.0, tensor_shape + [1]) far = near + np.random.uniform(0.1, 100.0, tensor_shape + [1]) projection_matrix = perspective.right_handed(vertical_field_of_view, aspect_ratio, near, far) with self.subTest(name="vertical_field_of_view"): self.assert_jacobian_is_finite_fn( lambda x: perspective.parameters_from_right_handed(x)[0], [projection_matrix]) with self.subTest(name="aspect_ratio"): self.assert_jacobian_is_finite_fn( lambda x: perspective.parameters_from_right_handed(x)[1], [projection_matrix]) with self.subTest(name="near_plane"): self.assert_jacobian_is_finite_fn( lambda x: perspective.parameters_from_right_handed(x)[2], [projection_matrix]) with self.subTest(name="far_plane"): self.assert_jacobian_is_finite_fn( lambda x: perspective.parameters_from_right_handed(x)[3], [projection_matrix]) def test_perspective_right_handed_preset(self): """Tests that perspective_right_handed generates expected results.""" vertical_field_of_view = ((60.0 * math.pi / 180.0,), (50.0 * math.pi / 180.0,)) aspect_ratio = ((1.5,), (1.1,)) near = ((1.0,), (1.2,)) far = ((10.0,), (5.0,)) pred = perspective.right_handed(vertical_field_of_view, aspect_ratio, near, far) gt = (((1.15470052, 0.0, 0.0, 0.0), (0.0, 1.73205066, 0.0, 0.0), (0.0, 0.0, -1.22222221, -2.22222233), (0.0, 0.0, -1.0, 0.0)), ((1.9495517, 0.0, 0.0, 0.0), (0.0, 2.14450693, 0.0, 0.0), (0.0, 0.0, -1.63157892, -3.15789485), (0.0, 0.0, -1.0, 0.0))) self.assertAllClose(pred, gt) @parameterized.parameters( ((1,), (1,), (1,), (1,)), ((None, 1), (None, 1), (None, 1), (None, 1)), ((None, 3, 1), (None, 3, 1), (None, 3, 1), (None, 3, 1)), ) def test_perspective_right_handed_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(perspective.right_handed, shapes) @parameterized.parameters( ("Not all batch dimensions are identical", (1,), (3, 1), (3, 1), (3, 1)), ("Not all batch dimensions are identical", (3, 1), (None, 3, 1), (3, 1), (3, 1)), ) def test_perspective_right_handed_shape_exception_raised( self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(perspective.right_handed, error_msg, shapes) @parameterized.parameters( ((1.0,), (1.0,), np.random.uniform(-1.0, 0.0, size=(1,)).astype(np.float32), (1.0,)), ((1.0,), (1.0,), (0.0,), (1.0,)), ((1.0,), np.random.uniform(-1.0, 0.0, size=(1,)).astype(np.float32), (0.1,), (1.0,)), ((1.0,), (0.0,), (0.1,), (1.0,)), ((1.0,), (1.0,), np.random.uniform(1.0, 2.0, size=(1,)).astype(np.float32), np.random.uniform(0.1, 0.5, size=(1,)).astype(np.float32)), ((1.0,), (1.0,), (0.1,), (0.1,)), (np.random.uniform(-math.pi, 0.0, size=(1,)).astype(np.float32), (1.0,), (0.1,), (1.0,)), (np.random.uniform(math.pi, 2.0 * math.pi, size=(1,)).astype(np.float32), (1.0,), (0.1,), (1.0,)), ((0.0,), (1.0,), (0.1,), (1.0,)), ((math.pi,), (1.0,), (0.1,), (1.0,)), ) def test_perspective_right_handed_valid_range_exception_raised( self, vertical_field_of_view, aspect_ratio, near, far): """Tests that an exception is raised with out of bounds values.""" with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( perspective.right_handed(vertical_field_of_view, aspect_ratio, near, far)) def test_perspective_right_handed_cross_jacobian_preset(self): """Tests the Jacobian of perspective_right_handed.""" vertical_field_of_view_init = np.array((1.0,)) aspect_ratio_init = np.array((1.0,)) near_init = np.array((1.0,)) far_init = np.array((10.0,)) self.assert_jacobian_is_correct_fn( perspective.right_handed, [vertical_field_of_view_init, aspect_ratio_init, near_init, far_init]) def test_perspective_right_handed_cross_jacobian_random(self): """Tests the Jacobian of perspective_right_handed.""" tensor_size = np.random.randint(1, 3) tensor_shape = np.random.randint(1, 5, size=(tensor_size)).tolist() eps = np.finfo(np.float64).eps vertical_field_of_view_init = np.random.uniform( eps, math.pi - eps, size=tensor_shape + [1]) aspect_ratio_init = np.random.uniform(eps, 100.0, size=tensor_shape + [1]) near_init = np.random.uniform(eps, 10.0, size=tensor_shape + [1]) far_init = np.random.uniform(10 + eps, 100.0, size=tensor_shape + [1]) self.assert_jacobian_is_correct_fn( perspective.right_handed, [vertical_field_of_view_init, aspect_ratio_init, near_init, far_init]) @parameterized.parameters( ((3, 3),), ((3, 3, 3),), ((None, 3, 3),), ) def test_intrinsics_from_matrix_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(perspective.intrinsics_from_matrix, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ("must have exactly 3 dimensions in axis -1", (3, None)), ) def test_intrinsics_from_matrix_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(perspective.intrinsics_from_matrix, error_msg, shapes) @parameterized.parameters( ((((0., 0., 0.), (0., 0., 0.), (0., 0., 1.)),), ((0., 0.), (0., 0.))), ((((1., 0., 3.), (0., 2., 4.), (0., 0., 1.)),), ((1., 2.), (3., 4.))), ) def test_intrinsics_from_matrix_preset(self, test_inputs, test_outputs): """Tests that intrinsics_from_matrix gives the correct result.""" self.assert_output_is_correct(perspective.intrinsics_from_matrix, test_inputs, test_outputs) def test_intrinsics_from_matrix_to_intrinsics_random(self): """Tests that converting intrinsics to a matrix and back is consistent.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_focal = np.random.normal(size=tensor_shape + [2]) random_principal_point = np.random.normal(size=tensor_shape + [2]) matrix = perspective.matrix_from_intrinsics(random_focal, random_principal_point) focal, principal_point = perspective.intrinsics_from_matrix(matrix) self.assertAllClose(random_focal, focal, rtol=1e-3) self.assertAllClose(random_principal_point, principal_point, rtol=1e-3) @parameterized.parameters( ((2,), (2,)), ((2, 2), (2, 2)), ((None, 2), (None, 2)), ) def test_matrix_from_intrinsics_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(perspective.matrix_from_intrinsics, shapes) @parameterized.parameters( ("must have exactly 2 dimensions in axis -1", (None,), (2,)), ("must have exactly 2 dimensions in axis -1", (2,), (None,)), ("Not all batch dimensions are identical.", (3, 2), (2, 2)), ) def test_matrix_from_intrinsics_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(perspective.matrix_from_intrinsics, error_msg, shapes) @parameterized.parameters( (((0., 0.), (0., 0.)), (((0., 0., 0.), (0., 0., 0.), (0., 0., 1.)),)), (((1., 2.), (3., 4.)), (((1., 0., 3.), (0., 2., 4.), (0., 0., 1.)),)), ) def test_matrix_from_intrinsics_preset(self, test_inputs, test_outputs): """Tests that matrix_from_intrinsics gives the correct result.""" self.assert_output_is_correct(perspective.matrix_from_intrinsics, test_inputs, test_outputs) def test_matrix_from_intrinsics_to_matrix_random(self): """Tests that converting a matrix to intrinsics and back is consistent.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_focal = np.random.normal(size=tensor_shape + [2]) random_principal_point = np.random.normal(size=tensor_shape + [2]) fx = random_focal[..., 0] fy = random_focal[..., 1] cx = random_principal_point[..., 0] cy = random_principal_point[..., 1] zero = np.zeros_like(fx) one = np.ones_like(fx) random_matrix = np.stack((fx, zero, cx, zero, fy, cy, zero, zero, one), axis=-1).reshape(tensor_shape + [3, 3]) focal, principal_point = perspective.intrinsics_from_matrix(random_matrix) matrix = perspective.matrix_from_intrinsics(focal, principal_point) self.assertAllClose(random_matrix, matrix, rtol=1e-3) @parameterized.parameters( ((3,), (2,), (2,)), ((2, 3), (2, 2), (2, 2)), ((2, 3), (2,), (2,)), ((None, 3), (None, 2), (None, 2)), ) def test_project_exception_not_exception_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(perspective.project, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,), (2,), (2,)), ("must have exactly 2 dimensions in axis -1", (3,), (None,), (2,)), ("must have exactly 2 dimensions in axis -1", (3,), (2,), (None,)), ("Not all batch dimensions are broadcast-compatible.", (3, 3), (2, 2), (2, 2)), ) def test_project_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(perspective.project, error_msg, shape) @parameterized.parameters( (((0., 0., 1.), (1., 1.), (0., 0.)), ((0., 0.),)), (((4., 2., 1.), (1., 1.), (-4., -2.)), ((0., 0.),)), (((4., 2., 10.), (1., 1.), (-.4, -.2)), ((0., 0.),)), (((4., 2., 10.), (2., 1.), (-.8, -.2)), ((0., 0.),)), (((4., 2., 10.), (2., 1.), (-.8, 0.)), ((0., .2),)), ) def test_project_preset(self, test_inputs, test_outputs): """Tests that the project function gives the correct result.""" self.assert_output_is_correct(perspective.project, test_inputs, test_outputs) def test_project_unproject_random(self): """Tests that projecting and unprojecting gives an identity mapping.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_point_3d = np.random.normal(size=tensor_shape + [3]) random_focal = np.random.normal(size=tensor_shape + [2]) random_principal_point = np.random.normal(size=tensor_shape + [2]) random_depth = np.expand_dims(random_point_3d[..., 2], axis=-1) point_2d = perspective.project(random_point_3d, random_focal, random_principal_point) point_3d = perspective.unproject(point_2d, random_depth, random_focal, random_principal_point) self.assertAllClose(random_point_3d, point_3d, rtol=1e-3) def test_project_ray_random(self): """Tests that that ray is pointing toward the correct location.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_point_3d = np.random.normal(size=tensor_shape + [3]) random_focal = np.random.normal(size=tensor_shape + [2]) random_principal_point = np.random.normal(size=tensor_shape + [2]) random_depth = np.expand_dims(random_point_3d[..., 2], axis=-1) point_2d = perspective.project(random_point_3d, random_focal, random_principal_point) ray_3d = perspective.ray(point_2d, random_focal, random_principal_point) ray_3d = random_depth * ray_3d self.assertAllClose(random_point_3d, ray_3d, rtol=1e-3) @parameterized.parameters( ((2,), (2,), (2,)), ((2, 2), (2, 2), (2, 2)), ((3, 2), (1, 2), (2,)), ((None, 2), (None, 2), (None, 2)), ) def test_ray_exception_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(perspective.ray, shapes) @parameterized.parameters( ("must have exactly 2 dimensions in axis -1", (None,), (2,), (2,)), ("must have exactly 2 dimensions in axis -1", (2,), (None,), (2,)), ("must have exactly 2 dimensions in axis -1", (2,), (2,), (None,)), ("Not all batch dimensions are broadcast-compatible.", (3, 2), (1, 2), (2, 2)), ) def test_ray_exception_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(perspective.ray, error_msg, shapes) @parameterized.parameters( (((0., 0.), (1., 1.), (0., 0.)), ((0., 0., 1.),)), (((0., 0.), (1., 1.), (-1., -2.)), ((1., 2., 1.),)), (((0., 0.), (10., 1.), (-1., -2.)), ((.1, 2., 1.),)), (((-2., -4.), (10., 1.), (-3., -6.)), ((.1, 2., 1.),)), ) def test_ray_preset(self, test_inputs, test_outputs): """Tests that the ray function gives the correct result.""" self.assert_output_is_correct(perspective.ray, test_inputs, test_outputs) def test_ray_project_random(self): """Tests that the end point of the ray projects at the good location.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_point_2d = np.random.normal(size=tensor_shape + [2]) random_focal = np.random.normal(size=tensor_shape + [2]) random_principal_point = np.random.normal(size=tensor_shape + [2]) ray_3d = perspective.ray(random_point_2d, random_focal, random_principal_point) point_2d = perspective.project(ray_3d, random_focal, random_principal_point) self.assertAllClose(random_point_2d, point_2d, rtol=1e-3) @parameterized.parameters( ((2,), (1,), (2,), (2,)), ((2, 2), (2, 1), (2, 2), (2, 2)), ((None, 2), (None, 1), (None, 2), (None, 2)), ) def test_unproject_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(perspective.unproject, shapes) @parameterized.parameters( ("must have exactly 2 dimensions in axis -1", (None,), (1,), (2,), (2,)), ("must have exactly 1 dimensions in axis -1", (2,), (None,), (2,), (2,)), ("must have exactly 2 dimensions in axis -1", (2,), (1,), (None,), (2,)), ("must have exactly 2 dimensions in axis -1", (2,), (1,), (2,), (None,)), ("Not all batch dimensions are identical.", (1, 2), (2, 1), (2, 2), (2, 2)), ) def test_unproject_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(perspective.unproject, error_msg, shapes) @parameterized.parameters( (((0., 0.), (1.,), (1., 1.), (0., 0.)), ((0., 0., 1.),)), (((0., 0.), (1.,), (1., 1.), (-4., -2.)), ((4., 2., 1.),)), (((0., 0.), (10.,), (1., 1.), (-.4, -.2)), ((4., 2., 10.),)), (((0., 0.), (10.,), (2., 1.), (-.8, -.2)), ((4., 2., 10.),)), (((0., .2), (10.,), (2., 1.), (-.8, 0.)), ((4., 2., 10.),)), ) def test_unproject_preset(self, test_inputs, test_outputs): """Tests that the unproject function gives the correct result.""" self.assert_output_is_correct(perspective.unproject, test_inputs, test_outputs) def test_unproject_project_random(self): """Tests that unprojecting and projecting gives and identity mapping.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_point_2d = np.random.normal(size=tensor_shape + [2]) random_focal = np.random.normal(size=tensor_shape + [2]) random_principal_point = np.random.normal(size=tensor_shape + [2]) random_depth = np.random.normal(size=tensor_shape + [1]) point_3d = perspective.unproject(random_point_2d, random_depth, random_focal, random_principal_point) point_2d = perspective.project(point_3d, random_focal, random_principal_point) self.assertAllClose(random_point_2d, point_2d, rtol=1e-3) def test_unproject_ray_random(self): """Tests that that ray is pointing toward the correct location.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_point_2d = np.random.normal(size=tensor_shape + [2]) random_focal = np.random.normal(size=tensor_shape + [2]) random_principal_point = np.random.normal(size=tensor_shape + [2]) random_depth = np.random.normal(size=tensor_shape + [1]) point_3d = perspective.unproject(random_point_2d, random_depth, random_focal, random_principal_point) ray_3d = perspective.ray(random_point_2d, random_focal, random_principal_point) ray_3d = random_depth * ray_3d self.assertAllClose(point_3d, ray_3d, rtol=1e-3) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/datasets/features/trimesh_feature.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Triangle mesh feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import six import tensorflow.compat.v2 as tf from tensorflow_datasets import features from tensorflow_graphics.io import triangle_mesh class TriangleMesh(features.FeaturesDict): """`FeatureConnector` for triangle meshes. During `_generate_examples`, the feature connector accepts as input any of: * `str`: path to a {obj,stl,ply,glb} triangle mesh. * `trimesh.Trimesh`: A triangle mesh object. * `trimesh.Scene`: A scene object containing multiple TriangleMesh objects. * `dict:` A dictionary containing the vertices and faces of the mesh (see output format below). Output: A dictionary containing: # TODO(b/156112246): Add additional attributes (vertex normals, colors, # texture coordinates). * 'vertices': A `float32` tensor with shape `[N, 3]` denoting the vertex coordinates, where N is the number of vertices in the mesh. * 'faces': An `int64` tensor with shape `[F, 3]` denoting the face vertex indices, where F is the number of faces in the mesh. Note: In case the input specifies a Scene (with multiple meshes), the output will be a single TriangleMesh which combines all the triangle meshes in the scene. """ def __init__(self): super(TriangleMesh, self).__init__({ 'vertices': features.Tensor(shape=(None, 3), dtype=tf.float32), 'faces': features.Tensor(shape=(None, 3), dtype=tf.uint64), }) def encode_example(self, path_or_trianglemesh): """Convert the given triangle mesh into a dict convertible to tf example.""" if isinstance(path_or_trianglemesh, six.string_types): # The parameter is a path. with tf.io.gfile.GFile(path_or_trianglemesh, 'rb') as tmesh_file: features_dict = self._convert_to_trimesh_feature( triangle_mesh.load(tmesh_file)) elif hasattr(path_or_trianglemesh, 'read') and hasattr( path_or_trianglemesh, 'name') and hasattr(path_or_trianglemesh, 'seek'): # The parameter is a file object. path_or_trianglemesh.seek(0) # reset features_dict = self._convert_to_trimesh_feature( triangle_mesh.load(path_or_trianglemesh)) elif isinstance(path_or_trianglemesh, dict): # The parameter is already a Trimesh dictionary. features_dict = path_or_trianglemesh else: # The parameter is a Trimesh or a Scene. features_dict = self._convert_to_trimesh_feature(path_or_trianglemesh) return super(TriangleMesh, self).encode_example(features_dict) def _convert_to_trimesh_feature(self, obj): if isinstance(obj, triangle_mesh.Trimesh): vertices = np.array(obj.vertices) faces = np.array(obj.faces, dtype=np.uint64) elif isinstance(obj, triangle_mesh.Scene): # Concatenate all the vertices and faces of the triangle meshes in the # scene. # TODO(b/156117488): Change to a different merging algorithm to avoid # duplicated vertices. vertices_list = [ np.array(mesh.vertices) for mesh in obj.geometry.values() ] faces_list = np.array([ np.array(mesh.faces, dtype=np.uint64) for mesh in obj.geometry.values() ]) faces_offset = np.cumsum( [vertices.shape[0] for vertices in vertices_list], dtype=np.uint64) faces_list[1:] += faces_offset[:-1] vertices = np.concatenate(vertices_list, axis=0) faces = np.concatenate(faces_list, axis=0) else: raise ValueError('obj should be either a Trimesh or a Scene') return { 'vertices': vertices.astype(np.float32), 'faces': faces, } @classmethod def from_json_content(cls, value) -> 'TriangleMesh': return cls() def to_json_content(self): return {}
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Triangle mesh feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import six import tensorflow.compat.v2 as tf from tensorflow_datasets import features from tensorflow_graphics.io import triangle_mesh class TriangleMesh(features.FeaturesDict): """`FeatureConnector` for triangle meshes. During `_generate_examples`, the feature connector accepts as input any of: * `str`: path to a {obj,stl,ply,glb} triangle mesh. * `trimesh.Trimesh`: A triangle mesh object. * `trimesh.Scene`: A scene object containing multiple TriangleMesh objects. * `dict:` A dictionary containing the vertices and faces of the mesh (see output format below). Output: A dictionary containing: # TODO(b/156112246): Add additional attributes (vertex normals, colors, # texture coordinates). * 'vertices': A `float32` tensor with shape `[N, 3]` denoting the vertex coordinates, where N is the number of vertices in the mesh. * 'faces': An `int64` tensor with shape `[F, 3]` denoting the face vertex indices, where F is the number of faces in the mesh. Note: In case the input specifies a Scene (with multiple meshes), the output will be a single TriangleMesh which combines all the triangle meshes in the scene. """ def __init__(self): super(TriangleMesh, self).__init__({ 'vertices': features.Tensor(shape=(None, 3), dtype=tf.float32), 'faces': features.Tensor(shape=(None, 3), dtype=tf.uint64), }) def encode_example(self, path_or_trianglemesh): """Convert the given triangle mesh into a dict convertible to tf example.""" if isinstance(path_or_trianglemesh, six.string_types): # The parameter is a path. with tf.io.gfile.GFile(path_or_trianglemesh, 'rb') as tmesh_file: features_dict = self._convert_to_trimesh_feature( triangle_mesh.load(tmesh_file)) elif hasattr(path_or_trianglemesh, 'read') and hasattr( path_or_trianglemesh, 'name') and hasattr(path_or_trianglemesh, 'seek'): # The parameter is a file object. path_or_trianglemesh.seek(0) # reset features_dict = self._convert_to_trimesh_feature( triangle_mesh.load(path_or_trianglemesh)) elif isinstance(path_or_trianglemesh, dict): # The parameter is already a Trimesh dictionary. features_dict = path_or_trianglemesh else: # The parameter is a Trimesh or a Scene. features_dict = self._convert_to_trimesh_feature(path_or_trianglemesh) return super(TriangleMesh, self).encode_example(features_dict) def _convert_to_trimesh_feature(self, obj): if isinstance(obj, triangle_mesh.Trimesh): vertices = np.array(obj.vertices) faces = np.array(obj.faces, dtype=np.uint64) elif isinstance(obj, triangle_mesh.Scene): # Concatenate all the vertices and faces of the triangle meshes in the # scene. # TODO(b/156117488): Change to a different merging algorithm to avoid # duplicated vertices. vertices_list = [ np.array(mesh.vertices) for mesh in obj.geometry.values() ] faces_list = np.array([ np.array(mesh.faces, dtype=np.uint64) for mesh in obj.geometry.values() ]) faces_offset = np.cumsum( [vertices.shape[0] for vertices in vertices_list], dtype=np.uint64) faces_list[1:] += faces_offset[:-1] vertices = np.concatenate(vertices_list, axis=0) faces = np.concatenate(faces_list, axis=0) else: raise ValueError('obj should be either a Trimesh or a Scene') return { 'vertices': vertices.astype(np.float32), 'faces': faces, } @classmethod def from_json_content(cls, value) -> 'TriangleMesh': return cls() def to_json_content(self): return {}
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/util/shape.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Shape utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import six import tensorflow as tf def _broadcast_shape_helper(shape_x, shape_y): """Helper function for is_broadcast_compatible and broadcast_shape. Args: shape_x: A `TensorShape`. shape_y: A `TensorShape`. Returns: Returns None if the shapes are not broadcast compatible, or a list containing the broadcasted dimensions otherwise. """ # To compute the broadcasted dimensions, we zip together shape_x and shape_y, # and pad with 1 to make them the same length. broadcasted_dims = reversed( list( six.moves.zip_longest( reversed(shape_x.dims), reversed(shape_y.dims), fillvalue=tf.compat.v1.Dimension(1)))) # Next we combine the dimensions according to the numpy broadcasting rules. # http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html return_dims = [] for (dim_x, dim_y) in broadcasted_dims: if dim_x.value is None or dim_y.value is None: # One or both dimensions is unknown. If either dimension is greater than # 1, we assume that the program is correct, and the other dimension will # be broadcast to match it. if dim_x.value is not None and dim_x.value > 1: return_dims.append(dim_x) elif dim_y.value is not None and dim_y.value > 1: return_dims.append(dim_y) else: return_dims.append(None) elif dim_x.value == 1: # We will broadcast dim_x to dim_y. return_dims.append(dim_y) elif dim_y.value == 1: # We will broadcast dim_y to dim_x. return_dims.append(dim_x) elif dim_x.value == dim_y.value: # The dimensions are compatible, so output is the same size in that # dimension. return_dims.append(dim_x.merge_with(dim_y)) else: return None return return_dims def is_broadcast_compatible(shape_x, shape_y): """Returns True if `shape_x` and `shape_y` are broadcast compatible. Args: shape_x: A `TensorShape`. shape_y: A `TensorShape`. Returns: True if a shape exists that both `shape_x` and `shape_y` can be broadcasted to. False otherwise. """ if shape_x.ndims is None or shape_y.ndims is None: return False return _broadcast_shape_helper(shape_x, shape_y) is not None def get_broadcasted_shape(shape_x, shape_y): """Returns the common shape for broadcast compatible shapes. Args: shape_x: A `TensorShape`. shape_y: A `TensorShape`. Returns: Returns None if the shapes are not broadcast compatible, or a list containing the broadcasted dimensions otherwise. """ if shape_x.ndims is None or shape_y.ndims is None: return None return _broadcast_shape_helper(shape_x, shape_y) def _check_type(variable, variable_name, expected_type): """Helper function for checking that inputs are of expected types.""" if isinstance(expected_type, (list, tuple)): expected_type_name = 'list or tuple' else: expected_type_name = expected_type.__name__ if not isinstance(variable, expected_type): raise ValueError('{} must be of type {}, but it is {}'.format( variable_name, expected_type_name, type(variable).__name__)) def _fix_axis_dim_pairs(pairs, name): """Helper function to make `pairs` a list if needed.""" if isinstance(pairs[0], int): pairs = [pairs] for pair in pairs: if len(pair) != 2: raise ValueError( '{} must consist of axis-value pairs, but found {}'.format( name, pair)) return pairs def _get_dim(tensor, axis): """Returns dimensionality of a tensor for a given axis.""" return tf.compat.v1.dimension_value(tensor.shape[axis]) def check_static(tensor, has_rank=None, has_rank_greater_than=None, has_rank_less_than=None, has_dim_equals=None, has_dim_greater_than=None, has_dim_less_than=None, tensor_name='tensor'): """Checks static shapes for rank and dimension constraints. This function can be used to check a tensor's shape for multiple rank and dimension constraints at the same time. Args: tensor: Any tensor with a static shape. has_rank: An int or `None`. If not `None`, the function checks if the rank of the `tensor` equals to `has_rank`. has_rank_greater_than: An int or `None`. If not `None`, the function checks if the rank of the `tensor` is greater than `has_rank_greater_than`. has_rank_less_than: An int or `None`. If not `None`, the function checks if the rank of the `tensor` is less than `has_rank_less_than`. has_dim_equals: Either a tuple or list containing a single pair of `int`s, or a list or tuple containing multiple such pairs. Each pair is in the form (`axis`, `dim`), which means the function should check if `tensor.shape[axis] == dim`. has_dim_greater_than: Either a tuple or list containing a single pair of `int`s, or a list or tuple containing multiple such pairs. Each pair is in the form (`axis`, `dim`), which means the function should check if `tensor.shape[axis] > dim`. has_dim_less_than: Either a tuple or list containing a single pair of `int`s, or a list or tuple containing multiple such pairs. Each pair is in the form (`axis`, `dim`), which means the function should check if `tensor.shape[axis] < dim`. tensor_name: A name for `tensor` to be used in the error message if one is thrown. Raises: ValueError: If any input is not of the expected types, or if one of the checks described above fails. """ rank = tensor.shape.ndims def _raise_value_error_for_rank(variable, error_msg): raise ValueError( '{} must have a rank {} {}, but it has rank {} and shape {}'.format( tensor_name, error_msg, variable, rank, tensor.shape.as_list())) def _raise_value_error_for_dim(tensor_name, error_msg, axis, value): raise ValueError( '{} must have {} {} dimensions in axis {}, but it has shape {}'.format( tensor_name, error_msg, value, axis, tensor.shape.as_list())) if has_rank is not None: _check_type(has_rank, 'has_rank', int) if rank != has_rank: _raise_value_error_for_rank(has_rank, 'of') if has_rank_greater_than is not None: _check_type(has_rank_greater_than, 'has_rank_greater_than', int) if rank <= has_rank_greater_than: _raise_value_error_for_rank(has_rank_greater_than, 'greater than') if has_rank_less_than is not None: _check_type(has_rank_less_than, 'has_rank_less_than', int) if rank >= has_rank_less_than: _raise_value_error_for_rank(has_rank_less_than, 'less than') if has_dim_equals is not None: _check_type(has_dim_equals, 'has_dim_equals', (list, tuple)) has_dim_equals = _fix_axis_dim_pairs(has_dim_equals, 'has_dim_equals') for axis, value in has_dim_equals: if _get_dim(tensor, axis) != value: _raise_value_error_for_dim(tensor_name, 'exactly', axis, value) if has_dim_greater_than is not None: _check_type(has_dim_greater_than, 'has_dim_greater_than', (list, tuple)) has_dim_greater_than = _fix_axis_dim_pairs(has_dim_greater_than, 'has_dim_greater_than') for axis, value in has_dim_greater_than: if not _get_dim(tensor, axis) > value: _raise_value_error_for_dim(tensor_name, 'greater than', axis, value) if has_dim_less_than is not None: _check_type(has_dim_less_than, 'has_dim_less_than', (list, tuple)) has_dim_less_than = _fix_axis_dim_pairs(has_dim_less_than, 'has_dim_less_than') for axis, value in has_dim_less_than: if not _get_dim(tensor, axis) < value: _raise_value_error_for_dim(tensor_name, 'less than', axis, value) def _check_tensors(tensors, tensors_name): """Helper function to check the type and length of tensors.""" _check_type(tensors, tensors_name, (list, tuple)) if len(tensors) < 2: raise ValueError('At least 2 tensors are required.') def _check_tensor_axis_lists(tensors, tensors_name, axes, axes_name): """Helper function to check that lengths of `tensors` and `axes` match.""" _check_type(axes, axes_name, (list, tuple)) if len(tensors) != len(axes): raise ValueError( '{} and {} must have the same length, but are {} and {}.'.format( tensors_name, axes_name, len(tensors), len(axes))) def _fix_axes(tensors, axes, allow_negative): """Makes all axes positive and checks for out of bound errors.""" axes = [ axis + tensor.shape.ndims if axis < 0 else axis for tensor, axis in zip(tensors, axes) ] if not all( ((allow_negative or (not allow_negative and axis >= 0)) and axis < tensor.shape.ndims) for tensor, axis in zip(tensors, axes)): rank_axis_pairs = zip([tensor.shape.ndims for tensor in tensors], axes) raise ValueError( 'Some axes are out of bounds. Given rank-axes pairs: {}'.format( [pair for pair in rank_axis_pairs])) return axes def _give_default_names(list_of_objects, name): """Helper function to give default names to objects for error messages.""" return [name + '_' + str(index) for index in range(len(list_of_objects))] def _all_are_equal(list_of_objects): """Helper function to check if all the items in a list are the same.""" if not list_of_objects: return True if isinstance(list_of_objects[0], list): list_of_objects = [tuple(obj) for obj in list_of_objects] return len(set(list_of_objects)) == 1 def _raise_error(tensor_names, batch_shapes): formatted_list = [(name, batch_shape) for name, batch_shape in zip(tensor_names, batch_shapes)] raise ValueError( 'Not all batch dimensions are identical: {}'.format(formatted_list)) def compare_batch_dimensions(tensors, last_axes, broadcast_compatible, initial_axes=0, tensor_names=None): """Compares batch dimensions for tensors with static shapes. Args: tensors: A list or tuple of tensors with static shapes to compare. last_axes: An `int` or a list or tuple of `int`s with the same length as `tensors`. If an `int`, it is assumed to be the same for all the tensors. Each entry should correspond to the last axis of the batch (with zero based indices). For instance, if there is only a single batch dimension, last axis should be `0`. broadcast_compatible: A 'bool', whether the batch shapes can be broadcast compatible in the numpy sense. initial_axes: An `int` or a list or tuple of `int`s with the same length as `tensors`. If an `int`, it is assumed to be the same for all the tensors. Each entry should correspond to the first axis of the batch (with zero based indices). Default value is `0`. tensor_names: Names of `tensors` to be used in the error message if one is thrown. If left as `None`, `tensor_i` is used. Raises: ValueError: If inputs have unexpected types, or if given axes are out of bounds, or if the check fails. """ _check_tensors(tensors, 'tensors') if isinstance(initial_axes, int): initial_axes = [initial_axes] * len(tensors) if isinstance(last_axes, int): last_axes = [last_axes] * len(tensors) _check_tensor_axis_lists(tensors, 'tensors', initial_axes, 'initial_axes') _check_tensor_axis_lists(tensors, 'tensors', last_axes, 'last_axes') initial_axes = _fix_axes(tensors, initial_axes, allow_negative=True) last_axes = _fix_axes(tensors, last_axes, allow_negative=True) batch_shapes = [ tensor.shape[init:last + 1] for tensor, init, last in zip(tensors, initial_axes, last_axes) ] if tensor_names is None: tensor_names = _give_default_names(tensors, 'tensor') if not broadcast_compatible: batch_ndims = [batch_shape.ndims for batch_shape in batch_shapes] batch_shapes = [batch_shape.as_list() for batch_shape in batch_shapes] if not _all_are_equal(batch_ndims): # If not all batch shapes have the same length, they cannot be identical. _raise_error(tensor_names, batch_shapes) for dims in zip(*batch_shapes): if _all_are_equal(dims): # Continue if all dimensions are None or have the same value. continue if None not in dims: # If all dimensions are known at this point, they are not identical. _raise_error(tensor_names, batch_shapes) # At this point dims must consist of both None's and int's. if len(set(dims)) != 2: # set(dims) should return (None, some_int). # Otherwise shapes are not identical. _raise_error(tensor_names, batch_shapes) else: if not all( is_broadcast_compatible(shape1, shape2) for shape1, shape2 in itertools.combinations(batch_shapes, 2)): raise ValueError( 'Not all batch dimensions are broadcast-compatible: {}'.format([ (name, batch_shape.as_list()) for name, batch_shape in zip(tensor_names, batch_shapes) ])) def compare_dimensions(tensors, axes, tensor_names=None): """Compares dimensions of tensors with static or dynamic shapes. Args: tensors: A list or tuple of tensors to compare. axes: An `int` or a list or tuple of `int`s with the same length as `tensors`. If an `int`, it is assumed to be the same for all the tensors. Each entry should correspond to the axis of the tensor being compared. tensor_names: Names of `tensors` to be used in the error message if one is thrown. If left as `None`, their `Tensor.name` fields are used instead. Raises: ValueError: If inputs have unexpected types, or if given axes are out of bounds, or if the check fails. """ _check_tensors(tensors, 'tensors') if isinstance(axes, int): axes = [axes] * len(tensors) _check_tensor_axis_lists(tensors, 'tensors', axes, 'axes') axes = _fix_axes(tensors, axes, allow_negative=False) if tensor_names is None: tensor_names = _give_default_names(tensors, 'tensor') dimensions = [_get_dim(tensor, axis) for tensor, axis in zip(tensors, axes)] if not _all_are_equal(dimensions): raise ValueError('Tensors {} must have the same number of dimensions in ' 'axes {}, but they are {}.'.format( list(tensor_names), list(axes), list(dimensions))) def is_static(tensor_shape): """Checks if the given tensor shape is static.""" if isinstance(tensor_shape, (list, tuple)): return None not in tensor_shape else: return None not in tensor_shape.as_list() # The util functions or classes are not exported. __all__ = []
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Shape utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import six import tensorflow as tf def _broadcast_shape_helper(shape_x, shape_y): """Helper function for is_broadcast_compatible and broadcast_shape. Args: shape_x: A `TensorShape`. shape_y: A `TensorShape`. Returns: Returns None if the shapes are not broadcast compatible, or a list containing the broadcasted dimensions otherwise. """ # To compute the broadcasted dimensions, we zip together shape_x and shape_y, # and pad with 1 to make them the same length. broadcasted_dims = reversed( list( six.moves.zip_longest( reversed(shape_x.dims), reversed(shape_y.dims), fillvalue=tf.compat.v1.Dimension(1)))) # Next we combine the dimensions according to the numpy broadcasting rules. # http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html return_dims = [] for (dim_x, dim_y) in broadcasted_dims: if dim_x.value is None or dim_y.value is None: # One or both dimensions is unknown. If either dimension is greater than # 1, we assume that the program is correct, and the other dimension will # be broadcast to match it. if dim_x.value is not None and dim_x.value > 1: return_dims.append(dim_x) elif dim_y.value is not None and dim_y.value > 1: return_dims.append(dim_y) else: return_dims.append(None) elif dim_x.value == 1: # We will broadcast dim_x to dim_y. return_dims.append(dim_y) elif dim_y.value == 1: # We will broadcast dim_y to dim_x. return_dims.append(dim_x) elif dim_x.value == dim_y.value: # The dimensions are compatible, so output is the same size in that # dimension. return_dims.append(dim_x.merge_with(dim_y)) else: return None return return_dims def is_broadcast_compatible(shape_x, shape_y): """Returns True if `shape_x` and `shape_y` are broadcast compatible. Args: shape_x: A `TensorShape`. shape_y: A `TensorShape`. Returns: True if a shape exists that both `shape_x` and `shape_y` can be broadcasted to. False otherwise. """ if shape_x.ndims is None or shape_y.ndims is None: return False return _broadcast_shape_helper(shape_x, shape_y) is not None def get_broadcasted_shape(shape_x, shape_y): """Returns the common shape for broadcast compatible shapes. Args: shape_x: A `TensorShape`. shape_y: A `TensorShape`. Returns: Returns None if the shapes are not broadcast compatible, or a list containing the broadcasted dimensions otherwise. """ if shape_x.ndims is None or shape_y.ndims is None: return None return _broadcast_shape_helper(shape_x, shape_y) def _check_type(variable, variable_name, expected_type): """Helper function for checking that inputs are of expected types.""" if isinstance(expected_type, (list, tuple)): expected_type_name = 'list or tuple' else: expected_type_name = expected_type.__name__ if not isinstance(variable, expected_type): raise ValueError('{} must be of type {}, but it is {}'.format( variable_name, expected_type_name, type(variable).__name__)) def _fix_axis_dim_pairs(pairs, name): """Helper function to make `pairs` a list if needed.""" if isinstance(pairs[0], int): pairs = [pairs] for pair in pairs: if len(pair) != 2: raise ValueError( '{} must consist of axis-value pairs, but found {}'.format( name, pair)) return pairs def _get_dim(tensor, axis): """Returns dimensionality of a tensor for a given axis.""" return tf.compat.v1.dimension_value(tensor.shape[axis]) def check_static(tensor, has_rank=None, has_rank_greater_than=None, has_rank_less_than=None, has_dim_equals=None, has_dim_greater_than=None, has_dim_less_than=None, tensor_name='tensor'): """Checks static shapes for rank and dimension constraints. This function can be used to check a tensor's shape for multiple rank and dimension constraints at the same time. Args: tensor: Any tensor with a static shape. has_rank: An int or `None`. If not `None`, the function checks if the rank of the `tensor` equals to `has_rank`. has_rank_greater_than: An int or `None`. If not `None`, the function checks if the rank of the `tensor` is greater than `has_rank_greater_than`. has_rank_less_than: An int or `None`. If not `None`, the function checks if the rank of the `tensor` is less than `has_rank_less_than`. has_dim_equals: Either a tuple or list containing a single pair of `int`s, or a list or tuple containing multiple such pairs. Each pair is in the form (`axis`, `dim`), which means the function should check if `tensor.shape[axis] == dim`. has_dim_greater_than: Either a tuple or list containing a single pair of `int`s, or a list or tuple containing multiple such pairs. Each pair is in the form (`axis`, `dim`), which means the function should check if `tensor.shape[axis] > dim`. has_dim_less_than: Either a tuple or list containing a single pair of `int`s, or a list or tuple containing multiple such pairs. Each pair is in the form (`axis`, `dim`), which means the function should check if `tensor.shape[axis] < dim`. tensor_name: A name for `tensor` to be used in the error message if one is thrown. Raises: ValueError: If any input is not of the expected types, or if one of the checks described above fails. """ rank = tensor.shape.ndims def _raise_value_error_for_rank(variable, error_msg): raise ValueError( '{} must have a rank {} {}, but it has rank {} and shape {}'.format( tensor_name, error_msg, variable, rank, tensor.shape.as_list())) def _raise_value_error_for_dim(tensor_name, error_msg, axis, value): raise ValueError( '{} must have {} {} dimensions in axis {}, but it has shape {}'.format( tensor_name, error_msg, value, axis, tensor.shape.as_list())) if has_rank is not None: _check_type(has_rank, 'has_rank', int) if rank != has_rank: _raise_value_error_for_rank(has_rank, 'of') if has_rank_greater_than is not None: _check_type(has_rank_greater_than, 'has_rank_greater_than', int) if rank <= has_rank_greater_than: _raise_value_error_for_rank(has_rank_greater_than, 'greater than') if has_rank_less_than is not None: _check_type(has_rank_less_than, 'has_rank_less_than', int) if rank >= has_rank_less_than: _raise_value_error_for_rank(has_rank_less_than, 'less than') if has_dim_equals is not None: _check_type(has_dim_equals, 'has_dim_equals', (list, tuple)) has_dim_equals = _fix_axis_dim_pairs(has_dim_equals, 'has_dim_equals') for axis, value in has_dim_equals: if _get_dim(tensor, axis) != value: _raise_value_error_for_dim(tensor_name, 'exactly', axis, value) if has_dim_greater_than is not None: _check_type(has_dim_greater_than, 'has_dim_greater_than', (list, tuple)) has_dim_greater_than = _fix_axis_dim_pairs(has_dim_greater_than, 'has_dim_greater_than') for axis, value in has_dim_greater_than: if not _get_dim(tensor, axis) > value: _raise_value_error_for_dim(tensor_name, 'greater than', axis, value) if has_dim_less_than is not None: _check_type(has_dim_less_than, 'has_dim_less_than', (list, tuple)) has_dim_less_than = _fix_axis_dim_pairs(has_dim_less_than, 'has_dim_less_than') for axis, value in has_dim_less_than: if not _get_dim(tensor, axis) < value: _raise_value_error_for_dim(tensor_name, 'less than', axis, value) def _check_tensors(tensors, tensors_name): """Helper function to check the type and length of tensors.""" _check_type(tensors, tensors_name, (list, tuple)) if len(tensors) < 2: raise ValueError('At least 2 tensors are required.') def _check_tensor_axis_lists(tensors, tensors_name, axes, axes_name): """Helper function to check that lengths of `tensors` and `axes` match.""" _check_type(axes, axes_name, (list, tuple)) if len(tensors) != len(axes): raise ValueError( '{} and {} must have the same length, but are {} and {}.'.format( tensors_name, axes_name, len(tensors), len(axes))) def _fix_axes(tensors, axes, allow_negative): """Makes all axes positive and checks for out of bound errors.""" axes = [ axis + tensor.shape.ndims if axis < 0 else axis for tensor, axis in zip(tensors, axes) ] if not all( ((allow_negative or (not allow_negative and axis >= 0)) and axis < tensor.shape.ndims) for tensor, axis in zip(tensors, axes)): rank_axis_pairs = zip([tensor.shape.ndims for tensor in tensors], axes) raise ValueError( 'Some axes are out of bounds. Given rank-axes pairs: {}'.format( [pair for pair in rank_axis_pairs])) return axes def _give_default_names(list_of_objects, name): """Helper function to give default names to objects for error messages.""" return [name + '_' + str(index) for index in range(len(list_of_objects))] def _all_are_equal(list_of_objects): """Helper function to check if all the items in a list are the same.""" if not list_of_objects: return True if isinstance(list_of_objects[0], list): list_of_objects = [tuple(obj) for obj in list_of_objects] return len(set(list_of_objects)) == 1 def _raise_error(tensor_names, batch_shapes): formatted_list = [(name, batch_shape) for name, batch_shape in zip(tensor_names, batch_shapes)] raise ValueError( 'Not all batch dimensions are identical: {}'.format(formatted_list)) def compare_batch_dimensions(tensors, last_axes, broadcast_compatible, initial_axes=0, tensor_names=None): """Compares batch dimensions for tensors with static shapes. Args: tensors: A list or tuple of tensors with static shapes to compare. last_axes: An `int` or a list or tuple of `int`s with the same length as `tensors`. If an `int`, it is assumed to be the same for all the tensors. Each entry should correspond to the last axis of the batch (with zero based indices). For instance, if there is only a single batch dimension, last axis should be `0`. broadcast_compatible: A 'bool', whether the batch shapes can be broadcast compatible in the numpy sense. initial_axes: An `int` or a list or tuple of `int`s with the same length as `tensors`. If an `int`, it is assumed to be the same for all the tensors. Each entry should correspond to the first axis of the batch (with zero based indices). Default value is `0`. tensor_names: Names of `tensors` to be used in the error message if one is thrown. If left as `None`, `tensor_i` is used. Raises: ValueError: If inputs have unexpected types, or if given axes are out of bounds, or if the check fails. """ _check_tensors(tensors, 'tensors') if isinstance(initial_axes, int): initial_axes = [initial_axes] * len(tensors) if isinstance(last_axes, int): last_axes = [last_axes] * len(tensors) _check_tensor_axis_lists(tensors, 'tensors', initial_axes, 'initial_axes') _check_tensor_axis_lists(tensors, 'tensors', last_axes, 'last_axes') initial_axes = _fix_axes(tensors, initial_axes, allow_negative=True) last_axes = _fix_axes(tensors, last_axes, allow_negative=True) batch_shapes = [ tensor.shape[init:last + 1] for tensor, init, last in zip(tensors, initial_axes, last_axes) ] if tensor_names is None: tensor_names = _give_default_names(tensors, 'tensor') if not broadcast_compatible: batch_ndims = [batch_shape.ndims for batch_shape in batch_shapes] batch_shapes = [batch_shape.as_list() for batch_shape in batch_shapes] if not _all_are_equal(batch_ndims): # If not all batch shapes have the same length, they cannot be identical. _raise_error(tensor_names, batch_shapes) for dims in zip(*batch_shapes): if _all_are_equal(dims): # Continue if all dimensions are None or have the same value. continue if None not in dims: # If all dimensions are known at this point, they are not identical. _raise_error(tensor_names, batch_shapes) # At this point dims must consist of both None's and int's. if len(set(dims)) != 2: # set(dims) should return (None, some_int). # Otherwise shapes are not identical. _raise_error(tensor_names, batch_shapes) else: if not all( is_broadcast_compatible(shape1, shape2) for shape1, shape2 in itertools.combinations(batch_shapes, 2)): raise ValueError( 'Not all batch dimensions are broadcast-compatible: {}'.format([ (name, batch_shape.as_list()) for name, batch_shape in zip(tensor_names, batch_shapes) ])) def compare_dimensions(tensors, axes, tensor_names=None): """Compares dimensions of tensors with static or dynamic shapes. Args: tensors: A list or tuple of tensors to compare. axes: An `int` or a list or tuple of `int`s with the same length as `tensors`. If an `int`, it is assumed to be the same for all the tensors. Each entry should correspond to the axis of the tensor being compared. tensor_names: Names of `tensors` to be used in the error message if one is thrown. If left as `None`, their `Tensor.name` fields are used instead. Raises: ValueError: If inputs have unexpected types, or if given axes are out of bounds, or if the check fails. """ _check_tensors(tensors, 'tensors') if isinstance(axes, int): axes = [axes] * len(tensors) _check_tensor_axis_lists(tensors, 'tensors', axes, 'axes') axes = _fix_axes(tensors, axes, allow_negative=False) if tensor_names is None: tensor_names = _give_default_names(tensors, 'tensor') dimensions = [_get_dim(tensor, axis) for tensor, axis in zip(tensors, axes)] if not _all_are_equal(dimensions): raise ValueError('Tensors {} must have the same number of dimensions in ' 'axes {}, but they are {}.'.format( list(tensor_names), list(axes), list(dimensions))) def is_static(tensor_shape): """Checks if the given tensor shape is static.""" if isinstance(tensor_shape, (list, tuple)): return None not in tensor_shape else: return None not in tensor_shape.as_list() # The util functions or classes are not exported. __all__ = []
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/image/tests/matting_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for matting.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.image import matting from tensorflow_graphics.util import asserts from tensorflow_graphics.util import shape from tensorflow_graphics.util import test_case def _laplacian_matrix(image, size=3, eps=1e-5, name=None): """Generates the closed form matting Laplacian matrices. Generates the closed form matting Laplacian as proposed by Levin et al. in "A Closed Form Solution to Natural Image Matting". Args: image: A tensor of shape `[B, H, W, C]`. size: An `int` representing the size of the patches used to enforce smoothness. eps: A small number of type `float` to regularize the problem. name: A name for this op. Defaults to "matting_laplacian_matrix". Returns: A tensor of shape `[B, H, W, size^2, size^2]` containing the matting Laplacian matrices. Raises: ValueError: If `image` is not of rank 4. """ with tf.compat.v1.name_scope(name, "matting_laplacian_matrix", [image]): image = tf.convert_to_tensor(value=image) shape.check_static(image, has_rank=4) if size % 2 == 0: raise ValueError("The patch size is expected to be an odd value.") pixels = size**2 channels = tf.shape(input=image)[-1] dtype = image.dtype patches = tf.image.extract_patches( image, sizes=(1, size, size, 1), strides=(1, 1, 1, 1), rates=(1, 1, 1, 1), padding="VALID") batches = tf.shape(input=patches)[:-1] new_shape = tf.concat((batches, (pixels, channels)), axis=-1) patches = tf.reshape(patches, shape=new_shape) mean = tf.reduce_mean(input_tensor=patches, axis=-2, keepdims=True) demean = patches - mean covariance = tf.matmul(demean, demean, transpose_a=True) / pixels regularizer = (eps / pixels) * tf.eye(channels, dtype=dtype) covariance_inv = tf.linalg.inv(covariance + regularizer) covariance_inv = asserts.assert_no_infs_or_nans(covariance_inv) mat = tf.matmul(tf.matmul(demean, covariance_inv), demean, transpose_b=True) return tf.eye(pixels, dtype=dtype) - (1.0 + mat) / pixels class MattingTest(test_case.TestCase): @parameterized.parameters((3, 1), (3, 3), (5, 3), (5, 1)) def test_build_matrices_jacobian_random(self, size, channels): """Tests the Jacobian of the build_matrices function.""" tensor_shape = np.random.randint(size, 6, size=3) image_init = np.random.uniform( 0.0, 1.0, size=tensor_shape.tolist() + [channels]) with self.subTest(name="laplacian"): self.assert_jacobian_is_correct_fn( lambda image: matting.build_matrices(image, size=size)[0], [image_init]) with self.subTest(name="pseudo_inverse"): self.assert_jacobian_is_correct_fn( lambda image: matting.build_matrices(image, size=size)[1], [image_init]) @parameterized.parameters((3, 1), (3, 3), (5, 3), (5, 1)) def test_build_matrices_laplacian_zero_rows_and_columns(self, size, channels): """Tests that the laplacian matrix rows and columns sum to zero.""" tensor_shape = np.random.randint(size, 6, size=3) image_init = np.random.uniform( 0.0, 1.0, size=tensor_shape.tolist() + [channels]) image = tf.convert_to_tensor(value=image_init) laplacian, _ = matting.build_matrices(image, size=size) rows = tf.reduce_sum(input_tensor=laplacian, axis=-2) columns = tf.reduce_sum(input_tensor=laplacian, axis=-1) with self.subTest(name="rows"): self.assertAllClose(rows, tf.zeros_like(rows)) with self.subTest(name="columns"): self.assertAllClose(columns, tf.zeros_like(columns)) @parameterized.parameters((3, 1), (3, 3), (5, 3), (5, 1)) def test_build_matrices_laplacian_versions(self, size, channels): """Compares two ways of computing the laplacian matrix.""" tensor_shape = np.random.randint(size, 6, size=3) image_init = np.random.uniform( 0.0, 1.0, size=tensor_shape.tolist() + [channels]) image = tf.convert_to_tensor(value=image_init) laplacian_v1, _ = matting.build_matrices(image, size=size) laplacian_v2 = _laplacian_matrix(image, size=size) self.assertAllClose(laplacian_v1, laplacian_v2) @parameterized.parameters( (3, (None, None, None, 1)), (3, (None, None, None, 3)), (5, (None, None, None, 1)), (5, (None, None, None, 3)), (3, (1, 3, 3, 1)), (3, (1, 3, 3, 3)), (5, (1, 5, 5, 1)), (5, (1, 5, 5, 3)), ) def test_build_matrices_not_raised(self, size, *shapes): """Tests that the shape exceptions are not raised.""" build_matrices = lambda image: matting.build_matrices(image, size=size) self.assert_exception_is_not_raised(build_matrices, shapes) @parameterized.parameters( ("tensor must have a rank of 4, but it has rank", 3, (1,)), ("tensor must have a rank of 4, but it has rank", 3, (1, 1, 1, 1, 1)), ("The patch size is expected to be an odd value.", 2, (1, 1, 1, 1)), ) def test_build_matrices_raised(self, error_msg, size, *shapes): """Tests that the shape exceptions are properly raised.""" build_matrices = lambda image: matting.build_matrices(image, size=size) self.assert_exception_is_raised(build_matrices, error_msg, shapes) @parameterized.parameters((3,), (5,)) def test_linear_coefficients_jacobian_random(self, size): """Tests the Jacobian of the linear_coefficients function.""" tensor_shape = np.random.randint(size, 6, size=3) matte_init = np.random.uniform(0.0, 1.0, size=tensor_shape.tolist() + [1]) tensor_shape[1:3] -= (size - 1) num_coeffs = np.random.randint(2, 4) pseudo_inverse_init = np.random.uniform( 0.0, 1.0, size=tensor_shape.tolist() + [num_coeffs, size**2]) def a_fn(matte, pseudo_inverse): a, _ = matting.linear_coefficients(matte, pseudo_inverse) return a def b_fn(matte, pseudo_inverse): _, b = matting.linear_coefficients(matte, pseudo_inverse) return b with self.subTest(name="a"): self.assert_jacobian_is_correct_fn(a_fn, [matte_init, pseudo_inverse_init]) with self.subTest(name="b"): self.assert_jacobian_is_correct_fn(b_fn, [matte_init, pseudo_inverse_init]) @parameterized.parameters( ((None, None, None, 1), (None, None, None, 4, 9)), ((None, None, None, 1), (None, None, None, 2, 25)), ((1, 6, 6, 1), (1, 4, 4, 2, 9)), ((1, 10, 10, 1), (1, 6, 6, 2, 25)), ) def test_linear_coefficients_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(matting.linear_coefficients, shapes) @parameterized.parameters( ("must have exactly 1 dimensions in axis -1", (1, 6, 6, 2), (1, 4, 4, 2, 9)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (2, 4, 4, 2, 9)), ) def test_linear_coefficients_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(matting.linear_coefficients, error_msg, shapes) @parameterized.parameters((3,), (5,)) def test_linear_coefficients_reconstruction_same_images(self, size): """Tests that the matte can be reconstructed by using the coefficients .""" tensor_shape = np.random.randint(size, 6, size=3).tolist() image = np.random.uniform(0.0, 1.0, size=tensor_shape + [1]) _, pseudo_inverse = matting.build_matrices(image, size=size) a, b = matting.linear_coefficients(image, pseudo_inverse) reconstructed = matting.reconstruct(image, a, b) self.assertAllClose(image, reconstructed, atol=1e-4) @parameterized.parameters((3,), (5,)) def test_linear_coefficients_reconstruction_opposite_images(self, size): """Tests that the matte can be reconstructed by using the coefficients .""" tensor_shape = np.random.randint(size, 6, size=3).tolist() image = np.random.uniform(0.0, 1.0, size=tensor_shape + [1]) _, pseudo_inverse = matting.build_matrices(image, size=size) a, b = matting.linear_coefficients(1.0 - image, pseudo_inverse) reconstructed = matting.reconstruct(image, a, b) self.assertAllClose(1.0 - image, reconstructed, atol=1e-4) @parameterized.parameters((3,), (5,)) def test_loss_jacobian_random(self, size): """Tests the Jacobian of the matting loss function.""" tensor_shape = np.random.randint(size, 6, size=3) matte_init = np.random.uniform(0.0, 1.0, size=tensor_shape.tolist() + [1]) tensor_shape[1:3] -= (size - 1) laplacian_init = np.random.uniform( 0.0, 1.0, size=tensor_shape.tolist() + [size**2, size**2]) with self.subTest(name="matte"): self.assert_jacobian_is_correct_fn(matting.loss, [matte_init, laplacian_init]) @parameterized.parameters( ((None, None, None, 1), (None, None, None, 9, 9)), ((None, None, None, 1), (None, None, None, 25, 25)), ((1, 6, 6, 1), (1, 4, 4, 9, 9)), ((1, 10, 10, 1), (1, 6, 6, 25, 25)), ) def test_loss_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(matting.loss, shapes) @parameterized.parameters( ("must have exactly 1 dimensions in axis -1", (1, 6, 6, 2), (1, 4, 4, 9, 9)), ("must have exactly 9 dimensions in axis -2", (1, 6, 6, 1), (1, 4, 4, 1, 9)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (2, 4, 4, 9, 9)), ) def test_loss_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(matting.loss, error_msg, shapes) @parameterized.parameters((3,), (5,)) def test_loss_opposite_images(self, size): """Tests that passing opposite images results in a loss close to 0.0.""" tensor_shape = np.random.randint(size, 6, size=3).tolist() image = np.random.uniform(0.0, 1.0, size=tensor_shape + [1]) laplacian, _ = matting.build_matrices(image, size=size) loss = matting.loss(1.0 - image, laplacian) self.assertAllClose(loss, 0.0, atol=1e-4) @parameterized.parameters((3,), (5,)) def test_loss_same_images(self, size): """Tests that passing same images results in a loss close to 0.0.""" tensor_shape = np.random.randint(size, 6, size=3).tolist() image = np.random.uniform(0.0, 1.0, size=tensor_shape + [1]) laplacian, _ = matting.build_matrices(image, size=size) loss = matting.loss(image, laplacian) self.assertAllClose(loss, 0.0, atol=1e-4) @parameterized.parameters((3,), (5,)) def test_loss_positive(self, size): """Tests that the loss is always greater or equal to 0.0.""" tensor_shape = np.random.randint(size, 6, size=3).tolist() image = tf.random.uniform(minval=0.0, maxval=1.0, shape=tensor_shape + [3]) matte = tf.random.uniform(minval=0.0, maxval=1.0, shape=tensor_shape + [1]) laplacian, _ = matting.build_matrices(image, size=size) loss = matting.loss(matte, laplacian) self.assertAllGreaterEqual(loss, 0.0) @parameterized.parameters((1,), (3,)) def test_reconstruct_jacobian_random(self, channels): """Tests the Jacobian of the reconstruct function.""" tensor_shape = np.random.randint(1, 5, size=3).tolist() image_init = np.random.uniform(0.0, 1.0, size=tensor_shape + [channels]) mul_init = np.random.uniform(0.0, 1.0, size=tensor_shape + [channels]) add_init = np.random.uniform(0.0, 1.0, size=tensor_shape + [1]) self.assert_jacobian_is_correct_fn(matting.reconstruct, [image_init, mul_init, add_init]) @parameterized.parameters( ((None, None, None, 3), (None, None, None, 3), (None, None, None, 1)), ((1, 6, 6, 3), (1, 6, 6, 3), (1, 6, 6, 1)), ) def test_reconstruct_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(matting.reconstruct, shapes) @parameterized.parameters( ("tensor must have a rank of 4, but it has rank", (1, 6, 6), (1, 6, 6, 2), (1, 6, 6, 1)), ("tensor must have a rank of 4, but it has rank", (1, 6, 6, 2), (1, 6, 6), (1, 6, 6, 1)), ("tensor must have a rank of 4, but it has rank", (1, 6, 6, 2), (1, 6, 6, 2), (1, 6, 6)), ("must have exactly 1 dimensions in axis -1", (1, 6, 6, 2), (1, 6, 6, 2), (1, 6, 6, 2)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (1, 6, 6, 4), (1, 6, 6, 1)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (1, 4, 6, 1), (1, 6, 6, 1)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (1, 6, 6, 1), (1, 4, 6, 1)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (1, 6, 4, 1), (1, 6, 6, 1)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (1, 6, 6, 1), (1, 6, 4, 1)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (4, 6, 6, 1), (1, 6, 6, 1)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (1, 6, 6, 1), (4, 6, 6, 1)), ) def test_reconstruct_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(matting.reconstruct, error_msg, shapes) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for matting.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.image import matting from tensorflow_graphics.util import asserts from tensorflow_graphics.util import shape from tensorflow_graphics.util import test_case def _laplacian_matrix(image, size=3, eps=1e-5, name=None): """Generates the closed form matting Laplacian matrices. Generates the closed form matting Laplacian as proposed by Levin et al. in "A Closed Form Solution to Natural Image Matting". Args: image: A tensor of shape `[B, H, W, C]`. size: An `int` representing the size of the patches used to enforce smoothness. eps: A small number of type `float` to regularize the problem. name: A name for this op. Defaults to "matting_laplacian_matrix". Returns: A tensor of shape `[B, H, W, size^2, size^2]` containing the matting Laplacian matrices. Raises: ValueError: If `image` is not of rank 4. """ with tf.compat.v1.name_scope(name, "matting_laplacian_matrix", [image]): image = tf.convert_to_tensor(value=image) shape.check_static(image, has_rank=4) if size % 2 == 0: raise ValueError("The patch size is expected to be an odd value.") pixels = size**2 channels = tf.shape(input=image)[-1] dtype = image.dtype patches = tf.image.extract_patches( image, sizes=(1, size, size, 1), strides=(1, 1, 1, 1), rates=(1, 1, 1, 1), padding="VALID") batches = tf.shape(input=patches)[:-1] new_shape = tf.concat((batches, (pixels, channels)), axis=-1) patches = tf.reshape(patches, shape=new_shape) mean = tf.reduce_mean(input_tensor=patches, axis=-2, keepdims=True) demean = patches - mean covariance = tf.matmul(demean, demean, transpose_a=True) / pixels regularizer = (eps / pixels) * tf.eye(channels, dtype=dtype) covariance_inv = tf.linalg.inv(covariance + regularizer) covariance_inv = asserts.assert_no_infs_or_nans(covariance_inv) mat = tf.matmul(tf.matmul(demean, covariance_inv), demean, transpose_b=True) return tf.eye(pixels, dtype=dtype) - (1.0 + mat) / pixels class MattingTest(test_case.TestCase): @parameterized.parameters((3, 1), (3, 3), (5, 3), (5, 1)) def test_build_matrices_jacobian_random(self, size, channels): """Tests the Jacobian of the build_matrices function.""" tensor_shape = np.random.randint(size, 6, size=3) image_init = np.random.uniform( 0.0, 1.0, size=tensor_shape.tolist() + [channels]) with self.subTest(name="laplacian"): self.assert_jacobian_is_correct_fn( lambda image: matting.build_matrices(image, size=size)[0], [image_init]) with self.subTest(name="pseudo_inverse"): self.assert_jacobian_is_correct_fn( lambda image: matting.build_matrices(image, size=size)[1], [image_init]) @parameterized.parameters((3, 1), (3, 3), (5, 3), (5, 1)) def test_build_matrices_laplacian_zero_rows_and_columns(self, size, channels): """Tests that the laplacian matrix rows and columns sum to zero.""" tensor_shape = np.random.randint(size, 6, size=3) image_init = np.random.uniform( 0.0, 1.0, size=tensor_shape.tolist() + [channels]) image = tf.convert_to_tensor(value=image_init) laplacian, _ = matting.build_matrices(image, size=size) rows = tf.reduce_sum(input_tensor=laplacian, axis=-2) columns = tf.reduce_sum(input_tensor=laplacian, axis=-1) with self.subTest(name="rows"): self.assertAllClose(rows, tf.zeros_like(rows)) with self.subTest(name="columns"): self.assertAllClose(columns, tf.zeros_like(columns)) @parameterized.parameters((3, 1), (3, 3), (5, 3), (5, 1)) def test_build_matrices_laplacian_versions(self, size, channels): """Compares two ways of computing the laplacian matrix.""" tensor_shape = np.random.randint(size, 6, size=3) image_init = np.random.uniform( 0.0, 1.0, size=tensor_shape.tolist() + [channels]) image = tf.convert_to_tensor(value=image_init) laplacian_v1, _ = matting.build_matrices(image, size=size) laplacian_v2 = _laplacian_matrix(image, size=size) self.assertAllClose(laplacian_v1, laplacian_v2) @parameterized.parameters( (3, (None, None, None, 1)), (3, (None, None, None, 3)), (5, (None, None, None, 1)), (5, (None, None, None, 3)), (3, (1, 3, 3, 1)), (3, (1, 3, 3, 3)), (5, (1, 5, 5, 1)), (5, (1, 5, 5, 3)), ) def test_build_matrices_not_raised(self, size, *shapes): """Tests that the shape exceptions are not raised.""" build_matrices = lambda image: matting.build_matrices(image, size=size) self.assert_exception_is_not_raised(build_matrices, shapes) @parameterized.parameters( ("tensor must have a rank of 4, but it has rank", 3, (1,)), ("tensor must have a rank of 4, but it has rank", 3, (1, 1, 1, 1, 1)), ("The patch size is expected to be an odd value.", 2, (1, 1, 1, 1)), ) def test_build_matrices_raised(self, error_msg, size, *shapes): """Tests that the shape exceptions are properly raised.""" build_matrices = lambda image: matting.build_matrices(image, size=size) self.assert_exception_is_raised(build_matrices, error_msg, shapes) @parameterized.parameters((3,), (5,)) def test_linear_coefficients_jacobian_random(self, size): """Tests the Jacobian of the linear_coefficients function.""" tensor_shape = np.random.randint(size, 6, size=3) matte_init = np.random.uniform(0.0, 1.0, size=tensor_shape.tolist() + [1]) tensor_shape[1:3] -= (size - 1) num_coeffs = np.random.randint(2, 4) pseudo_inverse_init = np.random.uniform( 0.0, 1.0, size=tensor_shape.tolist() + [num_coeffs, size**2]) def a_fn(matte, pseudo_inverse): a, _ = matting.linear_coefficients(matte, pseudo_inverse) return a def b_fn(matte, pseudo_inverse): _, b = matting.linear_coefficients(matte, pseudo_inverse) return b with self.subTest(name="a"): self.assert_jacobian_is_correct_fn(a_fn, [matte_init, pseudo_inverse_init]) with self.subTest(name="b"): self.assert_jacobian_is_correct_fn(b_fn, [matte_init, pseudo_inverse_init]) @parameterized.parameters( ((None, None, None, 1), (None, None, None, 4, 9)), ((None, None, None, 1), (None, None, None, 2, 25)), ((1, 6, 6, 1), (1, 4, 4, 2, 9)), ((1, 10, 10, 1), (1, 6, 6, 2, 25)), ) def test_linear_coefficients_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(matting.linear_coefficients, shapes) @parameterized.parameters( ("must have exactly 1 dimensions in axis -1", (1, 6, 6, 2), (1, 4, 4, 2, 9)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (2, 4, 4, 2, 9)), ) def test_linear_coefficients_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(matting.linear_coefficients, error_msg, shapes) @parameterized.parameters((3,), (5,)) def test_linear_coefficients_reconstruction_same_images(self, size): """Tests that the matte can be reconstructed by using the coefficients .""" tensor_shape = np.random.randint(size, 6, size=3).tolist() image = np.random.uniform(0.0, 1.0, size=tensor_shape + [1]) _, pseudo_inverse = matting.build_matrices(image, size=size) a, b = matting.linear_coefficients(image, pseudo_inverse) reconstructed = matting.reconstruct(image, a, b) self.assertAllClose(image, reconstructed, atol=1e-4) @parameterized.parameters((3,), (5,)) def test_linear_coefficients_reconstruction_opposite_images(self, size): """Tests that the matte can be reconstructed by using the coefficients .""" tensor_shape = np.random.randint(size, 6, size=3).tolist() image = np.random.uniform(0.0, 1.0, size=tensor_shape + [1]) _, pseudo_inverse = matting.build_matrices(image, size=size) a, b = matting.linear_coefficients(1.0 - image, pseudo_inverse) reconstructed = matting.reconstruct(image, a, b) self.assertAllClose(1.0 - image, reconstructed, atol=1e-4) @parameterized.parameters((3,), (5,)) def test_loss_jacobian_random(self, size): """Tests the Jacobian of the matting loss function.""" tensor_shape = np.random.randint(size, 6, size=3) matte_init = np.random.uniform(0.0, 1.0, size=tensor_shape.tolist() + [1]) tensor_shape[1:3] -= (size - 1) laplacian_init = np.random.uniform( 0.0, 1.0, size=tensor_shape.tolist() + [size**2, size**2]) with self.subTest(name="matte"): self.assert_jacobian_is_correct_fn(matting.loss, [matte_init, laplacian_init]) @parameterized.parameters( ((None, None, None, 1), (None, None, None, 9, 9)), ((None, None, None, 1), (None, None, None, 25, 25)), ((1, 6, 6, 1), (1, 4, 4, 9, 9)), ((1, 10, 10, 1), (1, 6, 6, 25, 25)), ) def test_loss_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(matting.loss, shapes) @parameterized.parameters( ("must have exactly 1 dimensions in axis -1", (1, 6, 6, 2), (1, 4, 4, 9, 9)), ("must have exactly 9 dimensions in axis -2", (1, 6, 6, 1), (1, 4, 4, 1, 9)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (2, 4, 4, 9, 9)), ) def test_loss_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(matting.loss, error_msg, shapes) @parameterized.parameters((3,), (5,)) def test_loss_opposite_images(self, size): """Tests that passing opposite images results in a loss close to 0.0.""" tensor_shape = np.random.randint(size, 6, size=3).tolist() image = np.random.uniform(0.0, 1.0, size=tensor_shape + [1]) laplacian, _ = matting.build_matrices(image, size=size) loss = matting.loss(1.0 - image, laplacian) self.assertAllClose(loss, 0.0, atol=1e-4) @parameterized.parameters((3,), (5,)) def test_loss_same_images(self, size): """Tests that passing same images results in a loss close to 0.0.""" tensor_shape = np.random.randint(size, 6, size=3).tolist() image = np.random.uniform(0.0, 1.0, size=tensor_shape + [1]) laplacian, _ = matting.build_matrices(image, size=size) loss = matting.loss(image, laplacian) self.assertAllClose(loss, 0.0, atol=1e-4) @parameterized.parameters((3,), (5,)) def test_loss_positive(self, size): """Tests that the loss is always greater or equal to 0.0.""" tensor_shape = np.random.randint(size, 6, size=3).tolist() image = tf.random.uniform(minval=0.0, maxval=1.0, shape=tensor_shape + [3]) matte = tf.random.uniform(minval=0.0, maxval=1.0, shape=tensor_shape + [1]) laplacian, _ = matting.build_matrices(image, size=size) loss = matting.loss(matte, laplacian) self.assertAllGreaterEqual(loss, 0.0) @parameterized.parameters((1,), (3,)) def test_reconstruct_jacobian_random(self, channels): """Tests the Jacobian of the reconstruct function.""" tensor_shape = np.random.randint(1, 5, size=3).tolist() image_init = np.random.uniform(0.0, 1.0, size=tensor_shape + [channels]) mul_init = np.random.uniform(0.0, 1.0, size=tensor_shape + [channels]) add_init = np.random.uniform(0.0, 1.0, size=tensor_shape + [1]) self.assert_jacobian_is_correct_fn(matting.reconstruct, [image_init, mul_init, add_init]) @parameterized.parameters( ((None, None, None, 3), (None, None, None, 3), (None, None, None, 1)), ((1, 6, 6, 3), (1, 6, 6, 3), (1, 6, 6, 1)), ) def test_reconstruct_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(matting.reconstruct, shapes) @parameterized.parameters( ("tensor must have a rank of 4, but it has rank", (1, 6, 6), (1, 6, 6, 2), (1, 6, 6, 1)), ("tensor must have a rank of 4, but it has rank", (1, 6, 6, 2), (1, 6, 6), (1, 6, 6, 1)), ("tensor must have a rank of 4, but it has rank", (1, 6, 6, 2), (1, 6, 6, 2), (1, 6, 6)), ("must have exactly 1 dimensions in axis -1", (1, 6, 6, 2), (1, 6, 6, 2), (1, 6, 6, 2)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (1, 6, 6, 4), (1, 6, 6, 1)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (1, 4, 6, 1), (1, 6, 6, 1)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (1, 6, 6, 1), (1, 4, 6, 1)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (1, 6, 4, 1), (1, 6, 6, 1)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (1, 6, 6, 1), (1, 6, 4, 1)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (4, 6, 6, 1), (1, 6, 6, 1)), ("Not all batch dimensions are identical.", (1, 6, 6, 1), (1, 6, 6, 1), (4, 6, 6, 1)), ) def test_reconstruct_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(matting.reconstruct, error_msg, shapes) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/representation/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/transformation/tests/axis_angle_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for axis-angle.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.geometry.transformation.tests import test_helpers from tensorflow_graphics.util import test_case class AxisAngleTest(test_case.TestCase): @parameterized.parameters( ((3,),), ((None, 3),), ) def test_from_euler_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(axis_angle.from_euler, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,)),) def test_from_euler_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(axis_angle.from_euler, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_jacobian_random(self): """Test the Jacobian of the from_euler function. Note: Preset angles are not tested as the gradient of tf.norm is NaN at 0. """ x_init = test_helpers.generate_random_test_euler_angles() self.assert_jacobian_is_finite_fn(lambda x: axis_angle.from_euler(x)[0], [x_init]) self.assert_jacobian_is_finite_fn(lambda x: axis_angle.from_euler(x)[1], [x_init]) def test_from_euler_random(self): """Tests that from_euler allows to perform the expect rotation of points.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() tensor_shape = random_euler_angles.shape[:-1] random_point = np.random.normal(size=tensor_shape + (3,)) random_matrix = rotation_matrix_3d.from_euler(random_euler_angles) random_axis, random_angle = axis_angle.from_euler(random_euler_angles) rotated_with_matrix = rotation_matrix_3d.rotate(random_point, random_matrix) rotated_with_axis_angle = axis_angle.rotate(random_point, random_axis, random_angle) self.assertAllClose(rotated_with_matrix, rotated_with_axis_angle) @parameterized.parameters( ((3,),), ((None, 3),), ((2, 3),), ) def test_from_euler_with_small_angles_approximation_exception_not_raised( self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( axis_angle.from_euler_with_small_angles_approximation, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,)),) def test_from_euler_with_small_angles_approximation_exception_raised( self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised( axis_angle.from_euler_with_small_angles_approximation, error_msg, shapes) def test_from_euler_normalized_preset(self): """Tests that from_euler allows build normalized axis-angles.""" euler_angles = test_helpers.generate_preset_test_euler_angles() axis, angle = axis_angle.from_euler(euler_angles) self.assertAllEqual( axis_angle.is_normalized(axis, angle), np.ones(angle.shape, dtype=bool)) def test_from_euler_normalized_random(self): """Tests that from_euler allows build normalized axis-angles.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_axis, random_angle = axis_angle.from_euler(random_euler_angles) self.assertAllEqual( axis_angle.is_normalized(random_axis, random_angle), np.ones(shape=random_angle.shape)) def test_from_euler_with_small_angles_approximation_random(self): # Only generate small angles. For a test tolerance of 1e-3, 0.23 was found # empirically to be the range where the small angle approximation works. random_euler_angles = test_helpers.generate_random_test_euler_angles( min_angle=-0.23, max_angle=0.23) exact_axis_angle = axis_angle.from_euler(random_euler_angles) approximate_axis_angle = ( axis_angle.from_euler_with_small_angles_approximation( random_euler_angles)) self.assertAllClose(exact_axis_angle, approximate_axis_angle, atol=1e-3) @parameterized.parameters( ((4,),), ((None, 4),), ((2, 4),), ) def test_from_quaternion_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(axis_angle.from_quaternion, shape) @parameterized.parameters( ("must have exactly 4 dimensions in axis -1", (None,)),) def test_from_quaternion_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(axis_angle.from_quaternion, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_quaternion_jacobian_random(self): """Test the Jacobian of the from_quaternion function. Note: Preset angles are not tested as the gradient of tf.norm is NaN a 0. """ x_init = test_helpers.generate_random_test_quaternions() self.assert_jacobian_is_finite_fn( lambda x: axis_angle.from_quaternion(x)[0], [x_init]) self.assert_jacobian_is_finite_fn( lambda x: axis_angle.from_quaternion(x)[1], [x_init]) def test_from_quaternion_normalized_preset(self): """Tests that from_quaternion returns normalized axis-angles.""" euler_angles = test_helpers.generate_preset_test_euler_angles() quat = quaternion.from_euler(euler_angles) axis, angle = axis_angle.from_quaternion(quat) self.assertAllEqual( axis_angle.is_normalized(axis, angle), np.ones(angle.shape, dtype=bool)) def test_from_quaternion_normalized_random(self): """Tests that from_quaternion returns normalized axis-angles.""" random_quaternions = test_helpers.generate_random_test_quaternions() random_axis, random_angle = axis_angle.from_quaternion(random_quaternions) self.assertAllEqual( axis_angle.is_normalized(random_axis, random_angle), np.ones(random_angle.shape)) def test_from_quaternion_preset(self): """Tests that axis_angle.from_quaternion produces the expected result.""" preset_euler_angles = test_helpers.generate_preset_test_euler_angles() preset_quaternions = quaternion.from_euler(preset_euler_angles) preset_axis_angle = axis_angle.from_euler(preset_euler_angles) self.assertAllClose( preset_axis_angle, axis_angle.from_quaternion(preset_quaternions), rtol=1e-3) def test_from_quaternion_random(self): """Tests that axis_angle.from_quaternion produces the expected result.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_quaternions = quaternion.from_euler(random_euler_angles) random_axis_angle = axis_angle.from_euler(random_euler_angles) self.assertAllClose( random_axis_angle, axis_angle.from_quaternion(random_quaternions), rtol=1e-3) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ) def test_from_rotation_matrix_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(axis_angle.from_rotation_matrix, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -1", (3, None)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ) def test_from_rotation_matrix_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(axis_angle.from_rotation_matrix, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_rotation_matrix_jacobian_random(self): """Test the Jacobian of the from_rotation_matrix function. Note: Preset angles are not tested as the gradient of tf.norm is NaN a 0. """ x_init = test_helpers.generate_random_test_rotation_matrix_3d() self.assert_jacobian_is_finite_fn( lambda x: axis_angle.from_rotation_matrix(x)[0], [x_init]) self.assert_jacobian_is_finite_fn( lambda x: axis_angle.from_rotation_matrix(x)[1], [x_init]) def test_from_rotation_matrix_normalized_preset(self): """Tests that from_rotation_matrix returns normalized axis-angles.""" preset_euler_angles = test_helpers.generate_preset_test_euler_angles() matrix = rotation_matrix_3d.from_euler(preset_euler_angles) axis, angle = axis_angle.from_rotation_matrix(matrix) self.assertAllEqual( axis_angle.is_normalized(axis, angle), np.ones(angle.shape, dtype=bool)) def test_from_rotation_matrix_normalized_random(self): """Tests that from_rotation_matrix returns normalized axis-angles.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() matrix = rotation_matrix_3d.from_euler(random_euler_angles) axis, angle = axis_angle.from_rotation_matrix(matrix) self.assertAllEqual( axis_angle.is_normalized(axis, angle), np.ones(angle.shape, dtype=bool)) def test_from_rotation_matrix_random(self): """Tests rotation around Z axis.""" def get_rotation_matrix_around_z(angle_rad): return np.array([ [np.cos(angle_rad), -np.sin(angle_rad), 0], [np.sin(angle_rad), np.cos(angle_rad), 0], [0, 0, 1], ]) tensor_size = np.random.randint(10) angle = ( np.array([ np.deg2rad(np.random.randint(720) - 360) for _ in range(tensor_size) ]).reshape((tensor_size, 1))) rotation_matrix = [get_rotation_matrix_around_z(i[0]) for i in angle] rotation_matrix = np.array(rotation_matrix).reshape((tensor_size, 3, 3)) tf_axis, tf_angle = axis_angle.from_rotation_matrix(rotation_matrix) axis = np.tile([[0., 0., 1.]], (angle.shape[0], 1)) tf_quat_gt = quaternion.from_axis_angle(axis, angle) tf_quat = quaternion.from_axis_angle(tf_axis, tf_angle) # Compare quaternions since axis orientation and angle ambiguity will # lead to more complex comparisons. for quat_gt, quat in zip(self.evaluate(tf_quat_gt), self.evaluate(tf_quat)): # Remember that q=-q for any quaternion. pos = np.allclose(quat_gt, quat) neg = np.allclose(quat_gt, -quat) self.assertTrue(pos or neg) @parameterized.parameters( ((3,), (1,)), ((None, 3), (None, 1)), ((2, 3), (2, 1)), ((1, 3), (1,)), ((3,), (1, 1)), ) def test_inverse_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(axis_angle.inverse, shape) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,), (1,)), ("must have exactly 1 dimensions in axis -1", (3,), (None,)), ) def test_inverse_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(axis_angle.inverse, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_preset(self): """Test the Jacobian of the inverse function.""" x_axis_init, x_angle_init = test_helpers.generate_preset_test_axis_angle() if tf.executing_eagerly(): # Because axis is returned as is, gradient calculation fails in graph mode # but not in eager mode. This is a side effect of having a graph rather # than a problem of the function. with self.subTest("axis"): self.assert_jacobian_is_correct_fn( lambda x: axis_angle.inverse(x, x_angle_init)[0], [x_axis_init]) with self.subTest("angle"): self.assert_jacobian_is_correct_fn( lambda x: axis_angle.inverse(x_axis_init, x)[1], [x_angle_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_random(self): """Test the Jacobian of the inverse function.""" x_axis_init, x_angle_init = test_helpers.generate_random_test_axis_angle() if tf.executing_eagerly(): # Because axis is returned as is, gradient calculation fails in graph mode # but not in eager mode. This is a side effect of having a graph rather # than a problem of the function. with self.subTest("axis"): self.assert_jacobian_is_correct_fn( lambda x: axis_angle.inverse(1.0 * x, x_angle_init)[0], [x_axis_init]) with self.subTest("angle"): self.assert_jacobian_is_correct_fn( lambda x: axis_angle.inverse(x_axis_init, x)[1], [x_angle_init]) def test_inverse_normalized_random(self): """Tests that axis-angle inversion return a normalized axis-angle.""" random_axis, random_angle = test_helpers.generate_random_test_axis_angle() inverse_axis, inverse_angle = axis_angle.inverse(random_axis, random_angle) self.assertAllEqual( axis_angle.is_normalized(inverse_axis, inverse_angle), np.ones(random_angle.shape)) def test_inverse_random(self): """Tests axis-angle inversion.""" random_axis, random_angle = test_helpers.generate_random_test_axis_angle() inverse_axis, inverse_angle = axis_angle.inverse(random_axis, random_angle) self.assertAllClose(inverse_axis, random_axis, rtol=1e-3) self.assertAllClose(inverse_angle, -random_angle, rtol=1e-3) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,), (1,)), ("must have exactly 1 dimensions in axis -1", (3,), (None,)), ) def test_is_normalized_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(axis_angle.is_normalized, error_msg, shape) def test_is_normalized_random(self): """Tests that is_normalized works as intended.""" # Samples normalized axis-angles. random_euler_angles = test_helpers.generate_random_test_euler_angles() with self.subTest(name=("is_normalized")): random_axis, random_angle = axis_angle.from_euler(random_euler_angles) pred = axis_angle.is_normalized(random_axis, random_angle) self.assertAllEqual(np.ones(shape=random_angle.shape, dtype=bool), pred) with self.subTest(name=("is_not_normalized")): random_axis *= 1.01 pred = axis_angle.is_normalized(random_axis, random_angle) self.assertAllEqual(np.zeros(shape=random_angle.shape, dtype=bool), pred) @parameterized.parameters( ((3,), (3,), (1,)), ((None, 3), (None, 3), (None, 1)), ((2, 3), (2, 3), (2, 1)), ((3,), (1, 3), (1, 2, 1)), ((1, 2, 3), (1, 3), (1,)), ((3,), (1, 3), (1,)), ) def test_rotate_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(axis_angle.rotate, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (2,), (3,), (1,)), ("must have exactly 3 dimensions in axis -1", (3,), (2,), (1,)), ("must have exactly 1 dimensions in axis -1", (3,), (3,), (2,)), ) def test_rotate_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(axis_angle.rotate, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_preset(self): """Test the Jacobian of the rotate function.""" x_axis_init, x_angle_init = test_helpers.generate_preset_test_axis_angle() x_point_init = np.random.uniform(size=x_axis_init.shape) self.assert_jacobian_is_correct_fn( axis_angle.rotate, [x_point_init, x_axis_init, x_angle_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_random(self): """Test the Jacobian of the rotate function.""" x_axis_init, x_angle_init = test_helpers.generate_random_test_axis_angle() x_point_init = np.random.uniform(size=x_axis_init.shape) self.assert_jacobian_is_correct_fn( axis_angle.rotate, [x_point_init, x_axis_init, x_angle_init]) def test_rotate_random(self): """Tests that the rotate provide the same results as quaternion.rotate.""" random_axis, random_angle = test_helpers.generate_random_test_axis_angle() tensor_shape = random_angle.shape[:-1] random_point = np.random.normal(size=tensor_shape + (3,)) random_quaternion = quaternion.from_axis_angle(random_axis, random_angle) ground_truth = quaternion.rotate(random_point, random_quaternion) prediction = axis_angle.rotate(random_point, random_axis, random_angle) self.assertAllClose(ground_truth, prediction, rtol=1e-6) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for axis-angle.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.geometry.transformation.tests import test_helpers from tensorflow_graphics.util import test_case class AxisAngleTest(test_case.TestCase): @parameterized.parameters( ((3,),), ((None, 3),), ) def test_from_euler_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(axis_angle.from_euler, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,)),) def test_from_euler_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(axis_angle.from_euler, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_jacobian_random(self): """Test the Jacobian of the from_euler function. Note: Preset angles are not tested as the gradient of tf.norm is NaN at 0. """ x_init = test_helpers.generate_random_test_euler_angles() self.assert_jacobian_is_finite_fn(lambda x: axis_angle.from_euler(x)[0], [x_init]) self.assert_jacobian_is_finite_fn(lambda x: axis_angle.from_euler(x)[1], [x_init]) def test_from_euler_random(self): """Tests that from_euler allows to perform the expect rotation of points.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() tensor_shape = random_euler_angles.shape[:-1] random_point = np.random.normal(size=tensor_shape + (3,)) random_matrix = rotation_matrix_3d.from_euler(random_euler_angles) random_axis, random_angle = axis_angle.from_euler(random_euler_angles) rotated_with_matrix = rotation_matrix_3d.rotate(random_point, random_matrix) rotated_with_axis_angle = axis_angle.rotate(random_point, random_axis, random_angle) self.assertAllClose(rotated_with_matrix, rotated_with_axis_angle) @parameterized.parameters( ((3,),), ((None, 3),), ((2, 3),), ) def test_from_euler_with_small_angles_approximation_exception_not_raised( self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( axis_angle.from_euler_with_small_angles_approximation, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,)),) def test_from_euler_with_small_angles_approximation_exception_raised( self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised( axis_angle.from_euler_with_small_angles_approximation, error_msg, shapes) def test_from_euler_normalized_preset(self): """Tests that from_euler allows build normalized axis-angles.""" euler_angles = test_helpers.generate_preset_test_euler_angles() axis, angle = axis_angle.from_euler(euler_angles) self.assertAllEqual( axis_angle.is_normalized(axis, angle), np.ones(angle.shape, dtype=bool)) def test_from_euler_normalized_random(self): """Tests that from_euler allows build normalized axis-angles.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_axis, random_angle = axis_angle.from_euler(random_euler_angles) self.assertAllEqual( axis_angle.is_normalized(random_axis, random_angle), np.ones(shape=random_angle.shape)) def test_from_euler_with_small_angles_approximation_random(self): # Only generate small angles. For a test tolerance of 1e-3, 0.23 was found # empirically to be the range where the small angle approximation works. random_euler_angles = test_helpers.generate_random_test_euler_angles( min_angle=-0.23, max_angle=0.23) exact_axis_angle = axis_angle.from_euler(random_euler_angles) approximate_axis_angle = ( axis_angle.from_euler_with_small_angles_approximation( random_euler_angles)) self.assertAllClose(exact_axis_angle, approximate_axis_angle, atol=1e-3) @parameterized.parameters( ((4,),), ((None, 4),), ((2, 4),), ) def test_from_quaternion_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(axis_angle.from_quaternion, shape) @parameterized.parameters( ("must have exactly 4 dimensions in axis -1", (None,)),) def test_from_quaternion_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(axis_angle.from_quaternion, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_quaternion_jacobian_random(self): """Test the Jacobian of the from_quaternion function. Note: Preset angles are not tested as the gradient of tf.norm is NaN a 0. """ x_init = test_helpers.generate_random_test_quaternions() self.assert_jacobian_is_finite_fn( lambda x: axis_angle.from_quaternion(x)[0], [x_init]) self.assert_jacobian_is_finite_fn( lambda x: axis_angle.from_quaternion(x)[1], [x_init]) def test_from_quaternion_normalized_preset(self): """Tests that from_quaternion returns normalized axis-angles.""" euler_angles = test_helpers.generate_preset_test_euler_angles() quat = quaternion.from_euler(euler_angles) axis, angle = axis_angle.from_quaternion(quat) self.assertAllEqual( axis_angle.is_normalized(axis, angle), np.ones(angle.shape, dtype=bool)) def test_from_quaternion_normalized_random(self): """Tests that from_quaternion returns normalized axis-angles.""" random_quaternions = test_helpers.generate_random_test_quaternions() random_axis, random_angle = axis_angle.from_quaternion(random_quaternions) self.assertAllEqual( axis_angle.is_normalized(random_axis, random_angle), np.ones(random_angle.shape)) def test_from_quaternion_preset(self): """Tests that axis_angle.from_quaternion produces the expected result.""" preset_euler_angles = test_helpers.generate_preset_test_euler_angles() preset_quaternions = quaternion.from_euler(preset_euler_angles) preset_axis_angle = axis_angle.from_euler(preset_euler_angles) self.assertAllClose( preset_axis_angle, axis_angle.from_quaternion(preset_quaternions), rtol=1e-3) def test_from_quaternion_random(self): """Tests that axis_angle.from_quaternion produces the expected result.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_quaternions = quaternion.from_euler(random_euler_angles) random_axis_angle = axis_angle.from_euler(random_euler_angles) self.assertAllClose( random_axis_angle, axis_angle.from_quaternion(random_quaternions), rtol=1e-3) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ) def test_from_rotation_matrix_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(axis_angle.from_rotation_matrix, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -1", (3, None)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ) def test_from_rotation_matrix_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(axis_angle.from_rotation_matrix, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_rotation_matrix_jacobian_random(self): """Test the Jacobian of the from_rotation_matrix function. Note: Preset angles are not tested as the gradient of tf.norm is NaN a 0. """ x_init = test_helpers.generate_random_test_rotation_matrix_3d() self.assert_jacobian_is_finite_fn( lambda x: axis_angle.from_rotation_matrix(x)[0], [x_init]) self.assert_jacobian_is_finite_fn( lambda x: axis_angle.from_rotation_matrix(x)[1], [x_init]) def test_from_rotation_matrix_normalized_preset(self): """Tests that from_rotation_matrix returns normalized axis-angles.""" preset_euler_angles = test_helpers.generate_preset_test_euler_angles() matrix = rotation_matrix_3d.from_euler(preset_euler_angles) axis, angle = axis_angle.from_rotation_matrix(matrix) self.assertAllEqual( axis_angle.is_normalized(axis, angle), np.ones(angle.shape, dtype=bool)) def test_from_rotation_matrix_normalized_random(self): """Tests that from_rotation_matrix returns normalized axis-angles.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() matrix = rotation_matrix_3d.from_euler(random_euler_angles) axis, angle = axis_angle.from_rotation_matrix(matrix) self.assertAllEqual( axis_angle.is_normalized(axis, angle), np.ones(angle.shape, dtype=bool)) def test_from_rotation_matrix_random(self): """Tests rotation around Z axis.""" def get_rotation_matrix_around_z(angle_rad): return np.array([ [np.cos(angle_rad), -np.sin(angle_rad), 0], [np.sin(angle_rad), np.cos(angle_rad), 0], [0, 0, 1], ]) tensor_size = np.random.randint(10) angle = ( np.array([ np.deg2rad(np.random.randint(720) - 360) for _ in range(tensor_size) ]).reshape((tensor_size, 1))) rotation_matrix = [get_rotation_matrix_around_z(i[0]) for i in angle] rotation_matrix = np.array(rotation_matrix).reshape((tensor_size, 3, 3)) tf_axis, tf_angle = axis_angle.from_rotation_matrix(rotation_matrix) axis = np.tile([[0., 0., 1.]], (angle.shape[0], 1)) tf_quat_gt = quaternion.from_axis_angle(axis, angle) tf_quat = quaternion.from_axis_angle(tf_axis, tf_angle) # Compare quaternions since axis orientation and angle ambiguity will # lead to more complex comparisons. for quat_gt, quat in zip(self.evaluate(tf_quat_gt), self.evaluate(tf_quat)): # Remember that q=-q for any quaternion. pos = np.allclose(quat_gt, quat) neg = np.allclose(quat_gt, -quat) self.assertTrue(pos or neg) @parameterized.parameters( ((3,), (1,)), ((None, 3), (None, 1)), ((2, 3), (2, 1)), ((1, 3), (1,)), ((3,), (1, 1)), ) def test_inverse_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(axis_angle.inverse, shape) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,), (1,)), ("must have exactly 1 dimensions in axis -1", (3,), (None,)), ) def test_inverse_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(axis_angle.inverse, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_preset(self): """Test the Jacobian of the inverse function.""" x_axis_init, x_angle_init = test_helpers.generate_preset_test_axis_angle() if tf.executing_eagerly(): # Because axis is returned as is, gradient calculation fails in graph mode # but not in eager mode. This is a side effect of having a graph rather # than a problem of the function. with self.subTest("axis"): self.assert_jacobian_is_correct_fn( lambda x: axis_angle.inverse(x, x_angle_init)[0], [x_axis_init]) with self.subTest("angle"): self.assert_jacobian_is_correct_fn( lambda x: axis_angle.inverse(x_axis_init, x)[1], [x_angle_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_random(self): """Test the Jacobian of the inverse function.""" x_axis_init, x_angle_init = test_helpers.generate_random_test_axis_angle() if tf.executing_eagerly(): # Because axis is returned as is, gradient calculation fails in graph mode # but not in eager mode. This is a side effect of having a graph rather # than a problem of the function. with self.subTest("axis"): self.assert_jacobian_is_correct_fn( lambda x: axis_angle.inverse(1.0 * x, x_angle_init)[0], [x_axis_init]) with self.subTest("angle"): self.assert_jacobian_is_correct_fn( lambda x: axis_angle.inverse(x_axis_init, x)[1], [x_angle_init]) def test_inverse_normalized_random(self): """Tests that axis-angle inversion return a normalized axis-angle.""" random_axis, random_angle = test_helpers.generate_random_test_axis_angle() inverse_axis, inverse_angle = axis_angle.inverse(random_axis, random_angle) self.assertAllEqual( axis_angle.is_normalized(inverse_axis, inverse_angle), np.ones(random_angle.shape)) def test_inverse_random(self): """Tests axis-angle inversion.""" random_axis, random_angle = test_helpers.generate_random_test_axis_angle() inverse_axis, inverse_angle = axis_angle.inverse(random_axis, random_angle) self.assertAllClose(inverse_axis, random_axis, rtol=1e-3) self.assertAllClose(inverse_angle, -random_angle, rtol=1e-3) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,), (1,)), ("must have exactly 1 dimensions in axis -1", (3,), (None,)), ) def test_is_normalized_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(axis_angle.is_normalized, error_msg, shape) def test_is_normalized_random(self): """Tests that is_normalized works as intended.""" # Samples normalized axis-angles. random_euler_angles = test_helpers.generate_random_test_euler_angles() with self.subTest(name=("is_normalized")): random_axis, random_angle = axis_angle.from_euler(random_euler_angles) pred = axis_angle.is_normalized(random_axis, random_angle) self.assertAllEqual(np.ones(shape=random_angle.shape, dtype=bool), pred) with self.subTest(name=("is_not_normalized")): random_axis *= 1.01 pred = axis_angle.is_normalized(random_axis, random_angle) self.assertAllEqual(np.zeros(shape=random_angle.shape, dtype=bool), pred) @parameterized.parameters( ((3,), (3,), (1,)), ((None, 3), (None, 3), (None, 1)), ((2, 3), (2, 3), (2, 1)), ((3,), (1, 3), (1, 2, 1)), ((1, 2, 3), (1, 3), (1,)), ((3,), (1, 3), (1,)), ) def test_rotate_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(axis_angle.rotate, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (2,), (3,), (1,)), ("must have exactly 3 dimensions in axis -1", (3,), (2,), (1,)), ("must have exactly 1 dimensions in axis -1", (3,), (3,), (2,)), ) def test_rotate_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(axis_angle.rotate, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_preset(self): """Test the Jacobian of the rotate function.""" x_axis_init, x_angle_init = test_helpers.generate_preset_test_axis_angle() x_point_init = np.random.uniform(size=x_axis_init.shape) self.assert_jacobian_is_correct_fn( axis_angle.rotate, [x_point_init, x_axis_init, x_angle_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_random(self): """Test the Jacobian of the rotate function.""" x_axis_init, x_angle_init = test_helpers.generate_random_test_axis_angle() x_point_init = np.random.uniform(size=x_axis_init.shape) self.assert_jacobian_is_correct_fn( axis_angle.rotate, [x_point_init, x_axis_init, x_angle_init]) def test_rotate_random(self): """Tests that the rotate provide the same results as quaternion.rotate.""" random_axis, random_angle = test_helpers.generate_random_test_axis_angle() tensor_shape = random_angle.shape[:-1] random_point = np.random.normal(size=tensor_shape + (3,)) random_quaternion = quaternion.from_axis_angle(random_axis, random_angle) ground_truth = quaternion.rotate(random_point, random_quaternion) prediction = axis_angle.rotate(random_point, random_axis, random_angle) self.assertAllClose(ground_truth, prediction, rtol=1e-6) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/nn/metric/precision.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the precision metric.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def _cast_to_int(prediction): return tf.cast(x=prediction, dtype=tf.int32) def evaluate(ground_truth, prediction, classes=None, reduce_average=True, prediction_to_category_function=_cast_to_int, name=None): """Computes the precision metric for the given ground truth and predictions. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: ground_truth: A tensor of shape `[A1, ..., An, N]`, where the last axis represents the ground truth labels. Will be cast to int32. prediction: A tensor of shape `[A1, ..., An, N]`, where the last axis represents the predictions (which can be continuous). classes: An integer or a list/tuple of integers representing the classes for which the precision will be evaluated. In case 'classes' is 'None', the number of classes will be inferred from the given labels and the precision will be calculated for each of the classes. Defaults to 'None'. reduce_average: Whether to calculate the average of the precision for each class and return a single precision value. Defaults to true. prediction_to_category_function: A function to associate a `prediction` to a category. Defaults to rounding down the value of the prediction to the nearest integer value. name: A name for this op. Defaults to "precision_evaluate". Returns: A tensor of shape `[A1, ..., An, C]`, where the last axis represents the precision calculated for each of the requested classes. Raises: ValueError: if the shape of `ground_truth`, `prediction` is not supported. """ with tf.compat.v1.name_scope(name, "precision_evaluate", [ground_truth, prediction]): ground_truth = tf.cast( x=tf.convert_to_tensor(value=ground_truth), dtype=tf.int32) prediction = tf.convert_to_tensor(value=prediction) shape.compare_batch_dimensions( tensors=(ground_truth, prediction), tensor_names=("ground_truth", "prediction"), last_axes=-1, broadcast_compatible=True) prediction = prediction_to_category_function(prediction) if classes is None: num_classes = tf.math.maximum( tf.math.reduce_max(input_tensor=ground_truth), tf.math.reduce_max(input_tensor=prediction)) + 1 classes = tf.range(num_classes) else: classes = tf.convert_to_tensor(value=classes) # Make sure classes is a tensor of rank 1. classes = tf.reshape(classes, [1]) if tf.rank(classes) == 0 else classes # Create a confusion matrix for each of the classes (with dimensions # [A1, ..., An, C, N]). classes = tf.expand_dims(classes, -1) ground_truth_per_class = tf.equal(tf.expand_dims(ground_truth, -2), classes) prediction_per_class = tf.equal(tf.expand_dims(prediction, -2), classes) # Calculate the precision for each of the classes. true_positives = tf.math.reduce_sum( input_tensor=tf.cast( x=tf.math.logical_and(ground_truth_per_class, prediction_per_class), dtype=tf.float32), axis=-1) total_predicted_positives = tf.math.reduce_sum( input_tensor=tf.cast(x=prediction_per_class, dtype=tf.float32), axis=-1) precision_per_class = safe_ops.safe_signed_div(true_positives, total_predicted_positives) if reduce_average: return tf.math.reduce_mean(input_tensor=precision_per_class, axis=-1) else: return precision_per_class # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the precision metric.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def _cast_to_int(prediction): return tf.cast(x=prediction, dtype=tf.int32) def evaluate(ground_truth, prediction, classes=None, reduce_average=True, prediction_to_category_function=_cast_to_int, name=None): """Computes the precision metric for the given ground truth and predictions. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: ground_truth: A tensor of shape `[A1, ..., An, N]`, where the last axis represents the ground truth labels. Will be cast to int32. prediction: A tensor of shape `[A1, ..., An, N]`, where the last axis represents the predictions (which can be continuous). classes: An integer or a list/tuple of integers representing the classes for which the precision will be evaluated. In case 'classes' is 'None', the number of classes will be inferred from the given labels and the precision will be calculated for each of the classes. Defaults to 'None'. reduce_average: Whether to calculate the average of the precision for each class and return a single precision value. Defaults to true. prediction_to_category_function: A function to associate a `prediction` to a category. Defaults to rounding down the value of the prediction to the nearest integer value. name: A name for this op. Defaults to "precision_evaluate". Returns: A tensor of shape `[A1, ..., An, C]`, where the last axis represents the precision calculated for each of the requested classes. Raises: ValueError: if the shape of `ground_truth`, `prediction` is not supported. """ with tf.compat.v1.name_scope(name, "precision_evaluate", [ground_truth, prediction]): ground_truth = tf.cast( x=tf.convert_to_tensor(value=ground_truth), dtype=tf.int32) prediction = tf.convert_to_tensor(value=prediction) shape.compare_batch_dimensions( tensors=(ground_truth, prediction), tensor_names=("ground_truth", "prediction"), last_axes=-1, broadcast_compatible=True) prediction = prediction_to_category_function(prediction) if classes is None: num_classes = tf.math.maximum( tf.math.reduce_max(input_tensor=ground_truth), tf.math.reduce_max(input_tensor=prediction)) + 1 classes = tf.range(num_classes) else: classes = tf.convert_to_tensor(value=classes) # Make sure classes is a tensor of rank 1. classes = tf.reshape(classes, [1]) if tf.rank(classes) == 0 else classes # Create a confusion matrix for each of the classes (with dimensions # [A1, ..., An, C, N]). classes = tf.expand_dims(classes, -1) ground_truth_per_class = tf.equal(tf.expand_dims(ground_truth, -2), classes) prediction_per_class = tf.equal(tf.expand_dims(prediction, -2), classes) # Calculate the precision for each of the classes. true_positives = tf.math.reduce_sum( input_tensor=tf.cast( x=tf.math.logical_and(ground_truth_per_class, prediction_per_class), dtype=tf.float32), axis=-1) total_predicted_positives = tf.math.reduce_sum( input_tensor=tf.cast(x=prediction_per_class, dtype=tf.float32), axis=-1) precision_per_class = safe_ops.safe_signed_div(true_positives, total_predicted_positives) if reduce_average: return tf.math.reduce_mean(input_tensor=precision_per_class, axis=-1) else: return precision_per_class # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/projects/cvxnet/README.md
# CvxNet: Differentiable Convex Decomposition (CVPR 2020) \[[Project Page](http://cvxnet.github.io)\] \[[Video](https://www.youtube.com/watch?v=Rgi63tT670w)\] \[[Paper](https://arxiv.org/abs/1909.05736)\] <div align="center"> <img width="95%" alt="CvxNet Illustration" src="http://services.google.com/fh/files/misc/cropped_teaser.gif"> </div> This project provides the open source implementation with pretrained models used for experiments in the paper. Our work proposes a differentiable way of representating any shape as the union of convex polytopes. CvxNet can be trained on large-scale shape collections as an implicit representation while used as an explicit representation during inference time. Please refer to our paper for more details. ## Installation We highly recommend using [conda enviroment](https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html) or [virtualenv](https://virtualenv.pypa.io/en/latest/) to run this project. The code is tested on python 3.7.6 and we recommend using python 3.7+ and install all the dependencies by: ```bash git clone https://github.com/tensorflow/graphics.git cd graphics/tensorflow_graphics/projects/cvxnet pip install -r requirements.txt ``` Meanwhile, make sure the path to the root directory of tensorflow_graphics is in your `PYTHONPATH`. If not, please: ```bash export PYTHONPATH="/PATH/TO/TENSORFLOW_GRAPHICS:$PYTHONPATH" ``` For efficiently extracting smooth mesh surfaces from indicator functions, we also adapt a tool `libmise` from [Occupancy Networks](https://github.com/autonomousvision/occupancy_networks). If you use this tool, please consider citing [their paper](https://avg.is.tuebingen.mpg.de/publications/occupancy-networks) as well. To install this extension module written in cython, assuming that we are still at `graphics/tensorflow_graphics/projects/cvxnet`, run: ```bash python ./setup.py build_ext --inplace ``` ## Prepare the dataset The model is trained on [ShapeNet](https://www.shapenet.org/). In our experiments, we use point samples with occupancy labels based on meshes from this dataset. We also use color renders from [3D-R2N2](https://github.com/chrischoy/3D-R2N2). In this project, we provide a small sample dataset which you can use to train and evaluate the model directly. If you want to use the whole dataset (which might be huge), please visit their websites ([ShapeNet](https://www.shapenet.org/) and [3D-R2N2](https://github.com/chrischoy/3D-R2N2)) and download the original data. We will soon release our point samples, depth renders, and the script to assembling raw data. To prepare the sample dataset, run: ```bash wget cvxnet.github.io/data/sample_dataset.zip unzip sample_dataset.zip -d /tmp/cvxnet rm sample_dataset.zip ``` and the sample dataset will reside in `/tmp/cvxnet/sample_dataset`. ## Training To start the training, make sure you have the dataset ready following the above step and run: ```bash python train.py --train_dir=/tmp/cvxnet/models/rgb --data_dir=/tmp/cvxnet/sample_dataset --image_input ``` The training record will be saved in `/tmp/cvxnet` so we can launch a tensorboard by `tensorboard --logdir /tmp/cvxnet` to monitor the training. Also note that this launches the RGB-to-3D experiment with the same parameters in the paper. If you want to launch the {Depth}-to-3D experiment, use: ```bash python train.py --train_dir=/tmp/cvxnet/models/depth --data_dir=/tmp/cvxnet/sample_dataset --n_half_planes=50 ``` ## Evaluation First, let's assume that our model for RGB-to-3D is saved in `/tmp/cvxnet/models/rgb` and the model for {Depth}-to-3D is saved in `/tmp/cvxnet/models/depth`. We can launch the evaluation job for the RGB-to-3D model by: ```bash python eval.py --train_dir=/tmp/cvxnet/models/rgb --data_dir=/tmp/cvxnet/sample_dataset--image_input ``` This will write the IoU (Intersection of Union) on the test set to tensorboard. Similarly, {Depth}-to-3D model can be evaluated by: ```bash python eval.py --train_dir=/tmp/cvxnet/models/depth --data_dir=/tmp/cvxnet/sample_dataset --n_half_planes=50 ``` We will soon release our pretrained models for RGB-to-3D and {Depth}-to-3D tasks. If you want to extract meshes as well, please also set `--extract_mesh` which will automatically save meshes to the `train_dir`. Note that we use a transformed version of ShapeNet for our point sampling so for full shapenet evaluation you need to download the transformations which we will release soon. ## Reference If you find this work useful, please consider citing: ``` @article{deng2020cvxnet, title = {CvxNet: Learnable Convex Decomposition}, author = {Deng, Boyang and Genova, Kyle and Yazdani, Soroosh and Bouaziz, Sofien and Hinton, Geoffrey and Tagliasacchi, Andrea}, booktitle = {The IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, month = {June}, year = {2020} } ```
# CvxNet: Differentiable Convex Decomposition (CVPR 2020) \[[Project Page](http://cvxnet.github.io)\] \[[Video](https://www.youtube.com/watch?v=Rgi63tT670w)\] \[[Paper](https://arxiv.org/abs/1909.05736)\] <div align="center"> <img width="95%" alt="CvxNet Illustration" src="http://services.google.com/fh/files/misc/cropped_teaser.gif"> </div> This project provides the open source implementation with pretrained models used for experiments in the paper. Our work proposes a differentiable way of representating any shape as the union of convex polytopes. CvxNet can be trained on large-scale shape collections as an implicit representation while used as an explicit representation during inference time. Please refer to our paper for more details. ## Installation We highly recommend using [conda enviroment](https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html) or [virtualenv](https://virtualenv.pypa.io/en/latest/) to run this project. The code is tested on python 3.7.6 and we recommend using python 3.7+ and install all the dependencies by: ```bash git clone https://github.com/tensorflow/graphics.git cd graphics/tensorflow_graphics/projects/cvxnet pip install -r requirements.txt ``` Meanwhile, make sure the path to the root directory of tensorflow_graphics is in your `PYTHONPATH`. If not, please: ```bash export PYTHONPATH="/PATH/TO/TENSORFLOW_GRAPHICS:$PYTHONPATH" ``` For efficiently extracting smooth mesh surfaces from indicator functions, we also adapt a tool `libmise` from [Occupancy Networks](https://github.com/autonomousvision/occupancy_networks). If you use this tool, please consider citing [their paper](https://avg.is.tuebingen.mpg.de/publications/occupancy-networks) as well. To install this extension module written in cython, assuming that we are still at `graphics/tensorflow_graphics/projects/cvxnet`, run: ```bash python ./setup.py build_ext --inplace ``` ## Prepare the dataset The model is trained on [ShapeNet](https://www.shapenet.org/). In our experiments, we use point samples with occupancy labels based on meshes from this dataset. We also use color renders from [3D-R2N2](https://github.com/chrischoy/3D-R2N2). In this project, we provide a small sample dataset which you can use to train and evaluate the model directly. If you want to use the whole dataset (which might be huge), please visit their websites ([ShapeNet](https://www.shapenet.org/) and [3D-R2N2](https://github.com/chrischoy/3D-R2N2)) and download the original data. We will soon release our point samples, depth renders, and the script to assembling raw data. To prepare the sample dataset, run: ```bash wget cvxnet.github.io/data/sample_dataset.zip unzip sample_dataset.zip -d /tmp/cvxnet rm sample_dataset.zip ``` and the sample dataset will reside in `/tmp/cvxnet/sample_dataset`. ## Training To start the training, make sure you have the dataset ready following the above step and run: ```bash python train.py --train_dir=/tmp/cvxnet/models/rgb --data_dir=/tmp/cvxnet/sample_dataset --image_input ``` The training record will be saved in `/tmp/cvxnet` so we can launch a tensorboard by `tensorboard --logdir /tmp/cvxnet` to monitor the training. Also note that this launches the RGB-to-3D experiment with the same parameters in the paper. If you want to launch the {Depth}-to-3D experiment, use: ```bash python train.py --train_dir=/tmp/cvxnet/models/depth --data_dir=/tmp/cvxnet/sample_dataset --n_half_planes=50 ``` ## Evaluation First, let's assume that our model for RGB-to-3D is saved in `/tmp/cvxnet/models/rgb` and the model for {Depth}-to-3D is saved in `/tmp/cvxnet/models/depth`. We can launch the evaluation job for the RGB-to-3D model by: ```bash python eval.py --train_dir=/tmp/cvxnet/models/rgb --data_dir=/tmp/cvxnet/sample_dataset--image_input ``` This will write the IoU (Intersection of Union) on the test set to tensorboard. Similarly, {Depth}-to-3D model can be evaluated by: ```bash python eval.py --train_dir=/tmp/cvxnet/models/depth --data_dir=/tmp/cvxnet/sample_dataset --n_half_planes=50 ``` We will soon release our pretrained models for RGB-to-3D and {Depth}-to-3D tasks. If you want to extract meshes as well, please also set `--extract_mesh` which will automatically save meshes to the `train_dir`. Note that we use a transformed version of ShapeNet for our point sampling so for full shapenet evaluation you need to download the transformations which we will release soon. ## Reference If you find this work useful, please consider citing: ``` @article{deng2020cvxnet, title = {CvxNet: Learnable Convex Decomposition}, author = {Deng, Boyang and Genova, Kyle and Yazdani, Soroosh and Bouaziz, Sofien and Hinton, Geoffrey and Tagliasacchi, Andrea}, booktitle = {The IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, month = {June}, year = {2020} } ```
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/notebooks/mesh_viewer.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper class for viewing 3D meshes in Colab demos. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow_graphics.notebooks import threejs_visualization SEGMENTATION_COLORMAP = np.array( ((165, 242, 12), (89, 12, 89), (165, 89, 165), (242, 242, 165), (242, 165, 12), (89, 12, 12), (165, 12, 12), (165, 89, 242), (12, 12, 165), (165, 12, 89), (12, 89, 89), (165, 165, 89), (89, 242, 12), (12, 89, 165), (242, 242, 89), (165, 165, 165)), dtype=np.float32) / 255.0 class Viewer(object): """A ThreeJS based viewer class for viewing 3D meshes.""" def _mesh_from_data(self, data): """Creates a dictionary of ThreeJS mesh objects from numpy data.""" if 'vertices' not in data or 'faces' not in data: raise ValueError('Mesh Data must contain vertices and faces') vertices = np.asarray(data['vertices']) faces = np.asarray(data['faces']) material = self.context.THREE.MeshLambertMaterial.new_object({ 'color': 0xfffacd, 'vertexColors': self.context.THREE.NoColors, 'side': self.context.THREE.DoubleSide, }) mesh = {'vertices': vertices, 'faces': faces} if 'vertex_colors' in data: mesh['vertex_colors'] = np.asarray(data['vertex_colors']) material = self.context.THREE.MeshLambertMaterial.new_object({ 'color': 0xfffacd, 'vertexColors': self.context.THREE.VertexColors, 'side': self.context.THREE.DoubleSide, }) mesh['material'] = material return mesh def __init__(self, source_mesh_data): context = threejs_visualization.build_context() self.context = context light1 = context.THREE.PointLight.new_object(0x808080) light1.position.set(10., 10., 10.) light2 = context.THREE.AmbientLight.new_object(0x808080) lights = (light1, light2) camera = threejs_visualization.build_perspective_camera( field_of_view=30, position=(0.0, 0.0, 4.0)) mesh = self._mesh_from_data(source_mesh_data) geometries = threejs_visualization.triangular_mesh_renderer([mesh], lights=lights, camera=camera, width=400, height=400) self.geometries = geometries
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper class for viewing 3D meshes in Colab demos. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow_graphics.notebooks import threejs_visualization SEGMENTATION_COLORMAP = np.array( ((165, 242, 12), (89, 12, 89), (165, 89, 165), (242, 242, 165), (242, 165, 12), (89, 12, 12), (165, 12, 12), (165, 89, 242), (12, 12, 165), (165, 12, 89), (12, 89, 89), (165, 165, 89), (89, 242, 12), (12, 89, 165), (242, 242, 89), (165, 165, 165)), dtype=np.float32) / 255.0 class Viewer(object): """A ThreeJS based viewer class for viewing 3D meshes.""" def _mesh_from_data(self, data): """Creates a dictionary of ThreeJS mesh objects from numpy data.""" if 'vertices' not in data or 'faces' not in data: raise ValueError('Mesh Data must contain vertices and faces') vertices = np.asarray(data['vertices']) faces = np.asarray(data['faces']) material = self.context.THREE.MeshLambertMaterial.new_object({ 'color': 0xfffacd, 'vertexColors': self.context.THREE.NoColors, 'side': self.context.THREE.DoubleSide, }) mesh = {'vertices': vertices, 'faces': faces} if 'vertex_colors' in data: mesh['vertex_colors'] = np.asarray(data['vertex_colors']) material = self.context.THREE.MeshLambertMaterial.new_object({ 'color': 0xfffacd, 'vertexColors': self.context.THREE.VertexColors, 'side': self.context.THREE.DoubleSide, }) mesh['material'] = material return mesh def __init__(self, source_mesh_data): context = threejs_visualization.build_context() self.context = context light1 = context.THREE.PointLight.new_object(0x808080) light1.position.set(10., 10., 10.) light2 = context.THREE.AmbientLight.new_object(0x808080) lights = (light1, light2) camera = threejs_visualization.build_perspective_camera( field_of_view=30, position=(0.0, 0.0, 4.0)) mesh = self._mesh_from_data(source_mesh_data) geometries = threejs_visualization.triangular_mesh_renderer([mesh], lights=lights, camera=camera, width=400, height=400) self.geometries = geometries
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/geometry/representation/mesh/tests/mesh_test_utils.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper routines for mesh unit tests. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np def create_single_triangle_mesh(): r"""Creates a single-triangle mesh, in the z=0 plane and facing +z. (0,1) 2 |\ | \ | \ (0,0) 0---1 (1,0) Returns: vertices: A [3, 3] float array faces: A [1, 3] int array """ vertices = np.array( ((0, 0, 0), (1, 0, 0), (0, 1, 0)), dtype=np.float32) faces = np.array(((0, 1, 2),), dtype=np.int32) return vertices, faces def create_square_triangle_mesh(): r"""Creates a square mesh, in the z=0 planse and facing +z. # (0,1) 2---3 (1,1) # |\ /| # | 4 | # |/ \| # (0,0) 0---1 (1,0) Returns: vertices: A [5, 3] float array faces: A [4, 3] int array """ vertices = np.array( ((0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0.5, 0.5, 0)), dtype=np.float32) faces = np.array( ((0, 1, 4), (1, 3, 4), (3, 2, 4), (2, 0, 4)), dtype=np.int32) return vertices, faces
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper routines for mesh unit tests. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np def create_single_triangle_mesh(): r"""Creates a single-triangle mesh, in the z=0 plane and facing +z. (0,1) 2 |\ | \ | \ (0,0) 0---1 (1,0) Returns: vertices: A [3, 3] float array faces: A [1, 3] int array """ vertices = np.array( ((0, 0, 0), (1, 0, 0), (0, 1, 0)), dtype=np.float32) faces = np.array(((0, 1, 2),), dtype=np.int32) return vertices, faces def create_square_triangle_mesh(): r"""Creates a square mesh, in the z=0 planse and facing +z. # (0,1) 2---3 (1,1) # |\ /| # | 4 | # |/ \| # (0,0) 0---1 (1,0) Returns: vertices: A [5, 3] float array faces: A [4, 3] int array """ vertices = np.array( ((0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0.5, 0.5, 0)), dtype=np.float32) faces = np.array( ((0, 1, 4), (1, 3, 4), (3, 2, 4), (2, 0, 4)), dtype=np.int32) return vertices, faces
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/datasets/modelnet40/modelnet40_run.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Simple demo of modelnet40 dataset. See: https://www.tensorflow.org/datasets/api_docs/python/tfds/load """ from absl import app from tensorflow_graphics.datasets.modelnet40 import ModelNet40 def main(_): ds_train, info = ModelNet40.load( split="train", data_dir="~/tensorflow_dataset", with_info=True) for example in ds_train.take(1): points = example["points"] label = example["label"] # --- example accessing data print("points.shape=", points.shape) print("label.shape", label.shape) # --- example accessing info print("Example of string='{}' to ID#={}".format( "airplane", info.features["label"].str2int("airplane"))) print("Example of ID#={} to string='{}'".format( 12, info.features["label"].int2str(12))) if __name__ == "__main__": app.run(main)
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Simple demo of modelnet40 dataset. See: https://www.tensorflow.org/datasets/api_docs/python/tfds/load """ from absl import app from tensorflow_graphics.datasets.modelnet40 import ModelNet40 def main(_): ds_train, info = ModelNet40.load( split="train", data_dir="~/tensorflow_dataset", with_info=True) for example in ds_train.take(1): points = example["points"] label = example["label"] # --- example accessing data print("points.shape=", points.shape) print("label.shape", label.shape) # --- example accessing info print("Example of string='{}' to ID#={}".format( "airplane", info.features["label"].str2int("airplane"))) print("Example of ID#={} to string='{}'".format( 12, info.features["label"].int2str(12))) if __name__ == "__main__": app.run(main)
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./.git/info/exclude
# git ls-files --others --exclude-from=.git/info/exclude # Lines that start with '#' are comments. # For a project mostly in C, the following would be a good set of # exclude patterns (uncomment them if you want to use them): # *.[oa] # *~
# git ls-files --others --exclude-from=.git/info/exclude # Lines that start with '#' are comments. # For a project mostly in C, the following would be a good set of # exclude patterns (uncomment them if you want to use them): # *.[oa] # *~
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./.git/hooks/pre-applypatch.sample
#!/bin/sh # # An example hook script to verify what is about to be committed # by applypatch from an e-mail message. # # The hook should exit with non-zero status after issuing an # appropriate message if it wants to stop the commit. # # To enable this hook, rename this file to "pre-applypatch". . git-sh-setup precommit="$(git rev-parse --git-path hooks/pre-commit)" test -x "$precommit" && exec "$precommit" ${1+"$@"} :
#!/bin/sh # # An example hook script to verify what is about to be committed # by applypatch from an e-mail message. # # The hook should exit with non-zero status after issuing an # appropriate message if it wants to stop the commit. # # To enable this hook, rename this file to "pre-applypatch". . git-sh-setup precommit="$(git rev-parse --git-path hooks/pre-commit)" test -x "$precommit" && exec "$precommit" ${1+"$@"} :
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/datasets/features/pose_feature.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """3D Pose feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_datasets import features class Pose(features.FeaturesDict): """`FeatureConnector` for 3d pose representations. During `_generate_examples`, the feature connector accepts as input any of: * `dict:` A dictionary containing the rotation and translation of the object (see output format below). Output: A dictionary containing: * 'R': A `float32` tensor with shape `[3, 3]` denoting the 3D rotation matrix. * 't': A `float32` tensor with shape `[3,]` denoting the translation vector. """ def __init__(self): super(Pose, self).__init__({ 'R': features.Tensor(shape=(3, 3), dtype=tf.float32), 't': features.Tensor(shape=(3,), dtype=tf.float32), }) def encode_example(self, example_dict): """Convert the given pose into a dict convertible to tf example.""" if not all(key in example_dict for key in ['R', 't']): raise ValueError( f'Missing keys in provided dictionary! Expecting \'R\' and \'t\', ' f'but {example_dict.keys()} were given.') return super(Pose, self).encode_example(example_dict) @classmethod def from_json_content(cls, value) -> 'Pose': return cls() def to_json_content(self): return {}
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """3D Pose feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_datasets import features class Pose(features.FeaturesDict): """`FeatureConnector` for 3d pose representations. During `_generate_examples`, the feature connector accepts as input any of: * `dict:` A dictionary containing the rotation and translation of the object (see output format below). Output: A dictionary containing: * 'R': A `float32` tensor with shape `[3, 3]` denoting the 3D rotation matrix. * 't': A `float32` tensor with shape `[3,]` denoting the translation vector. """ def __init__(self): super(Pose, self).__init__({ 'R': features.Tensor(shape=(3, 3), dtype=tf.float32), 't': features.Tensor(shape=(3,), dtype=tf.float32), }) def encode_example(self, example_dict): """Convert the given pose into a dict convertible to tf example.""" if not all(key in example_dict for key in ['R', 't']): raise ValueError( f'Missing keys in provided dictionary! Expecting \'R\' and \'t\', ' f'but {example_dict.keys()} were given.') return super(Pose, self).encode_example(example_dict) @classmethod def from_json_content(cls, value) -> 'Pose': return cls() def to_json_content(self): return {}
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/projects/README.md
# Projects If you are conducting research / development and would like to open-source deep-learning based solutions for problems making use of 3D / computer graphics techniques, we would love to host your project in TensorFlow Graphics! If you want your project directly hosted and distributed by TensorFlow Graphics, you can put your work under **tensorflow_graphics/projects/PROJECT_NAME**. As a project owner, you set the bar in terms of code quality, style, and tests. The only requirement is a description of your project and how to use it inside **tensorflow_graphics/projects/PROJECT_NAME/README.md** and at least one test that makes sure that your project runs. If your project is linked to a publication, make sure to also include a link to the paper and a bibtex describing how to cite your work. If you have specific needs or requests, feel free to contact us at tf-graphics-contact@google.com; we would love to work with you to find a solution that fits your project!
# Projects If you are conducting research / development and would like to open-source deep-learning based solutions for problems making use of 3D / computer graphics techniques, we would love to host your project in TensorFlow Graphics! If you want your project directly hosted and distributed by TensorFlow Graphics, you can put your work under **tensorflow_graphics/projects/PROJECT_NAME**. As a project owner, you set the bar in terms of code quality, style, and tests. The only requirement is a description of your project and how to use it inside **tensorflow_graphics/projects/PROJECT_NAME/README.md** and at least one test that makes sure that your project runs. If your project is linked to a publication, make sure to also include a link to the paper and a bibtex describing how to cite your work. If you have specific needs or requests, feel free to contact us at tf-graphics-contact@google.com; we would love to work with you to find a solution that fits your project!
-1
tensorflow/graphics
487
Adding missing modules to __init__.py files for documentation generation.
Adding missing modules to __init__.py files for documentation generation.
copybara-service[bot]
"2021-01-29T17:38:21Z"
"2021-01-29T23:40:27Z"
0023dad7dc0c41fdceaaeb71c5ff3fd2232dacfa
d047500d9b6cb9b716e4b02859d5cc9efb004156
Adding missing modules to __init__.py files for documentation generation.. Adding missing modules to __init__.py files for documentation generation.
./tensorflow_graphics/rendering/reflectance/tests/lambertian_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for lambertian reflectance.""" import math import sys from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.rendering.reflectance import lambertian from tensorflow_graphics.util import test_case class LambertianTest(test_case.TestCase): @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_brdf_jacobian_random(self): """Tests the Jacobian of brdf.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() direction_incoming_light_init = np.random.uniform( 1.0, 1.0, size=tensor_shape + [3]) direction_outgoing_light_init = np.random.uniform( 1.0, 1.0, size=tensor_shape + [3]) surface_normal_init = np.random.uniform(1.0, 1.0, size=tensor_shape + [3]) albedo_init = np.random.random(tensor_shape + [3]) def lamertian_brdf_fn(albedo): return lambertian.brdf(direction_incoming_light_init, direction_outgoing_light_init, surface_normal_init, albedo) self.assert_jacobian_is_correct_fn(lamertian_brdf_fn, [albedo_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_brdf_jacobian_preset(self): direction_incoming_light_init = np.array((0.0, 1.0, 0.0)) direction_outgoing_light_init = np.array((0.0, 1.0, 0.0)) surface_normal_init = np.array((1.0, 0.0, 0.0)) albedo_init = np.array((1.0, 1.0, 1.0)) def lamertian_brdf_fn(albedo): return lambertian.brdf(direction_incoming_light_init, direction_outgoing_light_init, surface_normal_init, albedo) self.assert_jacobian_is_correct_fn(lamertian_brdf_fn, [albedo_init]) @parameterized.parameters( (-1.0, 1.0, 1.0 / math.pi), (1.0, 1.0, 0.0), (-1.0, -1.0, 0.0), (1.0, -1.0, 0.0), ) def test_brdf_random(self, incoming_yz, outgoing_yz, ratio): tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() albedo = np.random.uniform(low=0.0, high=1.0, size=tensor_shape + [3]) direction_incoming_light = np.random.uniform( low=-1.0, high=1.0, size=tensor_shape + [3]) direction_outgoing_light = np.random.uniform( low=-1.0, high=1.0, size=tensor_shape + [3]) surface_normal = np.array((0.0, 1.0, 1.0)) direction_incoming_light[..., 1:3] = incoming_yz direction_outgoing_light[..., 1:3] = outgoing_yz direction_incoming_light = direction_incoming_light / np.linalg.norm( direction_incoming_light, axis=-1, keepdims=True) direction_outgoing_light = direction_outgoing_light / np.linalg.norm( direction_outgoing_light, axis=-1, keepdims=True) surface_normal = surface_normal / np.linalg.norm( surface_normal, axis=-1, keepdims=True) gt = albedo * ratio pred = lambertian.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, albedo) self.assertAllClose(gt, pred) def test_brdf_exceptions_raised(self): """Tests that the exceptions are raised correctly.""" direction_incoming_light = np.random.uniform(-1.0, 1.0, size=(3,)) direction_outgoing_light = np.random.uniform(-1.0, 1.0, size=(3,)) surface_normal = np.random.uniform(-1.0, 1.0, size=(3,)) albedo = np.random.uniform(0.0, 1.0, (3,)) with self.subTest(name="assert_on_direction_incoming_light_not_normalized"): with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( lambertian.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, albedo)) direction_incoming_light /= np.linalg.norm( direction_incoming_light, axis=-1) with self.subTest(name="assert_on_direction_outgoing_light_not_normalized"): with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( lambertian.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, albedo)) direction_outgoing_light /= np.linalg.norm( direction_outgoing_light, axis=-1) with self.subTest(name="assert_on_surface_normal_not_normalized"): with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( lambertian.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, albedo)) surface_normal /= np.linalg.norm(surface_normal, axis=-1) with self.subTest(name="assert_on_albedo_not_normalized"): albedo = np.random.uniform(-10.0, -sys.float_info.epsilon, (3,)) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( lambertian.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, albedo)) albedo = np.random.uniform(sys.float_info.epsilon, 10.0, (3,)) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( lambertian.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, albedo)) @parameterized.parameters( ((3,), (3,), (3,), (3,)), ((None, 3), (None, 3), (None, 3), (None, 3)), ((1, 3), (1, 3), (1, 3), (1, 3)), ((2, 3), (2, 3), (2, 3), (2, 3)), ((3,), (1, 3), (1, 2, 3), (1, 3)), ((3,), (1, 3), (1, 2, 3), (1, 2, 2, 3)), ((1, 2, 2, 3), (1, 2, 3), (1, 3), (3,)), ) def test_brdf_shape_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(lambertian.brdf, shape) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (1,), (3,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (2,), (3,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (4,), (3,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (1,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (2,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (4,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (2,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (4,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (3,), (4,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (3,), (2,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (3,), (1,)), ("Not all batch dimensions are broadcast-compatible.", (2, 3), (3, 3), (3,), (3,)), ) def test_brdf_shape_exception_raised(self, error_msg, *shape): """Tests that the shape exception is raised.""" self.assert_exception_is_raised(lambertian.brdf, error_msg, shape) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for lambertian reflectance.""" import math import sys from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.rendering.reflectance import lambertian from tensorflow_graphics.util import test_case class LambertianTest(test_case.TestCase): @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_brdf_jacobian_random(self): """Tests the Jacobian of brdf.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() direction_incoming_light_init = np.random.uniform( 1.0, 1.0, size=tensor_shape + [3]) direction_outgoing_light_init = np.random.uniform( 1.0, 1.0, size=tensor_shape + [3]) surface_normal_init = np.random.uniform(1.0, 1.0, size=tensor_shape + [3]) albedo_init = np.random.random(tensor_shape + [3]) def lamertian_brdf_fn(albedo): return lambertian.brdf(direction_incoming_light_init, direction_outgoing_light_init, surface_normal_init, albedo) self.assert_jacobian_is_correct_fn(lamertian_brdf_fn, [albedo_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_brdf_jacobian_preset(self): direction_incoming_light_init = np.array((0.0, 1.0, 0.0)) direction_outgoing_light_init = np.array((0.0, 1.0, 0.0)) surface_normal_init = np.array((1.0, 0.0, 0.0)) albedo_init = np.array((1.0, 1.0, 1.0)) def lamertian_brdf_fn(albedo): return lambertian.brdf(direction_incoming_light_init, direction_outgoing_light_init, surface_normal_init, albedo) self.assert_jacobian_is_correct_fn(lamertian_brdf_fn, [albedo_init]) @parameterized.parameters( (-1.0, 1.0, 1.0 / math.pi), (1.0, 1.0, 0.0), (-1.0, -1.0, 0.0), (1.0, -1.0, 0.0), ) def test_brdf_random(self, incoming_yz, outgoing_yz, ratio): tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() albedo = np.random.uniform(low=0.0, high=1.0, size=tensor_shape + [3]) direction_incoming_light = np.random.uniform( low=-1.0, high=1.0, size=tensor_shape + [3]) direction_outgoing_light = np.random.uniform( low=-1.0, high=1.0, size=tensor_shape + [3]) surface_normal = np.array((0.0, 1.0, 1.0)) direction_incoming_light[..., 1:3] = incoming_yz direction_outgoing_light[..., 1:3] = outgoing_yz direction_incoming_light = direction_incoming_light / np.linalg.norm( direction_incoming_light, axis=-1, keepdims=True) direction_outgoing_light = direction_outgoing_light / np.linalg.norm( direction_outgoing_light, axis=-1, keepdims=True) surface_normal = surface_normal / np.linalg.norm( surface_normal, axis=-1, keepdims=True) gt = albedo * ratio pred = lambertian.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, albedo) self.assertAllClose(gt, pred) def test_brdf_exceptions_raised(self): """Tests that the exceptions are raised correctly.""" direction_incoming_light = np.random.uniform(-1.0, 1.0, size=(3,)) direction_outgoing_light = np.random.uniform(-1.0, 1.0, size=(3,)) surface_normal = np.random.uniform(-1.0, 1.0, size=(3,)) albedo = np.random.uniform(0.0, 1.0, (3,)) with self.subTest(name="assert_on_direction_incoming_light_not_normalized"): with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( lambertian.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, albedo)) direction_incoming_light /= np.linalg.norm( direction_incoming_light, axis=-1) with self.subTest(name="assert_on_direction_outgoing_light_not_normalized"): with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( lambertian.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, albedo)) direction_outgoing_light /= np.linalg.norm( direction_outgoing_light, axis=-1) with self.subTest(name="assert_on_surface_normal_not_normalized"): with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( lambertian.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, albedo)) surface_normal /= np.linalg.norm(surface_normal, axis=-1) with self.subTest(name="assert_on_albedo_not_normalized"): albedo = np.random.uniform(-10.0, -sys.float_info.epsilon, (3,)) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( lambertian.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, albedo)) albedo = np.random.uniform(sys.float_info.epsilon, 10.0, (3,)) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate( lambertian.brdf(direction_incoming_light, direction_outgoing_light, surface_normal, albedo)) @parameterized.parameters( ((3,), (3,), (3,), (3,)), ((None, 3), (None, 3), (None, 3), (None, 3)), ((1, 3), (1, 3), (1, 3), (1, 3)), ((2, 3), (2, 3), (2, 3), (2, 3)), ((3,), (1, 3), (1, 2, 3), (1, 3)), ((3,), (1, 3), (1, 2, 3), (1, 2, 2, 3)), ((1, 2, 2, 3), (1, 2, 3), (1, 3), (3,)), ) def test_brdf_shape_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(lambertian.brdf, shape) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (1,), (3,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (2,), (3,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (4,), (3,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (1,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (2,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (4,), (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (1,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (2,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (4,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (3,), (4,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (3,), (2,)), ("must have exactly 3 dimensions in axis -1", (3,), (3,), (3,), (1,)), ("Not all batch dimensions are broadcast-compatible.", (2, 3), (3, 3), (3,), (3,)), ) def test_brdf_shape_exception_raised(self, error_msg, *shape): """Tests that the shape exception is raised.""" self.assert_exception_is_raised(lambertian.brdf, error_msg, shape) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/geometry/transformation/axis_angle.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""This module implements axis-angle functionalities. The axis-angle representation is defined as $$\theta\mathbf{a}$$, where $$\mathbf{a}$$ is a unit vector indicating the direction of rotation and $$\theta$$ is a scalar controlling the angle of rotation. It is important to note that the axis-angle does not perform rotation by itself, but that it can be used to rotate any given vector $$\mathbf{v} \in {\mathbb{R}^3}$$ into a vector $$\mathbf{v}'$$ using the Rodrigues' rotation formula: $$\mathbf{v}'=\mathbf{v}\cos(\theta)+(\mathbf{a}\times\mathbf{v})\sin(\theta) +\mathbf{a}(\mathbf{a}\cdot\mathbf{v})(1-\cos(\theta)).$$ More details about the axis-angle formalism can be found on [this page.] (https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation) Note: Some of the functions defined in the module expect a normalized axis $$\mathbf{a} = [x, y, z]^T$$ as inputs where $$x^2 + y^2 + z^2 = 1$$. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.transformation import quaternion as quaternion_lib from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def from_euler(angles, name=None): r"""Converts Euler angles to an axis-angle representation. Note: The conversion is performed by first converting to a quaternion representation, and then by converting the quaternion to an axis-angle. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "axis_angle_from_euler". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. """ with tf.compat.v1.name_scope(name, "axis_angle_from_euler", [angles]): quaternion = quaternion_lib.from_euler(angles) return from_quaternion(quaternion) def from_euler_with_small_angles_approximation(angles, name=None): r"""Converts small Euler angles to an axis-angle representation. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: The conversion is performed by first converting to a quaternion representation, and then by converting the quaternion to an axis-angle. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three small Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "axis_angle_from_euler_with_small_angles_approximation". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. """ with tf.compat.v1.name_scope( name, "axis_angle_from_euler_with_small_angles_approximation", [angles]): quaternion = quaternion_lib.from_euler_with_small_angles_approximation( angles) return from_quaternion(quaternion) def from_quaternion(quaternion, name=None): """Converts a quaternion to an axis-angle representation. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "axis_angle_from_quaternion". Returns: Tuple of two tensors of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.compat.v1.name_scope(name, "axis_angle_from_quaternion", [quaternion]): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) # This prevents zero norm xyz and zero w, and is differentiable. quaternion += asserts.select_eps_for_addition(quaternion.dtype) xyz, w = tf.split(quaternion, (3, 1), axis=-1) norm = tf.norm(tensor=xyz, axis=-1, keepdims=True) angle = 2.0 * tf.atan2(norm, tf.abs(w)) axis = safe_ops.safe_unsigned_div(safe_ops.nonzero_sign(w) * xyz, norm) return axis, angle def from_rotation_matrix(rotation_matrix, name=None): """Converts a rotation matrix to an axis-angle representation. Note: In the current version the returned axis-angle representation is not unique for a given rotation matrix. Since a direct conversion would not really be faster, we first transform the rotation matrix to a quaternion, and finally perform the conversion from that quaternion to the corresponding axis-angle representation. Note: In the following, A1 to An are optional batch dimensions. Args: rotation_matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a rotation matrix. name: A name for this op that defaults to "axis_angle_from_rotation_matrix". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. Raises: ValueError: If the shape of `rotation_matrix` is not supported. """ with tf.compat.v1.name_scope(name, "axis_angle_from_rotation_matrix", [rotation_matrix]): rotation_matrix = tf.convert_to_tensor(value=rotation_matrix) shape.check_static( tensor=rotation_matrix, tensor_name="rotation_matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) rotation_matrix = rotation_matrix_3d.assert_rotation_matrix_normalized( rotation_matrix) quaternion = quaternion_lib.from_rotation_matrix(rotation_matrix) return from_quaternion(quaternion) def inverse(axis, angle, name=None): """Computes the axis-angle that is the inverse of the input axis-angle. Note: In the following, A1 to An are optional batch dimensions. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]` where the last dimension represents an angle. name: A name for this op that defaults to "axis_angle_inverse". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.compat.v1.name_scope(name, "axis_angle_inverse", [axis, angle]): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) return axis, -angle def is_normalized(axis, angle, atol=1e-3, name=None): """Determines if the axis-angle is normalized or not. Note: In the following, A1 to An are optional batch dimensions. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]` where the last dimension represents an angle. atol: The absolute tolerance parameter. name: A name for this op that defaults to "axis_angle_is_normalized". Returns: A tensor of shape `[A1, ..., An, 1]`, where False indicates that the axis is not normalized. """ with tf.compat.v1.name_scope(name, "axis_angle_is_normalized", [axis, angle]): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) norms = tf.norm(tensor=axis, axis=-1, keepdims=True) return tf.abs(norms - 1.) < atol def rotate(point, axis, angle, name=None): r"""Rotates a 3d point using an axis-angle by applying the Rodrigues' formula. Rotates a vector $$\mathbf{v} \in {\mathbb{R}^3}$$ into a vector $$\mathbf{v}' \in {\mathbb{R}^3}$$ using the Rodrigues' rotation formula: $$\mathbf{v}'=\mathbf{v}\cos(\theta)+(\mathbf{a}\times\mathbf{v})\sin(\theta) +\mathbf{a}(\mathbf{a}\cdot\mathbf{v})(1-\cos(\theta)).$$ Note: In the following, A1 to An are optional batch dimensions. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point to rotate. axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents an angle. name: A name for this op that defaults to "axis_angle_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If `point`, `axis`, or `angle` are of different shape or if their respective shape is not supported. """ with tf.compat.v1.name_scope(name, "axis_angle_rotate", [point, axis, angle]): point = tf.convert_to_tensor(value=point) axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(point, axis, angle), tensor_names=("point", "axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) cos_angle = tf.cos(angle) axis_dot_point = vector.dot(axis, point) return point * cos_angle + vector.cross( axis, point) * tf.sin(angle) + axis * axis_dot_point * (1.0 - cos_angle) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""This module implements axis-angle functionalities. The axis-angle representation is defined as $$\theta\mathbf{a}$$, where $$\mathbf{a}$$ is a unit vector indicating the direction of rotation and $$\theta$$ is a scalar controlling the angle of rotation. It is important to note that the axis-angle does not perform rotation by itself, but that it can be used to rotate any given vector $$\mathbf{v} \in {\mathbb{R}^3}$$ into a vector $$\mathbf{v}'$$ using the Rodrigues' rotation formula: $$\mathbf{v}'=\mathbf{v}\cos(\theta)+(\mathbf{a}\times\mathbf{v})\sin(\theta) +\mathbf{a}(\mathbf{a}\cdot\mathbf{v})(1-\cos(\theta)).$$ More details about the axis-angle formalism can be found on [this page.] (https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation) Note: Some of the functions defined in the module expect a normalized axis $$\mathbf{a} = [x, y, z]^T$$ as inputs where $$x^2 + y^2 + z^2 = 1$$. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.transformation import quaternion as quaternion_lib from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def from_euler(angles, name="axis_angle_from_euler"): r"""Converts Euler angles to an axis-angle representation. Note: The conversion is performed by first converting to a quaternion representation, and then by converting the quaternion to an axis-angle. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "axis_angle_from_euler". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. """ with tf.name_scope(name): quaternion = quaternion_lib.from_euler(angles) return from_quaternion(quaternion) def from_euler_with_small_angles_approximation( angles, name="axis_angle_from_euler_with_small_angles_approximation"): r"""Converts small Euler angles to an axis-angle representation. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: The conversion is performed by first converting to a quaternion representation, and then by converting the quaternion to an axis-angle. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three small Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "axis_angle_from_euler_with_small_angles_approximation". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. """ with tf.name_scope(name): quaternion = quaternion_lib.from_euler_with_small_angles_approximation( angles) return from_quaternion(quaternion) def from_quaternion(quaternion, name="axis_angle_from_quaternion"): """Converts a quaternion to an axis-angle representation. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "axis_angle_from_quaternion". Returns: Tuple of two tensors of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) # This prevents zero norm xyz and zero w, and is differentiable. quaternion += asserts.select_eps_for_addition(quaternion.dtype) xyz, w = tf.split(quaternion, (3, 1), axis=-1) norm = tf.norm(tensor=xyz, axis=-1, keepdims=True) angle = 2.0 * tf.atan2(norm, tf.abs(w)) axis = safe_ops.safe_unsigned_div(safe_ops.nonzero_sign(w) * xyz, norm) return axis, angle def from_rotation_matrix(rotation_matrix, name="axis_angle_from_rotation_matrix"): """Converts a rotation matrix to an axis-angle representation. Note: In the current version the returned axis-angle representation is not unique for a given rotation matrix. Since a direct conversion would not really be faster, we first transform the rotation matrix to a quaternion, and finally perform the conversion from that quaternion to the corresponding axis-angle representation. Note: In the following, A1 to An are optional batch dimensions. Args: rotation_matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a rotation matrix. name: A name for this op that defaults to "axis_angle_from_rotation_matrix". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. Raises: ValueError: If the shape of `rotation_matrix` is not supported. """ with tf.name_scope(name): rotation_matrix = tf.convert_to_tensor(value=rotation_matrix) shape.check_static( tensor=rotation_matrix, tensor_name="rotation_matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) rotation_matrix = rotation_matrix_3d.assert_rotation_matrix_normalized( rotation_matrix) quaternion = quaternion_lib.from_rotation_matrix(rotation_matrix) return from_quaternion(quaternion) def inverse(axis, angle, name="axis_angle_inverse"): """Computes the axis-angle that is the inverse of the input axis-angle. Note: In the following, A1 to An are optional batch dimensions. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]` where the last dimension represents an angle. name: A name for this op that defaults to "axis_angle_inverse". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.name_scope(name): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) return axis, -angle def is_normalized(axis, angle, atol=1e-3, name="axis_angle_is_normalized"): """Determines if the axis-angle is normalized or not. Note: In the following, A1 to An are optional batch dimensions. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]` where the last dimension represents an angle. atol: The absolute tolerance parameter. name: A name for this op that defaults to "axis_angle_is_normalized". Returns: A tensor of shape `[A1, ..., An, 1]`, where False indicates that the axis is not normalized. """ with tf.name_scope(name): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) norms = tf.norm(tensor=axis, axis=-1, keepdims=True) return tf.abs(norms - 1.) < atol def rotate(point, axis, angle, name="axis_angle_rotate"): r"""Rotates a 3d point using an axis-angle by applying the Rodrigues' formula. Rotates a vector $$\mathbf{v} \in {\mathbb{R}^3}$$ into a vector $$\mathbf{v}' \in {\mathbb{R}^3}$$ using the Rodrigues' rotation formula: $$\mathbf{v}'=\mathbf{v}\cos(\theta)+(\mathbf{a}\times\mathbf{v})\sin(\theta) +\mathbf{a}(\mathbf{a}\cdot\mathbf{v})(1-\cos(\theta)).$$ Note: In the following, A1 to An are optional batch dimensions. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point to rotate. axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents an angle. name: A name for this op that defaults to "axis_angle_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If `point`, `axis`, or `angle` are of different shape or if their respective shape is not supported. """ with tf.name_scope(name): point = tf.convert_to_tensor(value=point) axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(point, axis, angle), tensor_names=("point", "axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) cos_angle = tf.cos(angle) axis_dot_point = vector.dot(axis, point) return point * cos_angle + vector.cross( axis, point) * tf.sin(angle) + axis * axis_dot_point * (1.0 - cos_angle) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/geometry/transformation/dual_quaternion.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow dual quaternion utility functions. A dual quaternion is an extension of a quaternion with the real and dual parts and written as $$q = q_r + epsilon q_d$$, where $$epsilon$$ is the dual number with the property $$e^2 = 0$$. It can thus be represented as two quaternions, and thus stored as 8 numbers. We define the operations in terms of the two quaternions $$q_r$$ and $$q_d$$. Dual quaternions are extensions of quaternions to represent rigid transformations (rotations and translations). They are in particular important for deforming geometries as linear blending is a very close approximation of closest path blending, which is not the case for any other representation. Note: Some of the functions expect normalized quaternions as inputs where $$|q_r| = 1$$. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v2 as tf from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def conjugate(dual_quaternion, name=None): """Computes the conjugate of a dual quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: dual_quaternion: A tensor of shape `[A1, ..., An, 8]`, where the last dimension represents a normalized dual quaternion. name: A name for this op that defaults to "dual_quaternion_conjugate". Returns: A tensor of shape `[A1, ..., An, 8]`, where the last dimension represents a normalized dual quaternion. Raises: ValueError: If the shape of `dual_quaternion` is not supported. """ with tf.compat.v1.name_scope(name, "dual_quaternion_conjugate", [dual_quaternion]): dual_quaternion = tf.convert_to_tensor(value=dual_quaternion) shape.check_static( tensor=dual_quaternion, tensor_name="dual_quaternion", has_dim_equals=(-1, 8)) quaternion_real, quaternion_dual = tf.split( dual_quaternion, (4, 4), axis=-1) quaternion_real = asserts.assert_normalized(quaternion_real) return tf.concat((quaternion.conjugate(quaternion_real), quaternion.conjugate(quaternion_dual)), axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow dual quaternion utility functions. A dual quaternion is an extension of a quaternion with the real and dual parts and written as $$q = q_r + epsilon q_d$$, where $$epsilon$$ is the dual number with the property $$e^2 = 0$$. It can thus be represented as two quaternions, and thus stored as 8 numbers. We define the operations in terms of the two quaternions $$q_r$$ and $$q_d$$. Dual quaternions are extensions of quaternions to represent rigid transformations (rotations and translations). They are in particular important for deforming geometries as linear blending is a very close approximation of closest path blending, which is not the case for any other representation. Note: Some of the functions expect normalized quaternions as inputs where $$|q_r| = 1$$. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v2 as tf from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def conjugate(dual_quaternion, name="dual_quaternion_conjugate"): """Computes the conjugate of a dual quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: dual_quaternion: A tensor of shape `[A1, ..., An, 8]`, where the last dimension represents a normalized dual quaternion. name: A name for this op that defaults to "dual_quaternion_conjugate". Returns: A tensor of shape `[A1, ..., An, 8]`, where the last dimension represents a normalized dual quaternion. Raises: ValueError: If the shape of `dual_quaternion` is not supported. """ with tf.name_scope(name): dual_quaternion = tf.convert_to_tensor(value=dual_quaternion) shape.check_static( tensor=dual_quaternion, tensor_name="dual_quaternion", has_dim_equals=(-1, 8)) quaternion_real, quaternion_dual = tf.split( dual_quaternion, (4, 4), axis=-1) quaternion_real = asserts.assert_normalized(quaternion_real) return tf.concat((quaternion.conjugate(quaternion_real), quaternion.conjugate(quaternion_dual)), axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/geometry/transformation/euler.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""This modules implements Euler angles functionalities. The Euler angles are defined using a vector $$[\theta, \gamma, \beta]^T \in \mathbb{R}^3$$, where $$\theta$$ is the angle about $$x$$, $$\gamma$$ the angle about $$y$$, and $$\beta$$ is the angle about $$z$$ More details about Euler angles can be found on [this page.] (https://en.wikipedia.org/wiki/Euler_angles) Note: The angles are defined in radians. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def from_axis_angle(axis, angle, name=None): """Converts axis-angle to Euler angles. Note: In the following, A1 to An are optional batch dimensions. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents an angle. name: A name for this op that defaults to "euler_from_axis_angle". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. """ with tf.compat.v1.name_scope(name, "euler_from_axis_angle", [axis, angle]): return from_quaternion(quaternion.from_axis_angle(axis, angle)) def from_quaternion(quaternions, name=None): """Converts quaternions to Euler angles. Args: quaternions: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "euler_from_quaternion". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. """ def general_case(r00, r10, r21, r22, r20, eps_addition): """Handles the general case.""" theta_y = -tf.asin(r20) sign_cos_theta_y = safe_ops.nonzero_sign(tf.cos(theta_y)) r00 = safe_ops.nonzero_sign(r00) * eps_addition + r00 r22 = safe_ops.nonzero_sign(r22) * eps_addition + r22 theta_z = tf.atan2(r10 * sign_cos_theta_y, r00 * sign_cos_theta_y) theta_x = tf.atan2(r21 * sign_cos_theta_y, r22 * sign_cos_theta_y) return tf.stack((theta_x, theta_y, theta_z), axis=-1) def gimbal_lock(r01, r02, r20, eps_addition): """Handles Gimbal locks.""" sign_r20 = safe_ops.nonzero_sign(r20) r02 = safe_ops.nonzero_sign(r02) * eps_addition + r02 theta_x = tf.atan2(-sign_r20 * r01, -sign_r20 * r02) theta_y = -sign_r20 * tf.constant(math.pi / 2.0, dtype=r20.dtype) theta_z = tf.zeros_like(theta_x) angles = tf.stack((theta_x, theta_y, theta_z), axis=-1) return angles with tf.compat.v1.name_scope(name, "euler_from_quaternion", [quaternions]): quaternions = tf.convert_to_tensor(value=quaternions) shape.check_static( tensor=quaternions, tensor_name="quaternions", has_dim_equals=(-1, 4)) x, y, z, w = tf.unstack(quaternions, axis=-1) tx = safe_ops.safe_shrink(2.0 * x, -2.0, 2.0, True) ty = safe_ops.safe_shrink(2.0 * y, -2.0, 2.0, True) tz = safe_ops.safe_shrink(2.0 * z, -2.0, 2.0, True) twx = tx * w twy = ty * w twz = tz * w txx = tx * x txy = ty * x txz = tz * x tyy = ty * y tyz = tz * y tzz = tz * z # The following is clipped due to numerical instabilities that can take some # enties outside the [-1;1] range. r00 = safe_ops.safe_shrink(1.0 - (tyy + tzz), -1.0, 1.0, True) r10 = safe_ops.safe_shrink(txy + twz, -1.0, 1.0, True) r21 = safe_ops.safe_shrink(tyz + twx, -1.0, 1.0, True) r22 = safe_ops.safe_shrink(1.0 - (txx + tyy), -1.0, 1.0, True) r20 = safe_ops.safe_shrink(txz - twy, -1.0, 1.0, True) r01 = safe_ops.safe_shrink(txy - twz, -1.0, 1.0, True) r02 = safe_ops.safe_shrink(txz + twy, -1.0, 1.0, True) eps_addition = asserts.select_eps_for_addition(quaternions.dtype) general_solution = general_case(r00, r10, r21, r22, r20, eps_addition) gimbal_solution = gimbal_lock(r01, r02, r20, eps_addition) # The general solution is unstable close to the Gimbal lock, and the gimbal # solution is not toooff in these cases. is_gimbal = tf.less(tf.abs(tf.abs(r20) - 1.0), 1.0e-6) gimbal_mask = tf.stack((is_gimbal, is_gimbal, is_gimbal), axis=-1) return tf.compat.v1.where(gimbal_mask, gimbal_solution, general_solution) def from_rotation_matrix(rotation_matrix, name=None): """Converts rotation matrices to Euler angles. The rotation matrices are assumed to have been constructed by rotation around the $$x$$, then $$y$$, and finally the $$z$$ axis. Note: There is an infinite number of solutions to this problem. There are Gimbal locks when abs(rotation_matrix(2,0)) == 1, which are not handled. Note: In the following, A1 to An are optional batch dimensions. Args: rotation_matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a rotation matrix. name: A name for this op that defaults to "euler_from_rotation_matrix". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. Raises: ValueError: If the shape of `rotation_matrix` is not supported. """ def general_case(rotation_matrix, r20, eps_addition): """Handles the general case.""" theta_y = -tf.asin(r20) sign_cos_theta_y = safe_ops.nonzero_sign(tf.cos(theta_y)) r00 = rotation_matrix[..., 0, 0] r10 = rotation_matrix[..., 1, 0] r21 = rotation_matrix[..., 2, 1] r22 = rotation_matrix[..., 2, 2] r00 = safe_ops.nonzero_sign(r00) * eps_addition + r00 r22 = safe_ops.nonzero_sign(r22) * eps_addition + r22 # cos_theta_y evaluates to 0 on Gimbal locks, in which case the output of # this function will not be used. theta_z = tf.atan2(r10 * sign_cos_theta_y, r00 * sign_cos_theta_y) theta_x = tf.atan2(r21 * sign_cos_theta_y, r22 * sign_cos_theta_y) angles = tf.stack((theta_x, theta_y, theta_z), axis=-1) return angles def gimbal_lock(rotation_matrix, r20, eps_addition): """Handles Gimbal locks.""" r01 = rotation_matrix[..., 0, 1] r02 = rotation_matrix[..., 0, 2] sign_r20 = safe_ops.nonzero_sign(r20) r02 = safe_ops.nonzero_sign(r02) * eps_addition + r02 theta_x = tf.atan2(-sign_r20 * r01, -sign_r20 * r02) theta_y = -sign_r20 * tf.constant(math.pi / 2.0, dtype=r20.dtype) theta_z = tf.zeros_like(theta_x) angles = tf.stack((theta_x, theta_y, theta_z), axis=-1) return angles with tf.compat.v1.name_scope(name, "euler_from_rotation_matrix", [rotation_matrix]): rotation_matrix = tf.convert_to_tensor(value=rotation_matrix) shape.check_static( tensor=rotation_matrix, tensor_name="rotation_matrix", has_rank_greater_than=1, has_dim_equals=((-1, 3), (-2, 3))) rotation_matrix = rotation_matrix_3d.assert_rotation_matrix_normalized( rotation_matrix) r20 = rotation_matrix[..., 2, 0] eps_addition = asserts.select_eps_for_addition(rotation_matrix.dtype) general_solution = general_case(rotation_matrix, r20, eps_addition) gimbal_solution = gimbal_lock(rotation_matrix, r20, eps_addition) is_gimbal = tf.equal(tf.abs(r20), 1) gimbal_mask = tf.stack((is_gimbal, is_gimbal, is_gimbal), axis=-1) return tf.compat.v1.where(gimbal_mask, gimbal_solution, general_solution) def inverse(euler_angle, name=None): """Computes the angles that would inverse a transformation by euler_angle. Note: In the following, A1 to An are optional batch dimensions. Args: euler_angle: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. name: A name for this op that defaults to "euler_inverse". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. Raises: ValueError: If the shape of `euler_angle` is not supported. """ with tf.compat.v1.name_scope(name, "euler_inverse", [euler_angle]): euler_angle = tf.convert_to_tensor(value=euler_angle) shape.check_static( tensor=euler_angle, tensor_name="euler_angle", has_dim_equals=(-1, 3)) return -euler_angle # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""This modules implements Euler angles functionalities. The Euler angles are defined using a vector $$[\theta, \gamma, \beta]^T \in \mathbb{R}^3$$, where $$\theta$$ is the angle about $$x$$, $$\gamma$$ the angle about $$y$$, and $$\beta$$ is the angle about $$z$$ More details about Euler angles can be found on [this page.] (https://en.wikipedia.org/wiki/Euler_angles) Note: The angles are defined in radians. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def from_axis_angle(axis, angle, name="euler_from_axis_angle"): """Converts axis-angle to Euler angles. Note: In the following, A1 to An are optional batch dimensions. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents an angle. name: A name for this op that defaults to "euler_from_axis_angle". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. """ with tf.name_scope(name): return from_quaternion(quaternion.from_axis_angle(axis, angle)) def from_quaternion(quaternions, name="euler_from_quaternion"): """Converts quaternions to Euler angles. Args: quaternions: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "euler_from_quaternion". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. """ def general_case(r00, r10, r21, r22, r20, eps_addition): """Handles the general case.""" theta_y = -tf.asin(r20) sign_cos_theta_y = safe_ops.nonzero_sign(tf.cos(theta_y)) r00 = safe_ops.nonzero_sign(r00) * eps_addition + r00 r22 = safe_ops.nonzero_sign(r22) * eps_addition + r22 theta_z = tf.atan2(r10 * sign_cos_theta_y, r00 * sign_cos_theta_y) theta_x = tf.atan2(r21 * sign_cos_theta_y, r22 * sign_cos_theta_y) return tf.stack((theta_x, theta_y, theta_z), axis=-1) def gimbal_lock(r01, r02, r20, eps_addition): """Handles Gimbal locks.""" sign_r20 = safe_ops.nonzero_sign(r20) r02 = safe_ops.nonzero_sign(r02) * eps_addition + r02 theta_x = tf.atan2(-sign_r20 * r01, -sign_r20 * r02) theta_y = -sign_r20 * tf.constant(math.pi / 2.0, dtype=r20.dtype) theta_z = tf.zeros_like(theta_x) angles = tf.stack((theta_x, theta_y, theta_z), axis=-1) return angles with tf.name_scope(name): quaternions = tf.convert_to_tensor(value=quaternions) shape.check_static( tensor=quaternions, tensor_name="quaternions", has_dim_equals=(-1, 4)) x, y, z, w = tf.unstack(quaternions, axis=-1) tx = safe_ops.safe_shrink(2.0 * x, -2.0, 2.0, True) ty = safe_ops.safe_shrink(2.0 * y, -2.0, 2.0, True) tz = safe_ops.safe_shrink(2.0 * z, -2.0, 2.0, True) twx = tx * w twy = ty * w twz = tz * w txx = tx * x txy = ty * x txz = tz * x tyy = ty * y tyz = tz * y tzz = tz * z # The following is clipped due to numerical instabilities that can take some # enties outside the [-1;1] range. r00 = safe_ops.safe_shrink(1.0 - (tyy + tzz), -1.0, 1.0, True) r10 = safe_ops.safe_shrink(txy + twz, -1.0, 1.0, True) r21 = safe_ops.safe_shrink(tyz + twx, -1.0, 1.0, True) r22 = safe_ops.safe_shrink(1.0 - (txx + tyy), -1.0, 1.0, True) r20 = safe_ops.safe_shrink(txz - twy, -1.0, 1.0, True) r01 = safe_ops.safe_shrink(txy - twz, -1.0, 1.0, True) r02 = safe_ops.safe_shrink(txz + twy, -1.0, 1.0, True) eps_addition = asserts.select_eps_for_addition(quaternions.dtype) general_solution = general_case(r00, r10, r21, r22, r20, eps_addition) gimbal_solution = gimbal_lock(r01, r02, r20, eps_addition) # The general solution is unstable close to the Gimbal lock, and the gimbal # solution is not toooff in these cases. is_gimbal = tf.less(tf.abs(tf.abs(r20) - 1.0), 1.0e-6) gimbal_mask = tf.stack((is_gimbal, is_gimbal, is_gimbal), axis=-1) return tf.where(gimbal_mask, gimbal_solution, general_solution) def from_rotation_matrix(rotation_matrix, name="euler_from_rotation_matrix"): """Converts rotation matrices to Euler angles. The rotation matrices are assumed to have been constructed by rotation around the $$x$$, then $$y$$, and finally the $$z$$ axis. Note: There is an infinite number of solutions to this problem. There are Gimbal locks when abs(rotation_matrix(2,0)) == 1, which are not handled. Note: In the following, A1 to An are optional batch dimensions. Args: rotation_matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a rotation matrix. name: A name for this op that defaults to "euler_from_rotation_matrix". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. Raises: ValueError: If the shape of `rotation_matrix` is not supported. """ def general_case(rotation_matrix, r20, eps_addition): """Handles the general case.""" theta_y = -tf.asin(r20) sign_cos_theta_y = safe_ops.nonzero_sign(tf.cos(theta_y)) r00 = rotation_matrix[..., 0, 0] r10 = rotation_matrix[..., 1, 0] r21 = rotation_matrix[..., 2, 1] r22 = rotation_matrix[..., 2, 2] r00 = safe_ops.nonzero_sign(r00) * eps_addition + r00 r22 = safe_ops.nonzero_sign(r22) * eps_addition + r22 # cos_theta_y evaluates to 0 on Gimbal locks, in which case the output of # this function will not be used. theta_z = tf.atan2(r10 * sign_cos_theta_y, r00 * sign_cos_theta_y) theta_x = tf.atan2(r21 * sign_cos_theta_y, r22 * sign_cos_theta_y) angles = tf.stack((theta_x, theta_y, theta_z), axis=-1) return angles def gimbal_lock(rotation_matrix, r20, eps_addition): """Handles Gimbal locks.""" r01 = rotation_matrix[..., 0, 1] r02 = rotation_matrix[..., 0, 2] sign_r20 = safe_ops.nonzero_sign(r20) r02 = safe_ops.nonzero_sign(r02) * eps_addition + r02 theta_x = tf.atan2(-sign_r20 * r01, -sign_r20 * r02) theta_y = -sign_r20 * tf.constant(math.pi / 2.0, dtype=r20.dtype) theta_z = tf.zeros_like(theta_x) angles = tf.stack((theta_x, theta_y, theta_z), axis=-1) return angles with tf.name_scope(name): rotation_matrix = tf.convert_to_tensor(value=rotation_matrix) shape.check_static( tensor=rotation_matrix, tensor_name="rotation_matrix", has_rank_greater_than=1, has_dim_equals=((-1, 3), (-2, 3))) rotation_matrix = rotation_matrix_3d.assert_rotation_matrix_normalized( rotation_matrix) r20 = rotation_matrix[..., 2, 0] eps_addition = asserts.select_eps_for_addition(rotation_matrix.dtype) general_solution = general_case(rotation_matrix, r20, eps_addition) gimbal_solution = gimbal_lock(rotation_matrix, r20, eps_addition) is_gimbal = tf.equal(tf.abs(r20), 1) gimbal_mask = tf.stack((is_gimbal, is_gimbal, is_gimbal), axis=-1) return tf.where(gimbal_mask, gimbal_solution, general_solution) def inverse(euler_angle, name="euler_inverse"): """Computes the angles that would inverse a transformation by euler_angle. Note: In the following, A1 to An are optional batch dimensions. Args: euler_angle: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. name: A name for this op that defaults to "euler_inverse". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. Raises: ValueError: If the shape of `euler_angle` is not supported. """ with tf.name_scope(name): euler_angle = tf.convert_to_tensor(value=euler_angle) shape.check_static( tensor=euler_angle, tensor_name="euler_angle", has_dim_equals=(-1, 3)) return -euler_angle # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/geometry/transformation/linear_blend_skinning.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow linear blend skinning functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def blend(points, skinning_weights, bone_rotations, bone_translations, name=None): """Transforms the points using Linear Blend Skinning. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible and allow transforming full 3D shapes at once. In the following, B1 to Bm are optional batch dimensions, which allow transforming multiple poses at once. Args: points: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. skinning_weights: A tensor of shape `[A1, ..., An, W]`, where the last dimension represents the skinning weights of each bone. bone_rotations: A tensor of shape `[B1, ..., Bm, W, 3, 3]`, which represents the 3d rotations applied to each bone. bone_translations: A tensor of shape `[B1, ..., Bm, W, 3]`, which represents the 3d translation vectors applied to each bone. name: A name for this op that defaults to "linear_blend_skinning_blend". Returns: A tensor of shape `[B1, ..., Bm, A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If the shape of the input tensors are not supported. """ with tf.compat.v1.name_scope( name, "linear_blend_skinning_blend", [points, skinning_weights, bone_rotations, bone_translations]): points = tf.convert_to_tensor(value=points) skinning_weights = tf.convert_to_tensor(value=skinning_weights) bone_rotations = tf.convert_to_tensor(value=bone_rotations) bone_translations = tf.convert_to_tensor(value=bone_translations) shape.check_static( tensor=points, tensor_name="points", has_dim_equals=(-1, 3)) shape.check_static( tensor=bone_rotations, tensor_name="bone_rotations", has_rank_greater_than=2, has_dim_equals=((-2, 3), (-1, 3))) shape.check_static( tensor=bone_translations, tensor_name="bone_translations", has_rank_greater_than=1, has_dim_equals=(-1, 3)) shape.compare_dimensions( tensors=(skinning_weights, bone_rotations), tensor_names=("skinning_weights", "bone_rotations"), axes=(-1, -3)) shape.compare_dimensions( tensors=(skinning_weights, bone_translations), tensor_names=("skinning_weights", "bone_translations"), axes=(-1, -2)) shape.compare_batch_dimensions( tensors=(points, skinning_weights), tensor_names=("points", "skinning_weights"), last_axes=(-2, -2), broadcast_compatible=True) shape.compare_batch_dimensions( tensors=(bone_rotations, bone_translations), tensor_names=("bone_rotations", "bone_translations"), last_axes=(-3, -2), broadcast_compatible=True) num_bones = skinning_weights.shape[-1] def dim_value(dim): return 1 if dim is None else tf.compat.v1.dimension_value(dim) # TODO(b/148362025): factorize this block out points_batch_shape = shape.get_broadcasted_shape( points.shape[:-1], skinning_weights.shape[:-1]) points_batch_shape = [dim_value(dim) for dim in points_batch_shape] points = tf.broadcast_to(points, points_batch_shape + [3]) skinning_weights = tf.broadcast_to(skinning_weights, points_batch_shape + [num_bones]) bones_batch_shape = shape.get_broadcasted_shape( bone_rotations.shape[:-3], bone_translations.shape[:-2]) bones_batch_shape = [dim_value(dim) for dim in bones_batch_shape] bone_rotations = tf.broadcast_to(bone_rotations, bones_batch_shape + [num_bones, 3, 3]) bone_translations = tf.broadcast_to(bone_translations, bones_batch_shape + [num_bones, 3]) points_batch_dims = points.shape.ndims - 1 bones_batch_dims = bone_rotations.shape.ndims - 3 points = tf.reshape(points, [1] * bones_batch_dims + points_batch_shape + [1, 3]) skinning_weights = tf.reshape(skinning_weights, [1] * bones_batch_dims + points_batch_shape + [num_bones, 1]) bone_rotations = tf.reshape( bone_rotations, bones_batch_shape + [1] * points_batch_dims + [num_bones, 3, 3]) bone_translations = tf.reshape( bone_translations, bones_batch_shape + [1] * points_batch_dims + [num_bones, 3]) transformed_points = rotation_matrix_3d.rotate( points, bone_rotations) + bone_translations weighted_points = tf.multiply(skinning_weights, transformed_points) blended_points = tf.reduce_sum(input_tensor=weighted_points, axis=-2) return blended_points # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow linear blend skinning functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def blend(points, skinning_weights, bone_rotations, bone_translations, name="linear_blend_skinning_blend"): """Transforms the points using Linear Blend Skinning. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible and allow transforming full 3D shapes at once. In the following, B1 to Bm are optional batch dimensions, which allow transforming multiple poses at once. Args: points: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. skinning_weights: A tensor of shape `[A1, ..., An, W]`, where the last dimension represents the skinning weights of each bone. bone_rotations: A tensor of shape `[B1, ..., Bm, W, 3, 3]`, which represents the 3d rotations applied to each bone. bone_translations: A tensor of shape `[B1, ..., Bm, W, 3]`, which represents the 3d translation vectors applied to each bone. name: A name for this op that defaults to "linear_blend_skinning_blend". Returns: A tensor of shape `[B1, ..., Bm, A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If the shape of the input tensors are not supported. """ with tf.name_scope(name): points = tf.convert_to_tensor(value=points) skinning_weights = tf.convert_to_tensor(value=skinning_weights) bone_rotations = tf.convert_to_tensor(value=bone_rotations) bone_translations = tf.convert_to_tensor(value=bone_translations) shape.check_static( tensor=points, tensor_name="points", has_dim_equals=(-1, 3)) shape.check_static( tensor=bone_rotations, tensor_name="bone_rotations", has_rank_greater_than=2, has_dim_equals=((-2, 3), (-1, 3))) shape.check_static( tensor=bone_translations, tensor_name="bone_translations", has_rank_greater_than=1, has_dim_equals=(-1, 3)) shape.compare_dimensions( tensors=(skinning_weights, bone_rotations), tensor_names=("skinning_weights", "bone_rotations"), axes=(-1, -3)) shape.compare_dimensions( tensors=(skinning_weights, bone_translations), tensor_names=("skinning_weights", "bone_translations"), axes=(-1, -2)) shape.compare_batch_dimensions( tensors=(points, skinning_weights), tensor_names=("points", "skinning_weights"), last_axes=(-2, -2), broadcast_compatible=True) shape.compare_batch_dimensions( tensors=(bone_rotations, bone_translations), tensor_names=("bone_rotations", "bone_translations"), last_axes=(-3, -2), broadcast_compatible=True) num_bones = skinning_weights.shape[-1] def dim_value(dim): return 1 if dim is None else tf.compat.dimension_value(dim) # TODO(b/148362025): factorize this block out points_batch_shape = shape.get_broadcasted_shape( points.shape[:-1], skinning_weights.shape[:-1]) points_batch_shape = [dim_value(dim) for dim in points_batch_shape] points = tf.broadcast_to(points, points_batch_shape + [3]) skinning_weights = tf.broadcast_to(skinning_weights, points_batch_shape + [num_bones]) bones_batch_shape = shape.get_broadcasted_shape( bone_rotations.shape[:-3], bone_translations.shape[:-2]) bones_batch_shape = [dim_value(dim) for dim in bones_batch_shape] bone_rotations = tf.broadcast_to(bone_rotations, bones_batch_shape + [num_bones, 3, 3]) bone_translations = tf.broadcast_to(bone_translations, bones_batch_shape + [num_bones, 3]) points_batch_dims = points.shape.ndims - 1 bones_batch_dims = bone_rotations.shape.ndims - 3 points = tf.reshape(points, [1] * bones_batch_dims + points_batch_shape + [1, 3]) skinning_weights = tf.reshape(skinning_weights, [1] * bones_batch_dims + points_batch_shape + [num_bones, 1]) bone_rotations = tf.reshape( bone_rotations, bones_batch_shape + [1] * points_batch_dims + [num_bones, 3, 3]) bone_translations = tf.reshape( bone_translations, bones_batch_shape + [1] * points_batch_dims + [num_bones, 3]) transformed_points = rotation_matrix_3d.rotate( points, bone_rotations) + bone_translations weighted_points = tf.multiply(skinning_weights, transformed_points) blended_points = tf.reduce_sum(input_tensor=weighted_points, axis=-2) return blended_points # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/geometry/transformation/look_at.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements OpenGL lookAt functionalities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def right_handed(camera_position, look_at, up_vector, name=None): """Builds a right handed look at view matrix. Note: In the following, A1 to An are optional batch dimensions. Args: camera_position: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the 3D position of the camera. look_at: A tensor of shape `[A1, ..., An, 3]`, with the last dimension storing the position where the camera is looking at. up_vector: A tensor of shape `[A1, ..., An, 3]`, where the last dimension defines the up vector of the camera. name: A name for this op. Defaults to 'right_handed'. Raises: ValueError: if the all the inputs are not of the same shape, or if any input of of an unsupported shape. Returns: A tensor of shape `[A1, ..., An, 4, 4]`, containing right handed look at matrices. """ with tf.compat.v1.name_scope(name, "right_handed", [camera_position, look_at, up_vector]): camera_position = tf.convert_to_tensor(value=camera_position) look_at = tf.convert_to_tensor(value=look_at) up_vector = tf.convert_to_tensor(value=up_vector) shape.check_static( tensor=camera_position, tensor_name="camera_position", has_dim_equals=(-1, 3)) shape.check_static( tensor=look_at, tensor_name="look_at", has_dim_equals=(-1, 3)) shape.check_static( tensor=up_vector, tensor_name="up_vector", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(camera_position, look_at, up_vector), last_axes=-2, tensor_names=("camera_position", "look_at", "up_vector"), broadcast_compatible=False) z_axis = tf.linalg.l2_normalize(look_at - camera_position, axis=-1) horizontal_axis = tf.linalg.l2_normalize( vector.cross(z_axis, up_vector), axis=-1) vertical_axis = vector.cross(horizontal_axis, z_axis) batch_shape = tf.shape(input=horizontal_axis)[:-1] zeros = tf.zeros( shape=tf.concat((batch_shape, (3,)), axis=-1), dtype=horizontal_axis.dtype) one = tf.ones( shape=tf.concat((batch_shape, (1,)), axis=-1), dtype=horizontal_axis.dtype) matrix = tf.concat( (horizontal_axis, -vector.dot(horizontal_axis, camera_position), vertical_axis, -vector.dot(vertical_axis, camera_position), -z_axis, vector.dot(z_axis, camera_position), zeros, one), axis=-1) matrix_shape = tf.shape(input=matrix) output_shape = tf.concat((matrix_shape[:-1], (4, 4)), axis=-1) return tf.reshape(matrix, shape=output_shape) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements OpenGL lookAt functionalities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def right_handed(camera_position, look_at, up_vector, name="right_handed"): """Builds a right handed look at view matrix. Note: In the following, A1 to An are optional batch dimensions. Args: camera_position: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the 3D position of the camera. look_at: A tensor of shape `[A1, ..., An, 3]`, with the last dimension storing the position where the camera is looking at. up_vector: A tensor of shape `[A1, ..., An, 3]`, where the last dimension defines the up vector of the camera. name: A name for this op. Defaults to 'right_handed'. Raises: ValueError: if the all the inputs are not of the same shape, or if any input of of an unsupported shape. Returns: A tensor of shape `[A1, ..., An, 4, 4]`, containing right handed look at matrices. """ with tf.name_scope(name): camera_position = tf.convert_to_tensor(value=camera_position) look_at = tf.convert_to_tensor(value=look_at) up_vector = tf.convert_to_tensor(value=up_vector) shape.check_static( tensor=camera_position, tensor_name="camera_position", has_dim_equals=(-1, 3)) shape.check_static( tensor=look_at, tensor_name="look_at", has_dim_equals=(-1, 3)) shape.check_static( tensor=up_vector, tensor_name="up_vector", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(camera_position, look_at, up_vector), last_axes=-2, tensor_names=("camera_position", "look_at", "up_vector"), broadcast_compatible=False) z_axis = tf.linalg.l2_normalize(look_at - camera_position, axis=-1) horizontal_axis = tf.linalg.l2_normalize( vector.cross(z_axis, up_vector), axis=-1) vertical_axis = vector.cross(horizontal_axis, z_axis) batch_shape = tf.shape(input=horizontal_axis)[:-1] zeros = tf.zeros( shape=tf.concat((batch_shape, (3,)), axis=-1), dtype=horizontal_axis.dtype) one = tf.ones( shape=tf.concat((batch_shape, (1,)), axis=-1), dtype=horizontal_axis.dtype) matrix = tf.concat( (horizontal_axis, -vector.dot(horizontal_axis, camera_position), vertical_axis, -vector.dot(vertical_axis, camera_position), -z_axis, vector.dot(z_axis, camera_position), zeros, one), axis=-1) matrix_shape = tf.shape(input=matrix) output_shape = tf.concat((matrix_shape[:-1], (4, 4)), axis=-1) return tf.reshape(matrix, shape=output_shape) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/geometry/transformation/quaternion.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow quaternion utility functions. A quaternion is written as $$q = xi + yj + zk + w$$, where $$i,j,k$$ forms the three bases of the imaginary part. The functions implemented in this file use the Hamilton convention where $$i^2 = j^2 = k^2 = ijk = -1$$. A quaternion is stored in a 4-D vector $$[x, y, z, w]^T$$. More details about Hamiltonian quaternions can be found on [this page.] (https://en.wikipedia.org/wiki/Quaternion) Note: Some of the functions expect normalized quaternions as inputs where $$x^2 + y^2 + z^2 + w^2 = 1$$. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def _build_quaternion_from_sines_and_cosines(sin_half_angles, cos_half_angles): """Builds a quaternion from sines and cosines of half Euler angles. Note: In the following, A1 to An are optional batch dimensions. Args: sin_half_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the sine of half Euler angles. cos_half_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the cosine of half Euler angles. Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. """ c1, c2, c3 = tf.unstack(cos_half_angles, axis=-1) s1, s2, s3 = tf.unstack(sin_half_angles, axis=-1) w = c1 * c2 * c3 + s1 * s2 * s3 x = -c1 * s2 * s3 + s1 * c2 * c3 y = c1 * s2 * c3 + s1 * c2 * s3 z = -s1 * s2 * c3 + c1 * c2 * s3 return tf.stack((x, y, z, w), axis=-1) def between_two_vectors_3d(vector1, vector2, name=None): """Computes quaternion over the shortest arc between two vectors. Result quaternion describes shortest geodesic rotation from vector1 to vector2. Note: In the following, A1 to An are optional batch dimensions. Args: vector1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vector. vector2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vector. name: A name for this op that defaults to "quaternion_between_two_vectors_3d". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `vector1` or `vector2` is not supported. """ with tf.compat.v1.name_scope(name, "quaternion_between_two_vectors_3d", [vector1, vector2]): vector1 = tf.convert_to_tensor(value=vector1) vector2 = tf.convert_to_tensor(value=vector2) shape.check_static( tensor=vector1, tensor_name="vector1", has_dim_equals=(-1, 3)) shape.check_static( tensor=vector2, tensor_name="vector2", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(vector1, vector2), last_axes=-2, broadcast_compatible=True) # Make sure that we are dealing with unit vectors. vector1 = tf.nn.l2_normalize(vector1, axis=-1) vector2 = tf.nn.l2_normalize(vector2, axis=-1) cos_theta = vector.dot(vector1, vector2) real_part = 1.0 + cos_theta axis = vector.cross(vector1, vector2) # Compute arbitrary antiparallel axes to rotate around in case of opposite # vectors. x, y, z = tf.split(vector1, (1, 1, 1), axis=-1) x_bigger_z = tf.abs(x) > tf.abs(z) x_bigger_z = tf.concat([x_bigger_z] * 3, axis=-1) antiparallel_axis = tf.compat.v1.where( x_bigger_z, tf.concat((-y, x, tf.zeros_like(z)), axis=-1), tf.concat((tf.zeros_like(x), -z, y), axis=-1)) # Compute rotation between two vectors. is_antiparallel = real_part < 1e-6 is_antiparallel = tf.concat([is_antiparallel] * 4, axis=-1) rot = tf.compat.v1.where( is_antiparallel, tf.concat((antiparallel_axis, tf.zeros_like(real_part)), axis=-1), tf.concat((axis, real_part), axis=-1)) return tf.nn.l2_normalize(rot, axis=-1) def conjugate(quaternion, name=None): """Computes the conjugate of a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_conjugate". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.compat.v1.name_scope(name, "quaternion_conjugate", [quaternion]): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) xyz, w = tf.split(quaternion, (3, 1), axis=-1) return tf.concat((-xyz, w), axis=-1) def from_axis_angle(axis, angle, name=None): """Converts an axis-angle representation to a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents an angle. name: A name for this op that defaults to "quaternion_from_axis_angle". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.compat.v1.name_scope(name, "quaternion_from_axis_angle", [axis, angle]): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) half_angle = 0.5 * angle w = tf.cos(half_angle) xyz = tf.sin(half_angle) * axis return tf.concat((xyz, w), axis=-1) def from_euler(angles, name=None): """Converts an Euler angle representation to a quaternion. Note: Uses the z-y-x rotation convention (Tait-Bryan angles). Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[..., 0]` is the angle about `x` in radians, `[..., 1]` is the angle about `y` in radians and `[..., 2]` is the angle about `z` in radians. name: A name for this op that defaults to "quaternion_from_euler". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.compat.v1.name_scope(name, "quaternion_from_euler", [angles]): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) half_angles = angles / 2.0 cos_half_angles = tf.cos(half_angles) sin_half_angles = tf.sin(half_angles) return _build_quaternion_from_sines_and_cosines(sin_half_angles, cos_half_angles) def from_euler_with_small_angles_approximation(angles, name=None): r"""Converts small Euler angles to quaternions. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: Uses the z-y-x rotation convention (Tait-Bryan angles). Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[..., 0]` is the angle about `x` in radians, `[..., 1]` is the angle about `y` in radians and `[..., 2]` is the angle about `z` in radians. name: A name for this op that defaults to "quaternion_from_euler". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.compat.v1.name_scope(name, "quaternion_from_euler", [angles]): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) half_angles = angles / 2.0 cos_half_angles = 1.0 - 0.5 * half_angles * half_angles sin_half_angles = half_angles quaternion = _build_quaternion_from_sines_and_cosines( sin_half_angles, cos_half_angles) # We need to normalize the quaternion due to the small angle approximation. return tf.nn.l2_normalize(quaternion, axis=-1) def from_rotation_matrix(rotation_matrix, name=None): """Converts a rotation matrix representation to a quaternion. Warning: This function is not smooth everywhere. Note: In the following, A1 to An are optional batch dimensions. Args: rotation_matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a rotation matrix. name: A name for this op that defaults to "quaternion_from_rotation_matrix". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `rotation_matrix` is not supported. """ with tf.compat.v1.name_scope(name, "quaternion_from_rotation_matrix", [rotation_matrix]): rotation_matrix = tf.convert_to_tensor(value=rotation_matrix) shape.check_static( tensor=rotation_matrix, tensor_name="rotation_matrix", has_rank_greater_than=1, has_dim_equals=((-1, 3), (-2, 3))) rotation_matrix = rotation_matrix_3d.assert_rotation_matrix_normalized( rotation_matrix) trace = tf.linalg.trace(rotation_matrix) eps_addition = asserts.select_eps_for_addition(rotation_matrix.dtype) rows = tf.unstack(rotation_matrix, axis=-2) entries = [tf.unstack(row, axis=-1) for row in rows] def tr_positive(): sq = tf.sqrt(trace + 1.0) * 2. # sq = 4 * qw. qw = 0.25 * sq qx = safe_ops.safe_unsigned_div(entries[2][1] - entries[1][2], sq) qy = safe_ops.safe_unsigned_div(entries[0][2] - entries[2][0], sq) qz = safe_ops.safe_unsigned_div(entries[1][0] - entries[0][1], sq) return tf.stack((qx, qy, qz, qw), axis=-1) def cond_1(): sq = tf.sqrt(1.0 + entries[0][0] - entries[1][1] - entries[2][2] + eps_addition) * 2. # sq = 4 * qx. qw = safe_ops.safe_unsigned_div(entries[2][1] - entries[1][2], sq) qx = 0.25 * sq qy = safe_ops.safe_unsigned_div(entries[0][1] + entries[1][0], sq) qz = safe_ops.safe_unsigned_div(entries[0][2] + entries[2][0], sq) return tf.stack((qx, qy, qz, qw), axis=-1) def cond_2(): sq = tf.sqrt(1.0 + entries[1][1] - entries[0][0] - entries[2][2] + eps_addition) * 2. # sq = 4 * qy. qw = safe_ops.safe_unsigned_div(entries[0][2] - entries[2][0], sq) qx = safe_ops.safe_unsigned_div(entries[0][1] + entries[1][0], sq) qy = 0.25 * sq qz = safe_ops.safe_unsigned_div(entries[1][2] + entries[2][1], sq) return tf.stack((qx, qy, qz, qw), axis=-1) def cond_3(): sq = tf.sqrt(1.0 + entries[2][2] - entries[0][0] - entries[1][1] + eps_addition) * 2. # sq = 4 * qz. qw = safe_ops.safe_unsigned_div(entries[1][0] - entries[0][1], sq) qx = safe_ops.safe_unsigned_div(entries[0][2] + entries[2][0], sq) qy = safe_ops.safe_unsigned_div(entries[1][2] + entries[2][1], sq) qz = 0.25 * sq return tf.stack((qx, qy, qz, qw), axis=-1) def cond_idx(cond): cond = tf.expand_dims(cond, -1) cond = tf.tile(cond, [1] * (rotation_matrix.shape.ndims - 2) + [4]) return cond where_2 = tf.compat.v1.where( cond_idx(entries[1][1] > entries[2][2]), cond_2(), cond_3()) where_1 = tf.compat.v1.where( cond_idx((entries[0][0] > entries[1][1]) & (entries[0][0] > entries[2][2])), cond_1(), where_2) quat = tf.compat.v1.where(cond_idx(trace > 0), tr_positive(), where_1) return quat def inverse(quaternion, name=None): """Computes the inverse of a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_inverse". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.compat.v1.name_scope(name, "quaternion_inverse", [quaternion]): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) squared_norm = tf.reduce_sum( input_tensor=tf.square(quaternion), axis=-1, keepdims=True) return safe_ops.safe_unsigned_div(conjugate(quaternion), squared_norm) def is_normalized(quaternion, atol=1e-3, name=None): """Determines if quaternion is normalized quaternion or not. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. atol: The absolute tolerance parameter. name: A name for this op that defaults to "quaternion_is_normalized". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]`, where False indicates that the quaternion is not normalized. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.compat.v1.name_scope(name, "quaternion_is_normalized", [quaternion]): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) norms = tf.norm(tensor=quaternion, axis=-1, keepdims=True) return tf.compat.v1.where( tf.abs(norms - 1.) < atol, tf.ones_like(norms, dtype=bool), tf.zeros_like(norms, dtype=bool)) def normalize(quaternion, eps=1e-12, name=None): """Normalizes a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. eps: A lower bound value for the norm that defaults to 1e-12. name: A name for this op that defaults to "quaternion_normalize". Returns: A N-D tensor of shape `[?, ..., ?, 1]` where the quaternion elements have been normalized. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.compat.v1.name_scope(name, "quaternion_normalize", [quaternion]): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) return tf.math.l2_normalize(quaternion, axis=-1, epsilon=eps) def multiply(quaternion1, quaternion2, name=None): """Multiplies two quaternions. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion1: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. quaternion2: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. name: A name for this op that defaults to "quaternion_multiply". Returns: A tensor of shape `[A1, ..., An, 4]` representing quaternions. Raises: ValueError: If the shape of `quaternion1` or `quaternion2` is not supported. """ with tf.compat.v1.name_scope(name, "quaternion_multiply", [quaternion1, quaternion2]): quaternion1 = tf.convert_to_tensor(value=quaternion1) quaternion2 = tf.convert_to_tensor(value=quaternion2) shape.check_static( tensor=quaternion1, tensor_name="quaternion1", has_dim_equals=(-1, 4)) shape.check_static( tensor=quaternion2, tensor_name="quaternion2", has_dim_equals=(-1, 4)) x1, y1, z1, w1 = tf.unstack(quaternion1, axis=-1) x2, y2, z2, w2 = tf.unstack(quaternion2, axis=-1) x = x1 * w2 + y1 * z2 - z1 * y2 + w1 * x2 y = -x1 * z2 + y1 * w2 + z1 * x2 + w1 * y2 z = x1 * y2 - y1 * x2 + z1 * w2 + w1 * z2 w = -x1 * x2 - y1 * y2 - z1 * z2 + w1 * w2 return tf.stack((x, y, z, w), axis=-1) def normalized_random_uniform(quaternion_shape, name=None): """Random normalized quaternion following a uniform distribution law on SO(3). Args: quaternion_shape: A list representing the shape of the output tensor. name: A name for this op that defaults to "quaternion_normalized_random_uniform". Returns: A tensor of shape `[quaternion_shape[0],...,quaternion_shape[-1], 4]` representing random normalized quaternions. """ with tf.compat.v1.name_scope(name, "quaternion_normalized_random_uniform", [quaternion_shape]): quaternion_shape = tf.convert_to_tensor(value=quaternion_shape, dtype=tf.int32) quaternion_shape = tf.concat((quaternion_shape, tf.constant([4])), axis=0) random_normal = tf.random.normal(quaternion_shape) return normalize(random_normal) def normalized_random_uniform_initializer(): """Random unit quaternion initializer.""" # Since variable initializers must take `shape` as input, we cannot prevent # a clash between util.shape and the argument here. Therefore we have to # disable redefined-outer-name for this function. # pylint: disable=redefined-outer-name def _initializer(shape, dtype=tf.float32, partition_info=None): """Generate a random normalized quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: shape: A list representing the shape of the output. The last entry of the list must be `4`. dtype: type of the output (tf.float32 is the only type supported). partition_info: how the variable is partitioned (not used). Returns: A tensor of shape `[A1, ..., An, 4]` representing normalized quaternions. Raises: ValueError: If `shape` or `dtype` are not supported. """ del partition_info # unused if dtype != tf.float32: raise ValueError("'dtype' must be tf.float32.") if shape[-1] != 4: raise ValueError("Last dimension of 'shape' must be 4.") return normalized_random_uniform(shape[:-1]) return _initializer # pylint: enable=redefined-outer-name def rotate(point, quaternion, name=None): """Rotates a point using a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If the shape of `point` or `quaternion` is not supported. """ with tf.compat.v1.name_scope(name, "quaternion_rotate", [point, quaternion]): point = tf.convert_to_tensor(value=point) quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) shape.compare_batch_dimensions( tensors=(point, quaternion), last_axes=-2, broadcast_compatible=True) quaternion = asserts.assert_normalized(quaternion) padding = [[0, 0] for _ in range(point.shape.ndims)] padding[-1][-1] = 1 point = tf.pad(tensor=point, paddings=padding, mode="CONSTANT") point = multiply(quaternion, point) point = multiply(point, conjugate(quaternion)) xyz, _ = tf.split(point, (3, 1), axis=-1) return xyz def relative_angle(quaternion1, quaternion2, name=None): r"""Computes the unsigned relative rotation angle between 2 unit quaternions. Given two normalized quanternions $$\mathbf{q}_1$$ and $$\mathbf{q}_2$$, the relative angle is computed as $$\theta = 2\arccos(\mathbf{q}_1^T\mathbf{q}_2)$$. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion1: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. quaternion2: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_relative_angle". Returns: A tensor of shape `[A1, ..., An, 1]` where the last dimension represents rotation angles in the range [0.0, pi]. Raises: ValueError: If the shape of `quaternion1` or `quaternion2` is not supported. """ with (tf.compat.v1.name_scope(name, "quaternion_relative_angle", [quaternion1, quaternion2])): quaternion1 = tf.convert_to_tensor(value=quaternion1) quaternion2 = tf.convert_to_tensor(value=quaternion2) shape.check_static( tensor=quaternion1, tensor_name="quaternion1", has_dim_equals=(-1, 4)) shape.check_static( tensor=quaternion2, tensor_name="quaternion2", has_dim_equals=(-1, 4)) quaternion1 = asserts.assert_normalized(quaternion1) quaternion2 = asserts.assert_normalized(quaternion2) dot_product = vector.dot(quaternion1, quaternion2, keepdims=False) # Ensure dot product is in range [-1. 1]. eps_dot_prod = 4.0 * asserts.select_eps_for_addition(dot_product.dtype) dot_product = safe_ops.safe_shrink( dot_product, -1.0, 1.0, False, eps=eps_dot_prod) return 2.0 * tf.acos(tf.abs(dot_product)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow quaternion utility functions. A quaternion is written as $$q = xi + yj + zk + w$$, where $$i,j,k$$ forms the three bases of the imaginary part. The functions implemented in this file use the Hamilton convention where $$i^2 = j^2 = k^2 = ijk = -1$$. A quaternion is stored in a 4-D vector $$[x, y, z, w]^T$$. More details about Hamiltonian quaternions can be found on [this page.] (https://en.wikipedia.org/wiki/Quaternion) Note: Some of the functions expect normalized quaternions as inputs where $$x^2 + y^2 + z^2 + w^2 = 1$$. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def _build_quaternion_from_sines_and_cosines(sin_half_angles, cos_half_angles): """Builds a quaternion from sines and cosines of half Euler angles. Note: In the following, A1 to An are optional batch dimensions. Args: sin_half_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the sine of half Euler angles. cos_half_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the cosine of half Euler angles. Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. """ c1, c2, c3 = tf.unstack(cos_half_angles, axis=-1) s1, s2, s3 = tf.unstack(sin_half_angles, axis=-1) w = c1 * c2 * c3 + s1 * s2 * s3 x = -c1 * s2 * s3 + s1 * c2 * c3 y = c1 * s2 * c3 + s1 * c2 * s3 z = -s1 * s2 * c3 + c1 * c2 * s3 return tf.stack((x, y, z, w), axis=-1) def between_two_vectors_3d(vector1, vector2, name="quaternion_between_two_vectors_3d"): """Computes quaternion over the shortest arc between two vectors. Result quaternion describes shortest geodesic rotation from vector1 to vector2. Note: In the following, A1 to An are optional batch dimensions. Args: vector1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vector. vector2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vector. name: A name for this op that defaults to "quaternion_between_two_vectors_3d". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `vector1` or `vector2` is not supported. """ with tf.name_scope(name): vector1 = tf.convert_to_tensor(value=vector1) vector2 = tf.convert_to_tensor(value=vector2) shape.check_static( tensor=vector1, tensor_name="vector1", has_dim_equals=(-1, 3)) shape.check_static( tensor=vector2, tensor_name="vector2", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(vector1, vector2), last_axes=-2, broadcast_compatible=True) # Make sure that we are dealing with unit vectors. vector1 = tf.nn.l2_normalize(vector1, axis=-1) vector2 = tf.nn.l2_normalize(vector2, axis=-1) cos_theta = vector.dot(vector1, vector2) real_part = 1.0 + cos_theta axis = vector.cross(vector1, vector2) # Compute arbitrary antiparallel axes to rotate around in case of opposite # vectors. x, y, z = tf.split(vector1, (1, 1, 1), axis=-1) x_bigger_z = tf.abs(x) > tf.abs(z) x_bigger_z = tf.concat([x_bigger_z] * 3, axis=-1) antiparallel_axis = tf.where(x_bigger_z, tf.concat((-y, x, tf.zeros_like(z)), axis=-1), tf.concat((tf.zeros_like(x), -z, y), axis=-1)) # Compute rotation between two vectors. is_antiparallel = real_part < 1e-6 is_antiparallel = tf.concat([is_antiparallel] * 4, axis=-1) rot = tf.where( is_antiparallel, tf.concat((antiparallel_axis, tf.zeros_like(real_part)), axis=-1), tf.concat((axis, real_part), axis=-1)) return tf.nn.l2_normalize(rot, axis=-1) def conjugate(quaternion, name="quaternion_conjugate"): """Computes the conjugate of a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_conjugate". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) xyz, w = tf.split(quaternion, (3, 1), axis=-1) return tf.concat((-xyz, w), axis=-1) def from_axis_angle(axis, angle, name="quaternion_from_axis_angle"): """Converts an axis-angle representation to a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents an angle. name: A name for this op that defaults to "quaternion_from_axis_angle". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.name_scope(name): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) half_angle = 0.5 * angle w = tf.cos(half_angle) xyz = tf.sin(half_angle) * axis return tf.concat((xyz, w), axis=-1) def from_euler(angles, name="quaternion_from_euler"): """Converts an Euler angle representation to a quaternion. Note: Uses the z-y-x rotation convention (Tait-Bryan angles). Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[..., 0]` is the angle about `x` in radians, `[..., 1]` is the angle about `y` in radians and `[..., 2]` is the angle about `z` in radians. name: A name for this op that defaults to "quaternion_from_euler". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) half_angles = angles / 2.0 cos_half_angles = tf.cos(half_angles) sin_half_angles = tf.sin(half_angles) return _build_quaternion_from_sines_and_cosines(sin_half_angles, cos_half_angles) def from_euler_with_small_angles_approximation(angles, name="quaternion_from_euler"): r"""Converts small Euler angles to quaternions. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: Uses the z-y-x rotation convention (Tait-Bryan angles). Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[..., 0]` is the angle about `x` in radians, `[..., 1]` is the angle about `y` in radians and `[..., 2]` is the angle about `z` in radians. name: A name for this op that defaults to "quaternion_from_euler". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) half_angles = angles / 2.0 cos_half_angles = 1.0 - 0.5 * half_angles * half_angles sin_half_angles = half_angles quaternion = _build_quaternion_from_sines_and_cosines( sin_half_angles, cos_half_angles) # We need to normalize the quaternion due to the small angle approximation. return tf.nn.l2_normalize(quaternion, axis=-1) def from_rotation_matrix(rotation_matrix, name="quaternion_from_rotation_matrix"): """Converts a rotation matrix representation to a quaternion. Warning: This function is not smooth everywhere. Note: In the following, A1 to An are optional batch dimensions. Args: rotation_matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a rotation matrix. name: A name for this op that defaults to "quaternion_from_rotation_matrix". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `rotation_matrix` is not supported. """ with tf.name_scope(name): rotation_matrix = tf.convert_to_tensor(value=rotation_matrix) shape.check_static( tensor=rotation_matrix, tensor_name="rotation_matrix", has_rank_greater_than=1, has_dim_equals=((-1, 3), (-2, 3))) rotation_matrix = rotation_matrix_3d.assert_rotation_matrix_normalized( rotation_matrix) trace = tf.linalg.trace(rotation_matrix) eps_addition = asserts.select_eps_for_addition(rotation_matrix.dtype) rows = tf.unstack(rotation_matrix, axis=-2) entries = [tf.unstack(row, axis=-1) for row in rows] def tr_positive(): sq = tf.sqrt(trace + 1.0) * 2. # sq = 4 * qw. qw = 0.25 * sq qx = safe_ops.safe_unsigned_div(entries[2][1] - entries[1][2], sq) qy = safe_ops.safe_unsigned_div(entries[0][2] - entries[2][0], sq) qz = safe_ops.safe_unsigned_div(entries[1][0] - entries[0][1], sq) return tf.stack((qx, qy, qz, qw), axis=-1) def cond_1(): sq = tf.sqrt(1.0 + entries[0][0] - entries[1][1] - entries[2][2] + eps_addition) * 2. # sq = 4 * qx. qw = safe_ops.safe_unsigned_div(entries[2][1] - entries[1][2], sq) qx = 0.25 * sq qy = safe_ops.safe_unsigned_div(entries[0][1] + entries[1][0], sq) qz = safe_ops.safe_unsigned_div(entries[0][2] + entries[2][0], sq) return tf.stack((qx, qy, qz, qw), axis=-1) def cond_2(): sq = tf.sqrt(1.0 + entries[1][1] - entries[0][0] - entries[2][2] + eps_addition) * 2. # sq = 4 * qy. qw = safe_ops.safe_unsigned_div(entries[0][2] - entries[2][0], sq) qx = safe_ops.safe_unsigned_div(entries[0][1] + entries[1][0], sq) qy = 0.25 * sq qz = safe_ops.safe_unsigned_div(entries[1][2] + entries[2][1], sq) return tf.stack((qx, qy, qz, qw), axis=-1) def cond_3(): sq = tf.sqrt(1.0 + entries[2][2] - entries[0][0] - entries[1][1] + eps_addition) * 2. # sq = 4 * qz. qw = safe_ops.safe_unsigned_div(entries[1][0] - entries[0][1], sq) qx = safe_ops.safe_unsigned_div(entries[0][2] + entries[2][0], sq) qy = safe_ops.safe_unsigned_div(entries[1][2] + entries[2][1], sq) qz = 0.25 * sq return tf.stack((qx, qy, qz, qw), axis=-1) def cond_idx(cond): cond = tf.expand_dims(cond, -1) cond = tf.tile(cond, [1] * (rotation_matrix.shape.ndims - 2) + [4]) return cond where_2 = tf.where( cond_idx(entries[1][1] > entries[2][2]), cond_2(), cond_3()) where_1 = tf.where( cond_idx((entries[0][0] > entries[1][1]) & (entries[0][0] > entries[2][2])), cond_1(), where_2) quat = tf.where(cond_idx(trace > 0), tr_positive(), where_1) return quat def inverse(quaternion, name="quaternion_inverse"): """Computes the inverse of a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_inverse". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) squared_norm = tf.reduce_sum( input_tensor=tf.square(quaternion), axis=-1, keepdims=True) return safe_ops.safe_unsigned_div(conjugate(quaternion), squared_norm) def is_normalized(quaternion, atol=1e-3, name="quaternion_is_normalized"): """Determines if quaternion is normalized quaternion or not. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. atol: The absolute tolerance parameter. name: A name for this op that defaults to "quaternion_is_normalized". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]`, where False indicates that the quaternion is not normalized. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) norms = tf.norm(tensor=quaternion, axis=-1, keepdims=True) return tf.where( tf.abs(norms - 1.) < atol, tf.ones_like(norms, dtype=bool), tf.zeros_like(norms, dtype=bool)) def normalize(quaternion, eps=1e-12, name="quaternion_normalize"): """Normalizes a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. eps: A lower bound value for the norm that defaults to 1e-12. name: A name for this op that defaults to "quaternion_normalize". Returns: A N-D tensor of shape `[?, ..., ?, 1]` where the quaternion elements have been normalized. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) return tf.math.l2_normalize(quaternion, axis=-1, epsilon=eps) def multiply(quaternion1, quaternion2, name="quaternion_multiply"): """Multiplies two quaternions. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion1: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. quaternion2: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. name: A name for this op that defaults to "quaternion_multiply". Returns: A tensor of shape `[A1, ..., An, 4]` representing quaternions. Raises: ValueError: If the shape of `quaternion1` or `quaternion2` is not supported. """ with tf.name_scope(name): quaternion1 = tf.convert_to_tensor(value=quaternion1) quaternion2 = tf.convert_to_tensor(value=quaternion2) shape.check_static( tensor=quaternion1, tensor_name="quaternion1", has_dim_equals=(-1, 4)) shape.check_static( tensor=quaternion2, tensor_name="quaternion2", has_dim_equals=(-1, 4)) x1, y1, z1, w1 = tf.unstack(quaternion1, axis=-1) x2, y2, z2, w2 = tf.unstack(quaternion2, axis=-1) x = x1 * w2 + y1 * z2 - z1 * y2 + w1 * x2 y = -x1 * z2 + y1 * w2 + z1 * x2 + w1 * y2 z = x1 * y2 - y1 * x2 + z1 * w2 + w1 * z2 w = -x1 * x2 - y1 * y2 - z1 * z2 + w1 * w2 return tf.stack((x, y, z, w), axis=-1) def normalized_random_uniform(quaternion_shape, name="quaternion_normalized_random_uniform"): """Random normalized quaternion following a uniform distribution law on SO(3). Args: quaternion_shape: A list representing the shape of the output tensor. name: A name for this op that defaults to "quaternion_normalized_random_uniform". Returns: A tensor of shape `[quaternion_shape[0],...,quaternion_shape[-1], 4]` representing random normalized quaternions. """ with tf.name_scope(name): quaternion_shape = tf.convert_to_tensor( value=quaternion_shape, dtype=tf.int32) quaternion_shape = tf.concat((quaternion_shape, tf.constant([4])), axis=0) random_normal = tf.random.normal(quaternion_shape) return normalize(random_normal) def normalized_random_uniform_initializer(): """Random unit quaternion initializer.""" # Since variable initializers must take `shape` as input, we cannot prevent # a clash between util.shape and the argument here. Therefore we have to # disable redefined-outer-name for this function. # pylint: disable=redefined-outer-name def _initializer(shape, dtype=tf.float32, partition_info=None): """Generate a random normalized quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: shape: A list representing the shape of the output. The last entry of the list must be `4`. dtype: type of the output (tf.float32 is the only type supported). partition_info: how the variable is partitioned (not used). Returns: A tensor of shape `[A1, ..., An, 4]` representing normalized quaternions. Raises: ValueError: If `shape` or `dtype` are not supported. """ del partition_info # unused if dtype != tf.float32: raise ValueError("'dtype' must be tf.float32.") if shape[-1] != 4: raise ValueError("Last dimension of 'shape' must be 4.") return normalized_random_uniform(shape[:-1]) return _initializer # pylint: enable=redefined-outer-name def rotate(point, quaternion, name="quaternion_rotate"): """Rotates a point using a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If the shape of `point` or `quaternion` is not supported. """ with tf.name_scope(name): point = tf.convert_to_tensor(value=point) quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) shape.compare_batch_dimensions( tensors=(point, quaternion), last_axes=-2, broadcast_compatible=True) quaternion = asserts.assert_normalized(quaternion) padding = [[0, 0] for _ in range(point.shape.ndims)] padding[-1][-1] = 1 point = tf.pad(tensor=point, paddings=padding, mode="CONSTANT") point = multiply(quaternion, point) point = multiply(point, conjugate(quaternion)) xyz, _ = tf.split(point, (3, 1), axis=-1) return xyz def relative_angle(quaternion1, quaternion2, name="quaternion_relative_angle"): r"""Computes the unsigned relative rotation angle between 2 unit quaternions. Given two normalized quanternions $$\mathbf{q}_1$$ and $$\mathbf{q}_2$$, the relative angle is computed as $$\theta = 2\arccos(\mathbf{q}_1^T\mathbf{q}_2)$$. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion1: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. quaternion2: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_relative_angle". Returns: A tensor of shape `[A1, ..., An, 1]` where the last dimension represents rotation angles in the range [0.0, pi]. Raises: ValueError: If the shape of `quaternion1` or `quaternion2` is not supported. """ with tf.name_scope(name): quaternion1 = tf.convert_to_tensor(value=quaternion1) quaternion2 = tf.convert_to_tensor(value=quaternion2) shape.check_static( tensor=quaternion1, tensor_name="quaternion1", has_dim_equals=(-1, 4)) shape.check_static( tensor=quaternion2, tensor_name="quaternion2", has_dim_equals=(-1, 4)) quaternion1 = asserts.assert_normalized(quaternion1) quaternion2 = asserts.assert_normalized(quaternion2) dot_product = vector.dot(quaternion1, quaternion2, keepdims=False) # Ensure dot product is in range [-1. 1]. eps_dot_prod = 4.0 * asserts.select_eps_for_addition(dot_product.dtype) dot_product = safe_ops.safe_shrink( dot_product, -1.0, 1.0, False, eps=eps_dot_prod) return 2.0 * tf.acos(tf.abs(dot_product)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/geometry/transformation/rotation_matrix_2d.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""This module implements 2d rotation matrix functionalities. Given an angle of rotation $$\theta$$ a 2d rotation matrix can be expressed as $$ \mathbf{R} = \begin{bmatrix} \cos(\theta) & -\sin(\theta) \\ \sin(\theta) & \cos(\theta) \end{bmatrix}. $$ More details rotation matrices can be found on [this page.] (https://en.wikipedia.org/wiki/Rotation_matrix) Note: This matrix rotates points in the $$xy$$-plane counterclockwise. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def from_euler(angle, name=None): r"""Converts an angle to a 2d rotation matrix. Converts an angle $$\theta$$ to a 2d rotation matrix following the equation $$ \mathbf{R} = \begin{bmatrix} \cos(\theta) & -\sin(\theta) \\ \sin(\theta) & \cos(\theta) \end{bmatrix}. $$ Note: The resulting matrix rotates points in the $$xy$$-plane counterclockwise. Note: In the following, A1 to An are optional batch dimensions. Args: angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents an angle in radians. name: A name for this op that defaults to "rotation_matrix_2d_from_euler_angle". Returns: A tensor of shape `[A1, ..., An, 2, 2]`, where the last dimension represents a 2d rotation matrix. Raises: ValueError: If the shape of `angle` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_2d_from_euler_angle", [angle]): angle = tf.convert_to_tensor(value=angle) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) cos_angle = tf.cos(angle) sin_angle = tf.sin(angle) matrix = tf.stack((cos_angle, -sin_angle, sin_angle, cos_angle), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=angle)[:-1], (2, 2)), axis=-1) return tf.reshape(matrix, shape=output_shape) def from_euler_with_small_angles_approximation(angles, name=None): r"""Converts an angle to a 2d rotation matrix under the small angle assumption. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. The 2d rotation matrix will then be approximated as $$ \mathbf{R} = \begin{bmatrix} 1.0 - 0.5\theta^2 & -\theta \\ \theta & 1.0 - 0.5\theta^2 \end{bmatrix}. $$ In the current implementation, the smallness of the angles is not verified. Note: The resulting matrix rotates points in the $$xy$$-plane counterclockwise. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a small angle in radians. name: A name for this op that defaults to "rotation_matrix_2d_from_euler_with_small_angles_approximation". Returns: A tensor of shape `[A1, ..., An, 2, 2]`, where the last dimension represents a 2d rotation matrix. Raises: ValueError: If the shape of `angle` is not supported. """ with tf.compat.v1.name_scope( name, "rotation_matrix_2d_from_euler_with_small_angles_approximation", [angles]): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 1)) cos_angle = 1.0 - 0.5 * angles * angles sin_angle = angles matrix = tf.stack((cos_angle, -sin_angle, sin_angle, cos_angle), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=angles)[:-1], (2, 2)), axis=-1) return tf.reshape(matrix, shape=output_shape) def inverse(matrix, name=None): """Computes the inverse of a 2D rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 2, 2]`, where the last two dimensions represent a 2d rotation matrix. name: A name for this op that defaults to "rotation_matrix_2d_inverse". Returns: A tensor of shape `[A1, ..., An, 2, 2]`, where the last dimension represents a 2d rotation matrix. Raises: ValueError: If the shape of `matrix` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_2d_inverse", [matrix]): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 2), (-1, 2))) ndims = matrix.shape.ndims perm = list(range(ndims - 2)) + [ndims - 1, ndims - 2] return tf.transpose(a=matrix, perm=perm) def is_valid(matrix, atol=1e-3, name=None): r"""Determines if a matrix is a valid rotation matrix. Determines if a matrix $$\mathbf{R}$$ is a valid rotation matrix by checking that $$\mathbf{R}^T\mathbf{R} = \mathbf{I}$$ and $$\det(\mathbf{R}) = 1$$. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 2, 2]`, where the last two dimensions represent a 2d rotation matrix. atol: The absolute tolerance parameter. name: A name for this op that defaults to "rotation_matrix_2d_is_valid". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]` where False indicates that the input is not a valid rotation matrix. """ with tf.compat.v1.name_scope(name, "rotation_matrix_2d_is_valid", [matrix]): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 2), (-1, 2))) return rotation_matrix_common.is_valid(matrix, atol) def rotate(point, matrix, name=None): """Rotates a 2d point using a 2d rotation matrix. Note: In the following, A1 to An are optional batch dimensions, which must be identical. Args: point: A tensor of shape `[A1, ..., An, 2]`, where the last dimension represents a 2d point. matrix: A tensor of shape `[A1, ..., An, 2, 2]`, where the last two dimensions represent a 2d rotation matrix. name: A name for this op that defaults to "rotation_matrix_2d_rotate". Returns: A tensor of shape `[A1, ..., An, 2]`, where the last dimension represents a 2d point. Raises: ValueError: If the shape of `point` or `matrix` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_2d_rotate", [point, matrix]): point = tf.convert_to_tensor(value=point) matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 2)) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 2), (-1, 2))) shape.compare_batch_dimensions( tensors=(point, matrix), tensor_names=("point", "matrix"), last_axes=(-2, -3), broadcast_compatible=True) point = tf.expand_dims(point, axis=-1) common_batch_shape = shape.get_broadcasted_shape( point.shape[:-2], matrix.shape[:-2]) def dim_value(dim): return 1 if dim is None else tf.compat.v1.dimension_value(dim) common_batch_shape = [dim_value(dim) for dim in common_batch_shape] point = tf.broadcast_to(point, common_batch_shape + [2, 1]) matrix = tf.broadcast_to(matrix, common_batch_shape + [2, 2]) rotated_point = tf.matmul(matrix, point) return tf.squeeze(rotated_point, axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""This module implements 2d rotation matrix functionalities. Given an angle of rotation $$\theta$$ a 2d rotation matrix can be expressed as $$ \mathbf{R} = \begin{bmatrix} \cos(\theta) & -\sin(\theta) \\ \sin(\theta) & \cos(\theta) \end{bmatrix}. $$ More details rotation matrices can be found on [this page.] (https://en.wikipedia.org/wiki/Rotation_matrix) Note: This matrix rotates points in the $$xy$$-plane counterclockwise. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def from_euler(angle, name="rotation_matrix_2d_from_euler_angle"): r"""Converts an angle to a 2d rotation matrix. Converts an angle $$\theta$$ to a 2d rotation matrix following the equation $$ \mathbf{R} = \begin{bmatrix} \cos(\theta) & -\sin(\theta) \\ \sin(\theta) & \cos(\theta) \end{bmatrix}. $$ Note: The resulting matrix rotates points in the $$xy$$-plane counterclockwise. Note: In the following, A1 to An are optional batch dimensions. Args: angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents an angle in radians. name: A name for this op that defaults to "rotation_matrix_2d_from_euler_angle". Returns: A tensor of shape `[A1, ..., An, 2, 2]`, where the last dimension represents a 2d rotation matrix. Raises: ValueError: If the shape of `angle` is not supported. """ with tf.name_scope(name): angle = tf.convert_to_tensor(value=angle) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) cos_angle = tf.cos(angle) sin_angle = tf.sin(angle) matrix = tf.stack((cos_angle, -sin_angle, sin_angle, cos_angle), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=angle)[:-1], (2, 2)), axis=-1) return tf.reshape(matrix, shape=output_shape) def from_euler_with_small_angles_approximation( angles, name="rotation_matrix_2d_from_euler_with_small_angles_approximation"): r"""Converts an angle to a 2d rotation matrix under the small angle assumption. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. The 2d rotation matrix will then be approximated as $$ \mathbf{R} = \begin{bmatrix} 1.0 - 0.5\theta^2 & -\theta \\ \theta & 1.0 - 0.5\theta^2 \end{bmatrix}. $$ In the current implementation, the smallness of the angles is not verified. Note: The resulting matrix rotates points in the $$xy$$-plane counterclockwise. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a small angle in radians. name: A name for this op that defaults to "rotation_matrix_2d_from_euler_with_small_angles_approximation". Returns: A tensor of shape `[A1, ..., An, 2, 2]`, where the last dimension represents a 2d rotation matrix. Raises: ValueError: If the shape of `angle` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 1)) cos_angle = 1.0 - 0.5 * angles * angles sin_angle = angles matrix = tf.stack((cos_angle, -sin_angle, sin_angle, cos_angle), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=angles)[:-1], (2, 2)), axis=-1) return tf.reshape(matrix, shape=output_shape) def inverse(matrix, name="rotation_matrix_2d_inverse"): """Computes the inverse of a 2D rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 2, 2]`, where the last two dimensions represent a 2d rotation matrix. name: A name for this op that defaults to "rotation_matrix_2d_inverse". Returns: A tensor of shape `[A1, ..., An, 2, 2]`, where the last dimension represents a 2d rotation matrix. Raises: ValueError: If the shape of `matrix` is not supported. """ with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 2), (-1, 2))) ndims = matrix.shape.ndims perm = list(range(ndims - 2)) + [ndims - 1, ndims - 2] return tf.transpose(a=matrix, perm=perm) def is_valid(matrix, atol=1e-3, name="rotation_matrix_2d_is_valid"): r"""Determines if a matrix is a valid rotation matrix. Determines if a matrix $$\mathbf{R}$$ is a valid rotation matrix by checking that $$\mathbf{R}^T\mathbf{R} = \mathbf{I}$$ and $$\det(\mathbf{R}) = 1$$. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 2, 2]`, where the last two dimensions represent a 2d rotation matrix. atol: The absolute tolerance parameter. name: A name for this op that defaults to "rotation_matrix_2d_is_valid". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]` where False indicates that the input is not a valid rotation matrix. """ with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 2), (-1, 2))) return rotation_matrix_common.is_valid(matrix, atol) def rotate(point, matrix, name="rotation_matrix_2d_rotate"): """Rotates a 2d point using a 2d rotation matrix. Note: In the following, A1 to An are optional batch dimensions, which must be identical. Args: point: A tensor of shape `[A1, ..., An, 2]`, where the last dimension represents a 2d point. matrix: A tensor of shape `[A1, ..., An, 2, 2]`, where the last two dimensions represent a 2d rotation matrix. name: A name for this op that defaults to "rotation_matrix_2d_rotate". Returns: A tensor of shape `[A1, ..., An, 2]`, where the last dimension represents a 2d point. Raises: ValueError: If the shape of `point` or `matrix` is not supported. """ with tf.name_scope(name): point = tf.convert_to_tensor(value=point) matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 2)) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 2), (-1, 2))) shape.compare_batch_dimensions( tensors=(point, matrix), tensor_names=("point", "matrix"), last_axes=(-2, -3), broadcast_compatible=True) point = tf.expand_dims(point, axis=-1) common_batch_shape = shape.get_broadcasted_shape(point.shape[:-2], matrix.shape[:-2]) def dim_value(dim): return 1 if dim is None else tf.compat.dimension_value(dim) common_batch_shape = [dim_value(dim) for dim in common_batch_shape] point = tf.broadcast_to(point, common_batch_shape + [2, 1]) matrix = tf.broadcast_to(matrix, common_batch_shape + [2, 2]) rotated_point = tf.matmul(matrix, point) return tf.squeeze(rotated_point, axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/geometry/transformation/rotation_matrix_3d.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow 3d rotation matrix utility functions. More details rotation matrices can be found on [this page.] (https://en.wikipedia.org/wiki/Rotation_matrix) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape from tensorflow_graphics.util import tfg_flags FLAGS = flags.FLAGS def _build_matrix_from_sines_and_cosines(sin_angles, cos_angles): """Builds a rotation matrix from sines and cosines of Euler angles. Note: In the following, A1 to An are optional batch dimensions. Args: sin_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the sine of the Euler angles. cos_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the cosine of the Euler angles. Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. """ sin_angles.shape.assert_is_compatible_with(cos_angles.shape) sx, sy, sz = tf.unstack(sin_angles, axis=-1) cx, cy, cz = tf.unstack(cos_angles, axis=-1) m00 = cy * cz m01 = (sx * sy * cz) - (cx * sz) m02 = (cx * sy * cz) + (sx * sz) m10 = cy * sz m11 = (sx * sy * sz) + (cx * cz) m12 = (cx * sy * sz) - (sx * cz) m20 = -sy m21 = sx * cy m22 = cx * cy matrix = tf.stack((m00, m01, m02, m10, m11, m12, m20, m21, m22), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=sin_angles)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def assert_rotation_matrix_normalized(matrix, eps=1e-3, name=None): """Checks whether a matrix is a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. eps: The absolute tolerance parameter. name: A name for this op that defaults to 'assert_rotation_matrix_normalized'. Returns: The input matrix, with dependence on the assertion operator in the graph. Raises: tf.errors.InvalidArgumentError: If rotation_matrix_3d is not normalized. """ if not FLAGS[tfg_flags.TFG_ADD_ASSERTS_TO_GRAPH].value: return matrix with tf.compat.v1.name_scope(name, "assert_rotation_matrix_normalized", [matrix]): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) is_matrix_normalized = is_valid(matrix, atol=eps) with tf.control_dependencies([ tf.compat.v1.assert_equal( is_matrix_normalized, tf.ones_like(is_matrix_normalized, dtype=tf.bool)) ]): return tf.identity(matrix) def from_axis_angle(axis, angle, name=None): """Convert an axis-angle representation to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a normalized axis. name: A name for this op that defaults to "rotation_matrix_3d_from_axis_angle". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represents a 3d rotation matrix. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_from_axis_angle", [axis, angle]): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) sin_axis = tf.sin(angle) * axis cos_angle = tf.cos(angle) cos1_axis = (1.0 - cos_angle) * axis _, axis_y, axis_z = tf.unstack(axis, axis=-1) cos1_axis_x, cos1_axis_y, _ = tf.unstack(cos1_axis, axis=-1) sin_axis_x, sin_axis_y, sin_axis_z = tf.unstack(sin_axis, axis=-1) tmp = cos1_axis_x * axis_y m01 = tmp - sin_axis_z m10 = tmp + sin_axis_z tmp = cos1_axis_x * axis_z m02 = tmp + sin_axis_y m20 = tmp - sin_axis_y tmp = cos1_axis_y * axis_z m12 = tmp - sin_axis_x m21 = tmp + sin_axis_x diag = cos1_axis * axis + cos_angle diag_x, diag_y, diag_z = tf.unstack(diag, axis=-1) matrix = tf.stack((diag_x, m01, m02, m10, diag_y, m12, m20, m21, diag_z), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=axis)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def from_euler(angles, name=None): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_from_euler", [angles]): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = tf.sin(angles) cos_angles = tf.cos(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_euler_with_small_angles_approximation(angles, name=None): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three small Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians, `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.compat.v1.name_scope( name, "rotation_matrix_3d_from_euler_with_small_angles", [angles]): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = angles cos_angles = 1.0 - 0.5 * tf.square(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_quaternion(quaternion, name=None): """Convert a quaternion to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "rotation_matrix_3d_from_quaternion". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_from_quaternion", [quaternion]): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) x, y, z, w = tf.unstack(quaternion, axis=-1) tx = 2.0 * x ty = 2.0 * y tz = 2.0 * z twx = tx * w twy = ty * w twz = tz * w txx = tx * x txy = ty * x txz = tz * x tyy = ty * y tyz = tz * y tzz = tz * z matrix = tf.stack((1.0 - (tyy + tzz), txy - twz, txz + twy, txy + twz, 1.0 - (txx + tzz), tyz - twx, txz - twy, tyz + twx, 1.0 - (txx + tyy)), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=quaternion)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def inverse(matrix, name=None): """Computes the inverse of a 3D rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_inverse". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `matrix` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_inverse", [matrix]): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) matrix = assert_rotation_matrix_normalized(matrix) ndims = matrix.shape.ndims perm = list(range(ndims - 2)) + [ndims - 1, ndims - 2] return tf.transpose(a=matrix, perm=perm) def is_valid(matrix, atol=1e-3, name=None): """Determines if a matrix is a valid rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last two dimensions represent a matrix. atol: Absolute tolerance parameter. name: A name for this op that defaults to "rotation_matrix_3d_is_valid". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]` where False indicates that the input is not a valid rotation matrix. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_is_valid", [matrix]): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) return rotation_matrix_common.is_valid(matrix, atol) def rotate(point, matrix, name=None): """Rotate a point using a rotation matrix 3d. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last dimension represents a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If the shape of `point` or `rotation_matrix_3d` is not supported. """ with tf.compat.v1.name_scope(name, "rotation_matrix_3d_rotate", [point, matrix]): point = tf.convert_to_tensor(value=point) matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) shape.compare_batch_dimensions( tensors=(point, matrix), tensor_names=("point", "matrix"), last_axes=(-2, -3), broadcast_compatible=True) matrix = assert_rotation_matrix_normalized(matrix) point = tf.expand_dims(point, axis=-1) common_batch_shape = shape.get_broadcasted_shape( point.shape[:-2], matrix.shape[:-2]) def dim_value(dim): return 1 if dim is None else tf.compat.v1.dimension_value(dim) common_batch_shape = [dim_value(dim) for dim in common_batch_shape] point = tf.broadcast_to(point, common_batch_shape + [3, 1]) matrix = tf.broadcast_to(matrix, common_batch_shape + [3, 3]) rotated_point = tf.matmul(matrix, point) return tf.squeeze(rotated_point, axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow 3d rotation matrix utility functions. More details rotation matrices can be found on [this page.] (https://en.wikipedia.org/wiki/Rotation_matrix) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape from tensorflow_graphics.util import tfg_flags FLAGS = flags.FLAGS def _build_matrix_from_sines_and_cosines(sin_angles, cos_angles): """Builds a rotation matrix from sines and cosines of Euler angles. Note: In the following, A1 to An are optional batch dimensions. Args: sin_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the sine of the Euler angles. cos_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the cosine of the Euler angles. Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. """ sin_angles.shape.assert_is_compatible_with(cos_angles.shape) sx, sy, sz = tf.unstack(sin_angles, axis=-1) cx, cy, cz = tf.unstack(cos_angles, axis=-1) m00 = cy * cz m01 = (sx * sy * cz) - (cx * sz) m02 = (cx * sy * cz) + (sx * sz) m10 = cy * sz m11 = (sx * sy * sz) + (cx * cz) m12 = (cx * sy * sz) - (sx * cz) m20 = -sy m21 = sx * cy m22 = cx * cy matrix = tf.stack((m00, m01, m02, m10, m11, m12, m20, m21, m22), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=sin_angles)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def assert_rotation_matrix_normalized(matrix, eps=1e-3, name="assert_rotation_matrix_normalized"): """Checks whether a matrix is a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. eps: The absolute tolerance parameter. name: A name for this op that defaults to 'assert_rotation_matrix_normalized'. Returns: The input matrix, with dependence on the assertion operator in the graph. Raises: tf.errors.InvalidArgumentError: If rotation_matrix_3d is not normalized. """ if not FLAGS[tfg_flags.TFG_ADD_ASSERTS_TO_GRAPH].value: return matrix with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) is_matrix_normalized = is_valid(matrix, atol=eps) with tf.control_dependencies([ tf.debugging.assert_equal( is_matrix_normalized, tf.ones_like(is_matrix_normalized, dtype=tf.bool)) ]): return tf.identity(matrix) def from_axis_angle(axis, angle, name="rotation_matrix_3d_from_axis_angle"): """Convert an axis-angle representation to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a normalized axis. name: A name for this op that defaults to "rotation_matrix_3d_from_axis_angle". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represents a 3d rotation matrix. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.name_scope(name): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) sin_axis = tf.sin(angle) * axis cos_angle = tf.cos(angle) cos1_axis = (1.0 - cos_angle) * axis _, axis_y, axis_z = tf.unstack(axis, axis=-1) cos1_axis_x, cos1_axis_y, _ = tf.unstack(cos1_axis, axis=-1) sin_axis_x, sin_axis_y, sin_axis_z = tf.unstack(sin_axis, axis=-1) tmp = cos1_axis_x * axis_y m01 = tmp - sin_axis_z m10 = tmp + sin_axis_z tmp = cos1_axis_x * axis_z m02 = tmp + sin_axis_y m20 = tmp - sin_axis_y tmp = cos1_axis_y * axis_z m12 = tmp - sin_axis_x m21 = tmp + sin_axis_x diag = cos1_axis * axis + cos_angle diag_x, diag_y, diag_z = tf.unstack(diag, axis=-1) matrix = tf.stack((diag_x, m01, m02, m10, diag_y, m12, m20, m21, diag_z), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=axis)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def from_euler(angles, name="rotation_matrix_3d_from_euler"): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = tf.sin(angles) cos_angles = tf.cos(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_euler_with_small_angles_approximation( angles, name="rotation_matrix_3d_from_euler_with_small_angles"): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three small Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians, `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler_with_small_angles". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = angles cos_angles = 1.0 - 0.5 * tf.square(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_quaternion(quaternion, name="rotation_matrix_3d_from_quaternion"): """Convert a quaternion to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "rotation_matrix_3d_from_quaternion". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) x, y, z, w = tf.unstack(quaternion, axis=-1) tx = 2.0 * x ty = 2.0 * y tz = 2.0 * z twx = tx * w twy = ty * w twz = tz * w txx = tx * x txy = ty * x txz = tz * x tyy = ty * y tyz = tz * y tzz = tz * z matrix = tf.stack((1.0 - (tyy + tzz), txy - twz, txz + twy, txy + twz, 1.0 - (txx + tzz), tyz - twx, txz - twy, tyz + twx, 1.0 - (txx + tyy)), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=quaternion)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def inverse(matrix, name="rotation_matrix_3d_inverse"): """Computes the inverse of a 3D rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_inverse". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `matrix` is not supported. """ with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) matrix = assert_rotation_matrix_normalized(matrix) ndims = matrix.shape.ndims perm = list(range(ndims - 2)) + [ndims - 1, ndims - 2] return tf.transpose(a=matrix, perm=perm) def is_valid(matrix, atol=1e-3, name="rotation_matrix_3d_is_valid"): """Determines if a matrix is a valid rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last two dimensions represent a matrix. atol: Absolute tolerance parameter. name: A name for this op that defaults to "rotation_matrix_3d_is_valid". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]` where False indicates that the input is not a valid rotation matrix. """ with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) return rotation_matrix_common.is_valid(matrix, atol) def rotate(point, matrix, name="rotation_matrix_3d_rotate"): """Rotate a point using a rotation matrix 3d. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last dimension represents a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If the shape of `point` or `rotation_matrix_3d` is not supported. """ with tf.name_scope(name): point = tf.convert_to_tensor(value=point) matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) shape.compare_batch_dimensions( tensors=(point, matrix), tensor_names=("point", "matrix"), last_axes=(-2, -3), broadcast_compatible=True) matrix = assert_rotation_matrix_normalized(matrix) point = tf.expand_dims(point, axis=-1) common_batch_shape = shape.get_broadcasted_shape(point.shape[:-2], matrix.shape[:-2]) def dim_value(dim): return 1 if dim is None else tf.compat.dimension_value(dim) common_batch_shape = [dim_value(dim) for dim in common_batch_shape] point = tf.broadcast_to(point, common_batch_shape + [3, 1]) matrix = tf.broadcast_to(matrix, common_batch_shape + [3, 3]) rotated_point = tf.matmul(matrix, point) return tf.squeeze(rotated_point, axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/geometry/transformation/rotation_matrix_common.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains routines shared for rotation matrices.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def is_valid(matrix, atol=1e-3, name=None): r"""Determines if a matrix in K-dimensions is a valid rotation matrix. Determines if a matrix $$\mathbf{R}$$ is a valid rotation matrix by checking that $$\mathbf{R}^T\mathbf{R} = \mathbf{I}$$ and $$\det(\mathbf{R}) = 1$$. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, K, K]`, where the last two dimensions represent a rotation matrix in K-dimensions. atol: The absolute tolerance parameter. name: A name for this op that defaults to "rotation_matrix_common_is_valid". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]` where False indicates that the input is not a valid rotation matrix. """ with tf.compat.v1.name_scope(name, "rotation_matrix_common_is_valid", [matrix]): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1) shape.compare_dimensions( tensors=(matrix, matrix), tensor_names=("matrix", "matrix"), axes=(-1, -2)) distance_to_unit_determinant = tf.abs(tf.linalg.det(matrix) - 1.) # Computes how far the product of the transposed rotation matrix with itself # is from the identity matrix. ndims = matrix.shape.ndims permutation = list(range(ndims - 2)) + [ndims - 1, ndims - 2] identity = tf.eye( tf.compat.v1.dimension_value(matrix.shape[-1]), dtype=matrix.dtype) difference_to_identity = tf.matmul( tf.transpose(a=matrix, perm=permutation), matrix) - identity norm_diff = tf.norm(tensor=difference_to_identity, axis=(-2, -1)) # Computes the mask of entries that satisfies all conditions. mask = tf.logical_and(distance_to_unit_determinant < atol, norm_diff < atol) output = tf.compat.v1.where( mask, tf.ones_like(distance_to_unit_determinant, dtype=bool), tf.zeros_like(distance_to_unit_determinant, dtype=bool)) return tf.expand_dims(output, axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains routines shared for rotation matrices.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def is_valid(matrix, atol=1e-3, name="rotation_matrix_common_is_valid"): r"""Determines if a matrix in K-dimensions is a valid rotation matrix. Determines if a matrix $$\mathbf{R}$$ is a valid rotation matrix by checking that $$\mathbf{R}^T\mathbf{R} = \mathbf{I}$$ and $$\det(\mathbf{R}) = 1$$. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, K, K]`, where the last two dimensions represent a rotation matrix in K-dimensions. atol: The absolute tolerance parameter. name: A name for this op that defaults to "rotation_matrix_common_is_valid". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]` where False indicates that the input is not a valid rotation matrix. """ with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1) shape.compare_dimensions( tensors=(matrix, matrix), tensor_names=("matrix", "matrix"), axes=(-1, -2)) distance_to_unit_determinant = tf.abs(tf.linalg.det(matrix) - 1.) # Computes how far the product of the transposed rotation matrix with itself # is from the identity matrix. ndims = matrix.shape.ndims permutation = list(range(ndims - 2)) + [ndims - 1, ndims - 2] identity = tf.eye( tf.compat.dimension_value(matrix.shape[-1]), dtype=matrix.dtype) difference_to_identity = tf.matmul( tf.transpose(a=matrix, perm=permutation), matrix) - identity norm_diff = tf.norm(tensor=difference_to_identity, axis=(-2, -1)) # Computes the mask of entries that satisfies all conditions. mask = tf.logical_and(distance_to_unit_determinant < atol, norm_diff < atol) output = tf.where(mask, tf.ones_like(distance_to_unit_determinant, dtype=bool), tf.zeros_like(distance_to_unit_determinant, dtype=bool)) return tf.expand_dims(output, axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/geometry/transformation/tests/euler_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for euler-related utiliy functions.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import euler from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.geometry.transformation.tests import test_data as td from tensorflow_graphics.geometry.transformation.tests import test_helpers from tensorflow_graphics.util import test_case class EulerTest(test_case.TestCase): @parameterized.parameters( ((3,), (1,)), ((None, 3), (None, 1)), ) def test_from_axis_angle_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(euler.from_axis_angle, shapes) @parameterized.parameters( ("must have exactly 3 dimensions", (None,), (1,)), ("must have exactly 1 dimensions", (3,), (None,)), ) def test_from_axis_angle_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(euler.from_axis_angle, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_axis_angle_jacobian_preset(self): """Test the Jacobian of the from_axis_angle function.""" x_axis_init, x_angle_init = test_helpers.generate_preset_test_axis_angle() self.assert_jacobian_is_finite_fn(euler.from_axis_angle, [x_axis_init, x_angle_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_axis_angle_jacobian_random(self): """Test the Jacobian of the from_axis_angle function.""" x_axis_init, x_angle_init = test_helpers.generate_random_test_axis_angle() self.assert_jacobian_is_finite_fn(euler.from_axis_angle, [x_axis_init, x_angle_init]) def test_from_axis_angle_random(self): """Checks that Euler angles can be retrieved from an axis-angle.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_matrix = rotation_matrix_3d.from_euler(random_euler_angles) random_axis, random_angle = axis_angle.from_euler(random_euler_angles) predicted_matrix = rotation_matrix_3d.from_axis_angle( random_axis, random_angle) self.assertAllClose(random_matrix, predicted_matrix, atol=1e-3) def test_from_axis_angle_preset(self): """Checks that Euler angles can be retrieved from axis-angle.""" preset_euler_angles = test_helpers.generate_preset_test_euler_angles() random_matrix = rotation_matrix_3d.from_euler(preset_euler_angles) random_axis, random_angle = axis_angle.from_euler(preset_euler_angles) predicted_matrix = rotation_matrix_3d.from_axis_angle( random_axis, random_angle) self.assertAllClose(random_matrix, predicted_matrix, atol=1e-3) @parameterized.parameters( (td.ANGLE_90,), (-td.ANGLE_90,), ) def test_from_axis_angle_gimbal(self, gimbal_configuration): """Checks that from_axis_angle works when Ry = pi/2 or -pi/2.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_euler_angles[..., 1] = gimbal_configuration random_matrix = rotation_matrix_3d.from_euler(random_euler_angles) random_axis, random_angle = axis_angle.from_euler(random_euler_angles) predicted_random_angles = euler.from_axis_angle(random_axis, random_angle) reconstructed_random_matrices = rotation_matrix_3d.from_euler( predicted_random_angles) self.assertAllClose(reconstructed_random_matrices, random_matrix, atol=1e-3) @parameterized.parameters( ((4,),), ((None, 4),), ) def test_from_quaternion_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(euler.from_quaternion, shape) @parameterized.parameters( ("must have exactly 4 dimensions", (None,)),) def test_from_quaternion_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(euler.from_quaternion, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_quaternion_jacobian_preset(self): """Test the Jacobian of the from_quaternion function.""" x_init = test_helpers.generate_preset_test_quaternions() self.assert_jacobian_is_finite_fn(euler.from_quaternion, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_quaternion_jacobian_random(self): """Test the Jacobian of the from_quaternion function.""" x_init = test_helpers.generate_random_test_quaternions() self.assert_jacobian_is_finite_fn(euler.from_quaternion, [x_init]) @parameterized.parameters( (td.ANGLE_90,), (-td.ANGLE_90,), ) def test_from_quaternion_gimbal(self, gimbal_configuration): """Checks that from_quaternion works when Ry = pi/2 or -pi/2.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_euler_angles[..., 1] = gimbal_configuration random_quaternion = quaternion.from_euler(random_euler_angles) random_matrix = rotation_matrix_3d.from_euler(random_euler_angles) reconstructed_random_matrices = rotation_matrix_3d.from_quaternion( random_quaternion) self.assertAllClose(reconstructed_random_matrices, random_matrix, atol=2e-3) def test_from_quaternion_preset(self): """Checks that Euler angles can be retrieved from quaternions.""" preset_euler_angles = test_helpers.generate_preset_test_euler_angles() preset_matrix = rotation_matrix_3d.from_euler(preset_euler_angles) preset_quaternion = quaternion.from_euler(preset_euler_angles) predicted_matrix = rotation_matrix_3d.from_quaternion(preset_quaternion) self.assertAllClose(preset_matrix, predicted_matrix, atol=2e-3) def test_from_quaternion_random(self): """Checks that Euler angles can be retrieved from quaternions.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_matrix = rotation_matrix_3d.from_euler(random_euler_angles) random_quaternion = quaternion.from_rotation_matrix(random_matrix) predicted_angles = euler.from_quaternion(random_quaternion) predicted_matrix = rotation_matrix_3d.from_euler(predicted_angles) self.assertAllClose(random_matrix, predicted_matrix, atol=2e-3) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ) def test_from_rotation_matrix_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(euler.from_rotation_matrix, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions", (None, 3)), ("must have exactly 3 dimensions", (3, None)), ) def test_from_rotation_matrix_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(euler.from_rotation_matrix, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_rotation_matrix_jacobian_preset(self): """Test the Jacobian of the from_rotation_matrix function.""" x_init = test_helpers.generate_preset_test_rotation_matrices_3d() x = tf.convert_to_tensor(value=x_init) y = euler.from_rotation_matrix(x) self.assert_jacobian_is_finite(x, x_init, y) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_rotation_matrix_jacobian_random(self): """Test the Jacobian of the from_rotation_matrix function.""" x_init = test_helpers.generate_random_test_rotation_matrix_3d() self.assert_jacobian_is_finite_fn(euler.from_rotation_matrix, [x_init]) def test_from_rotation_matrix_gimbal(self): """Testing that Euler angles can be retrieved in Gimbal lock.""" angles = test_helpers.generate_random_test_euler_angles() angles[..., 1] = np.pi / 2. matrix = rotation_matrix_3d.from_euler(angles) predicted_angles = euler.from_rotation_matrix(matrix) reconstructed_matrices = rotation_matrix_3d.from_euler(predicted_angles) self.assertAllClose(reconstructed_matrices, matrix, rtol=1e-3) angles[..., 1] = -np.pi / 2. matrix = rotation_matrix_3d.from_euler(angles) predicted_angles = euler.from_rotation_matrix(matrix) reconstructed_matrices = rotation_matrix_3d.from_euler(predicted_angles) self.assertAllClose(reconstructed_matrices, matrix, rtol=1e-3) def test_from_rotation_matrix_preset(self): """Tests that Euler angles can be retrieved from rotation matrices.""" matrix = test_helpers.generate_preset_test_rotation_matrices_3d() predicted_angles = euler.from_rotation_matrix(matrix) reconstructed_matrices = rotation_matrix_3d.from_euler(predicted_angles) self.assertAllClose(reconstructed_matrices, matrix, rtol=1e-3) def test_from_rotation_matrix_random(self): """Tests that Euler angles can be retrieved from rotation matrices.""" matrix = test_helpers.generate_random_test_rotation_matrix_3d() predicted_angles = euler.from_rotation_matrix(matrix) # There is not a unique mapping from rotation matrices to Euler angles. The # following constructs the rotation matrices from the `predicted_angles` and # compares them with `matrix`. reconstructed_matrices = rotation_matrix_3d.from_euler(predicted_angles) self.assertAllClose(reconstructed_matrices, matrix, rtol=1e-3) @parameterized.parameters( ((3,),), ((None, 3),), ) def test_inverse_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(euler.inverse, shape) @parameterized.parameters( ("must have exactly 3 dimensions", (None,)),) def test_inverse_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(euler.inverse, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_preset(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_preset_test_euler_angles() self.assert_jacobian_is_correct_fn(euler.inverse, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_random(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_random_test_euler_angles() self.assert_jacobian_is_correct_fn(euler.inverse, [x_init]) def test_inverse_preset(self): """Checks that inverse works as intended.""" preset_euler_angles = test_helpers.generate_preset_test_euler_angles() prediction = euler.inverse(preset_euler_angles) groundtruth = -preset_euler_angles self.assertAllClose(prediction, groundtruth, rtol=1e-3) def test_inverse_random(self): """Checks that inverse works as intended.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() prediction = euler.inverse(random_euler_angles) groundtruth = -random_euler_angles self.assertAllClose(prediction, groundtruth, rtol=1e-3) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for euler-related utiliy functions.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import euler from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.geometry.transformation.tests import test_data as td from tensorflow_graphics.geometry.transformation.tests import test_helpers from tensorflow_graphics.util import test_case class EulerTest(test_case.TestCase): @parameterized.parameters( ((3,), (1,)), ((None, 3), (None, 1)), ) def test_from_axis_angle_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(euler.from_axis_angle, shapes) @parameterized.parameters( ("must have exactly 3 dimensions", (None,), (1,)), ("must have exactly 1 dimensions", (3,), (None,)), ) def test_from_axis_angle_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(euler.from_axis_angle, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_axis_angle_jacobian_preset(self): """Test the Jacobian of the from_axis_angle function.""" x_axis_init, x_angle_init = test_helpers.generate_preset_test_axis_angle() self.assert_jacobian_is_finite_fn(euler.from_axis_angle, [x_axis_init, x_angle_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_axis_angle_jacobian_random(self): """Test the Jacobian of the from_axis_angle function.""" x_axis_init, x_angle_init = test_helpers.generate_random_test_axis_angle() self.assert_jacobian_is_finite_fn(euler.from_axis_angle, [x_axis_init, x_angle_init]) def test_from_axis_angle_random(self): """Checks that Euler angles can be retrieved from an axis-angle.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_matrix = rotation_matrix_3d.from_euler(random_euler_angles) random_axis, random_angle = axis_angle.from_euler(random_euler_angles) predicted_matrix = rotation_matrix_3d.from_axis_angle( random_axis, random_angle) self.assertAllClose(random_matrix, predicted_matrix, atol=1e-3) def test_from_axis_angle_preset(self): """Checks that Euler angles can be retrieved from axis-angle.""" preset_euler_angles = test_helpers.generate_preset_test_euler_angles() random_matrix = rotation_matrix_3d.from_euler(preset_euler_angles) random_axis, random_angle = axis_angle.from_euler(preset_euler_angles) predicted_matrix = rotation_matrix_3d.from_axis_angle( random_axis, random_angle) self.assertAllClose(random_matrix, predicted_matrix, atol=1e-3) @parameterized.parameters( (td.ANGLE_90,), (-td.ANGLE_90,), ) def test_from_axis_angle_gimbal(self, gimbal_configuration): """Checks that from_axis_angle works when Ry = pi/2 or -pi/2.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_euler_angles[..., 1] = gimbal_configuration random_matrix = rotation_matrix_3d.from_euler(random_euler_angles) random_axis, random_angle = axis_angle.from_euler(random_euler_angles) predicted_random_angles = euler.from_axis_angle(random_axis, random_angle) reconstructed_random_matrices = rotation_matrix_3d.from_euler( predicted_random_angles) self.assertAllClose(reconstructed_random_matrices, random_matrix, atol=1e-3) @parameterized.parameters( ((4,),), ((None, 4),), ) def test_from_quaternion_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(euler.from_quaternion, shape) @parameterized.parameters( ("must have exactly 4 dimensions", (None,)),) def test_from_quaternion_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(euler.from_quaternion, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_quaternion_jacobian_preset(self): """Test the Jacobian of the from_quaternion function.""" x_init = test_helpers.generate_preset_test_quaternions() self.assert_jacobian_is_finite_fn(euler.from_quaternion, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_quaternion_jacobian_random(self): """Test the Jacobian of the from_quaternion function.""" x_init = test_helpers.generate_random_test_quaternions() self.assert_jacobian_is_finite_fn(euler.from_quaternion, [x_init]) @parameterized.parameters( (td.ANGLE_90,), (-td.ANGLE_90,), ) def test_from_quaternion_gimbal(self, gimbal_configuration): """Checks that from_quaternion works when Ry = pi/2 or -pi/2.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_euler_angles[..., 1] = gimbal_configuration random_quaternion = quaternion.from_euler(random_euler_angles) random_matrix = rotation_matrix_3d.from_euler(random_euler_angles) reconstructed_random_matrices = rotation_matrix_3d.from_quaternion( random_quaternion) self.assertAllClose(reconstructed_random_matrices, random_matrix, atol=2e-3) def test_from_quaternion_preset(self): """Checks that Euler angles can be retrieved from quaternions.""" preset_euler_angles = test_helpers.generate_preset_test_euler_angles() preset_matrix = rotation_matrix_3d.from_euler(preset_euler_angles) preset_quaternion = quaternion.from_euler(preset_euler_angles) predicted_matrix = rotation_matrix_3d.from_quaternion(preset_quaternion) self.assertAllClose(preset_matrix, predicted_matrix, atol=2e-3) def test_from_quaternion_random(self): """Checks that Euler angles can be retrieved from quaternions.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_matrix = rotation_matrix_3d.from_euler(random_euler_angles) random_quaternion = quaternion.from_rotation_matrix(random_matrix) predicted_angles = euler.from_quaternion(random_quaternion) predicted_matrix = rotation_matrix_3d.from_euler(predicted_angles) self.assertAllClose(random_matrix, predicted_matrix, atol=2e-3) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ) def test_from_rotation_matrix_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(euler.from_rotation_matrix, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions", (None, 3)), ("must have exactly 3 dimensions", (3, None)), ) def test_from_rotation_matrix_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(euler.from_rotation_matrix, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_rotation_matrix_jacobian_preset(self): """Test the Jacobian of the from_rotation_matrix function.""" if tf.executing_eagerly(): self.skipTest(reason="Graph mode only test") with tf.compat.v1.Session() as sess: x_init = np.array( sess.run(test_helpers.generate_preset_test_rotation_matrices_3d())) x = tf.convert_to_tensor(value=x_init) y = euler.from_rotation_matrix(x) self.assert_jacobian_is_finite(x, x_init, y) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_rotation_matrix_jacobian_random(self): """Test the Jacobian of the from_rotation_matrix function.""" x_init = test_helpers.generate_random_test_rotation_matrix_3d() self.assert_jacobian_is_finite_fn(euler.from_rotation_matrix, [x_init]) def test_from_rotation_matrix_gimbal(self): """Testing that Euler angles can be retrieved in Gimbal lock.""" angles = test_helpers.generate_random_test_euler_angles() angles[..., 1] = np.pi / 2. matrix = rotation_matrix_3d.from_euler(angles) predicted_angles = euler.from_rotation_matrix(matrix) reconstructed_matrices = rotation_matrix_3d.from_euler(predicted_angles) self.assertAllClose(reconstructed_matrices, matrix, rtol=1e-3) angles[..., 1] = -np.pi / 2. matrix = rotation_matrix_3d.from_euler(angles) predicted_angles = euler.from_rotation_matrix(matrix) reconstructed_matrices = rotation_matrix_3d.from_euler(predicted_angles) self.assertAllClose(reconstructed_matrices, matrix, rtol=1e-3) def test_from_rotation_matrix_preset(self): """Tests that Euler angles can be retrieved from rotation matrices.""" matrix = test_helpers.generate_preset_test_rotation_matrices_3d() predicted_angles = euler.from_rotation_matrix(matrix) reconstructed_matrices = rotation_matrix_3d.from_euler(predicted_angles) self.assertAllClose(reconstructed_matrices, matrix, rtol=1e-3) def test_from_rotation_matrix_random(self): """Tests that Euler angles can be retrieved from rotation matrices.""" matrix = test_helpers.generate_random_test_rotation_matrix_3d() predicted_angles = euler.from_rotation_matrix(matrix) # There is not a unique mapping from rotation matrices to Euler angles. The # following constructs the rotation matrices from the `predicted_angles` and # compares them with `matrix`. reconstructed_matrices = rotation_matrix_3d.from_euler(predicted_angles) self.assertAllClose(reconstructed_matrices, matrix, rtol=1e-3) @parameterized.parameters( ((3,),), ((None, 3),), ) def test_inverse_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(euler.inverse, shape) @parameterized.parameters( ("must have exactly 3 dimensions", (None,)),) def test_inverse_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(euler.inverse, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_preset(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_preset_test_euler_angles() self.assert_jacobian_is_correct_fn(euler.inverse, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_random(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_random_test_euler_angles() self.assert_jacobian_is_correct_fn(euler.inverse, [x_init]) def test_inverse_preset(self): """Checks that inverse works as intended.""" preset_euler_angles = test_helpers.generate_preset_test_euler_angles() prediction = euler.inverse(preset_euler_angles) groundtruth = -preset_euler_angles self.assertAllClose(prediction, groundtruth, rtol=1e-3) def test_inverse_random(self): """Checks that inverse works as intended.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() prediction = euler.inverse(random_euler_angles) groundtruth = -random_euler_angles self.assertAllClose(prediction, groundtruth, rtol=1e-3) if __name__ == "__main__": test_case.main()
1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/geometry/transformation/tests/quaternion_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for quaternion.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.geometry.transformation.tests import test_data as td from tensorflow_graphics.geometry.transformation.tests import test_helpers from tensorflow_graphics.util import test_case class QuaternionTest(test_case.TestCase): @parameterized.parameters( ((3,), (3,)), ((None, 3), (None, 3)), ) def test_between_two_vectors_3d_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(quaternion.between_two_vectors_3d, shapes) @parameterized.parameters( ("must have exactly 3 dimensions", (2,), (3,)), ("must have exactly 3 dimensions", (3,), (2,)), ) def test_between_two_vectors_3d_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.between_two_vectors_3d, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_between_two_vectors_3d_jacobian_random(self): """Tests the Jacobian of between_two_vectors_3d.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() x_1_init = np.random.random(tensor_shape + [3]) x_2_init = np.random.random(tensor_shape + [3]) self.assert_jacobian_is_correct_fn( quaternion.between_two_vectors_3d, [x_1_init, x_2_init], atol=1e-4) def test_between_two_vectors_3d_random(self): """Checks the extracted rotation between two 3d vectors.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() source = np.random.random(tensor_shape + [3]).astype(np.float32) target = np.random.random(tensor_shape + [3]).astype(np.float32) rotation = quaternion.between_two_vectors_3d(source, target) rec_target = quaternion.rotate(source, rotation) self.assertAllClose( tf.nn.l2_normalize(target, axis=-1), tf.nn.l2_normalize(rec_target, axis=-1)) # Checks that resulting quaternions are normalized. self.assertAllEqual( quaternion.is_normalized(rotation), np.full(tensor_shape + [1], True)) def test_between_two_vectors_3d_that_are_the_same(self): """Checks the extracted rotation between two identical 3d vectors.""" source = np.random.random((1, 3)) rotation = quaternion.between_two_vectors_3d(source, source) self.assertAllEqual([[0, 0, 0, 1]], rotation) def test_between_two_vectors_3d_that_are_collinear(self): """Checks the extracted rotation between two collinear 3d vectors.""" axis = [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0)] antiparallel_axis = [(0.0, 1.0, 0.0), (0.0, 0.0, 1.0)] source = np.multiply(axis, 10.) target = np.multiply(axis, -10.) rotation = quaternion.between_two_vectors_3d(source, target) rotation_pi = quaternion.from_axis_angle(antiparallel_axis, [[np.pi], [np.pi]]) self.assertAllClose(rotation_pi, rotation) @parameterized.parameters( ((4,),), ((None, 4),), ) def test_conjugate_exception_not_raised(self, *shape): """Tests that the shape exceptions of conjugate are not raised.""" self.assert_exception_is_not_raised(quaternion.conjugate, shape) @parameterized.parameters( ("must have exactly 4 dimensions", (3,)),) def test_conjugate_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.conjugate, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_conjugate_jacobian_preset(self): """Test the Jacobian of the conjugate function.""" x_init = test_helpers.generate_preset_test_quaternions() self.assert_jacobian_is_correct_fn(quaternion.conjugate, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_conjugate_jacobian_random(self): """Test the Jacobian of the conjugate function.""" x_init = test_helpers.generate_random_test_quaternions() self.assert_jacobian_is_correct_fn(quaternion.conjugate, [x_init]) @parameterized.parameters( ((3,), (1,)), ((None, 3), (None, 1)), ) def test_from_axis_angle_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(quaternion.from_axis_angle, shapes) @parameterized.parameters( ("must have exactly 3 dimensions", (2,), (1,)), ("must have exactly 1 dimensions", (3,), (2,)), ) def test_from_axis_angle_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.from_axis_angle, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_axis_angle_jacobian_preset(self): """Test the Jacobian of the from_axis_angle function.""" x_axis_init, x_angle_init = test_helpers.generate_preset_test_axis_angle() self.assert_jacobian_is_correct_fn(quaternion.from_axis_angle, [x_axis_init, x_angle_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_axis_angle_jacobian_random(self): """Test the Jacobian of the from_axis_angle function.""" x_axis_init, x_angle_init = test_helpers.generate_random_test_axis_angle() self.assert_jacobian_is_correct_fn(quaternion.from_axis_angle, [x_axis_init, x_angle_init]) def test_from_axis_angle_normalized_random(self): """Test that from_axis_angle produces normalized quaternions.""" random_axis, random_angle = test_helpers.generate_random_test_axis_angle() random_quaternion = quaternion.from_axis_angle(random_axis, random_angle) self.assertAllEqual( quaternion.is_normalized(random_quaternion), np.ones(shape=random_angle.shape, dtype=bool)) def test_from_axis_angle_random(self): """Tests converting an axis-angle to a quaternion.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() axis, angle = axis_angle.from_euler(random_euler_angles) grountruth = rotation_matrix_3d.from_quaternion( quaternion.from_euler(random_euler_angles)) prediction = rotation_matrix_3d.from_quaternion( quaternion.from_axis_angle(axis, angle)) self.assertAllClose(grountruth, prediction, rtol=1e-3) @parameterized.parameters( ((3,),), ((None, 3),), ) def test_from_euler_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(quaternion.from_euler, shape) @parameterized.parameters( ("must have exactly 3 dimensions", (4,)),) def test_from_euler_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.from_euler, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_jacobian_preset(self): """Test the Jacobian of the from_euler function.""" x_init = test_helpers.generate_preset_test_euler_angles() self.assert_jacobian_is_correct_fn(quaternion.from_euler, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_jacobian_random(self): """Test the Jacobian of the from_euler function.""" x_init = test_helpers.generate_random_test_euler_angles() self.assert_jacobian_is_correct_fn(quaternion.from_euler, [x_init]) def test_from_euler_normalized_random(self): """Tests that quaternions.from_euler returns normalized quaterions.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() tensor_shape = random_euler_angles.shape[:-1] random_quaternion = quaternion.from_euler(random_euler_angles) self.assertAllEqual( quaternion.is_normalized(random_quaternion), np.ones(shape=tensor_shape + (1,), dtype=bool)) def test_from_euler_random(self): """Tests that quaternions can be constructed from Euler angles.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() tensor_shape = random_euler_angles.shape[:-1] random_matrix = rotation_matrix_3d.from_euler(random_euler_angles) random_quaternion = quaternion.from_euler(random_euler_angles) random_point = np.random.normal(size=tensor_shape + (3,)) rotated_with_matrix = rotation_matrix_3d.rotate(random_point, random_matrix) rotated_with_quaternion = quaternion.rotate(random_point, random_quaternion) self.assertAllClose(rotated_with_matrix, rotated_with_quaternion) @parameterized.parameters( ((3,),), ((None, 3),), ) def test_from_euler_with_small_angles_approximation_exception_not_raised( self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( quaternion.from_euler_with_small_angles_approximation, shapes) @parameterized.parameters( ("must have exactly 3 dimensions", (4,)),) def test_from_euler_with_small_angles_approximation_exception_raised( self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised( quaternion.from_euler_with_small_angles_approximation, error_msg, shape) def test_from_euler_with_small_angles_approximation_random(self): # Only generate small angles. For a test tolerance of 1e-3, 0.33 was found # empirically to be the range where the small angle approximation works. random_euler_angles = test_helpers.generate_random_test_euler_angles( min_angle=-0.33, max_angle=0.33) exact_quaternion = quaternion.from_euler(random_euler_angles) approximate_quaternion = ( quaternion.from_euler_with_small_angles_approximation( random_euler_angles)) self.assertAllClose(exact_quaternion, approximate_quaternion, atol=1e-3) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions", (4, 3)), ("must have exactly 3 dimensions", (3, 4)), ) def test_from_rotation_matrix_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.from_rotation_matrix, error_msg, shape) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ) def test_from_rotation_matrix_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(quaternion.from_rotation_matrix, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_rotation_matrix_jacobian_preset(self): """Test the Jacobian of the from_rotation_matrix function.""" x_init = test_helpers.generate_preset_test_rotation_matrices_3d() x = tf.convert_to_tensor(value=x_init) y = quaternion.from_rotation_matrix(x) self.assert_jacobian_is_finite(x, x_init, y) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_rotation_matrix_jacobian_random(self): """Test the Jacobian of the from_rotation_matrix function.""" x_init = test_helpers.generate_random_test_rotation_matrix_3d() self.assert_jacobian_is_finite_fn(quaternion.from_rotation_matrix, [x_init]) def test_from_rotation_matrix_normalized_random(self): """Tests that from_rotation_matrix produces normalized quaternions.""" random_matrix = test_helpers.generate_random_test_rotation_matrix_3d() random_quaternion = quaternion.from_rotation_matrix(random_matrix) self.assertAllEqual( quaternion.is_normalized(random_quaternion), np.ones(shape=random_matrix.shape[:-2] + (1,), dtype=bool)) @parameterized.parameters( ((td.MAT_3D_ID,), (td.QUAT_ID,)), ((td.MAT_3D_X_45,), (td.QUAT_X_45,)), ((td.MAT_3D_Y_45,), (td.QUAT_Y_45,)), ((td.MAT_3D_Z_45,), (td.QUAT_Z_45,)), ((td.MAT_3D_X_90,), (td.QUAT_X_90,)), ((td.MAT_3D_Y_90,), (td.QUAT_Y_90,)), ((td.MAT_3D_Z_90,), (td.QUAT_Z_90,)), ((td.MAT_3D_X_180,), (td.QUAT_X_180,)), ((td.MAT_3D_Y_180,), (td.QUAT_Y_180,)), ((td.MAT_3D_Z_180,), (td.QUAT_Z_180,)), ) def test_from_rotation_matrix_preset(self, test_inputs, test_outputs): self.assert_output_is_correct(quaternion.from_rotation_matrix, test_inputs, test_outputs) def test_from_rotation_matrix_random(self): """Tests that from_rotation_matrix produces the expected quaternions.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_rotation_matrix_3d = rotation_matrix_3d.from_euler( random_euler_angles) groundtruth = rotation_matrix_3d.from_quaternion( quaternion.from_euler(random_euler_angles)) prediction = rotation_matrix_3d.from_quaternion( quaternion.from_rotation_matrix(random_rotation_matrix_3d)) self.assertAllClose(groundtruth, prediction) @parameterized.parameters( ((4,),), ((None, 4),), ) def test_inverse_exception_not_raised(self, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_not_raised(quaternion.inverse, shape) @parameterized.parameters( ("must have exactly 4 dimensions", (3,)),) def test_inverse_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.inverse, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_preset(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_preset_test_quaternions() self.assert_jacobian_is_correct_fn(quaternion.inverse, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_random(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_random_test_quaternions() self.assert_jacobian_is_correct_fn(quaternion.inverse, [x_init]) def test_inverse_normalized_random(self): """Tests that the inverse function returns normalized quaternions.""" random_quaternion = test_helpers.generate_random_test_quaternions() inverse_quaternion = quaternion.inverse(random_quaternion) self.assertAllEqual( quaternion.is_normalized(inverse_quaternion), np.ones(shape=random_quaternion.shape[:-1] + (1,), dtype=bool)) def test_inverse_random(self): """Tests that multiplying with the inverse gives identity.""" random_quaternion = test_helpers.generate_random_test_quaternions() inverse_quaternion = quaternion.inverse(random_quaternion) final_quaternion = quaternion.multiply(random_quaternion, inverse_quaternion) tensor_shape = random_quaternion.shape[:-1] identity_quaternion = np.array((0.0, 0.0, 0.0, 1.0), dtype=np.float32) identity_quaternion = np.tile(identity_quaternion, tensor_shape + (1,)) self.assertAllClose(final_quaternion, identity_quaternion, rtol=1e-3) @parameterized.parameters( ((4,),), ((None, 4),), ) def test_is_normalized_exception_not_raised(self, *shape): """Tests that the shape exceptions of from_quaternion are not raised.""" self.assert_exception_is_not_raised(quaternion.is_normalized, shape) @parameterized.parameters( ("must have exactly 4 dimensions", (1, 5)),) def test_is_normalized_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions of from_quaternion are raised.""" self.assert_exception_is_raised(quaternion.is_normalized, error_msg, shape) def test_is_normalized_random(self): """Tests that is_normalized works as intended.""" random_quaternion = test_helpers.generate_random_test_quaternions() tensor_shape = random_quaternion.shape[:-1] unnormalized_random_quaternion = random_quaternion * 1.01 quat = np.concatenate((random_quaternion, unnormalized_random_quaternion), axis=0) mask = np.concatenate( (np.ones(shape=tensor_shape + (1,), dtype=bool), np.zeros(shape=tensor_shape + (1,), dtype=bool)), axis=0) is_normalized = quaternion.is_normalized(quat) self.assertAllEqual(mask, is_normalized) @parameterized.parameters( ((4,),), ((None, 4),), ) def test_normalize_exception_not_raised(self, *shape): """Tests that the shape exceptions of from_quaternion are not raised.""" self.assert_exception_is_not_raised(quaternion.normalize, shape) @parameterized.parameters( ("must have exactly 4 dimensions", (1, 5)),) def test_normalize_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions of from_quaternion are raised.""" self.assert_exception_is_raised(quaternion.normalize, error_msg, shape) def test_normalize_random(self): """Tests that normalize works as intended.""" random_quaternion = test_helpers.generate_random_test_quaternions() tensor_shape = random_quaternion.shape[:-1] unnormalized_random_quaternion = random_quaternion * 1.01 quat = np.concatenate((random_quaternion, unnormalized_random_quaternion), axis=0) mask = np.concatenate( (np.ones(shape=tensor_shape + (1,), dtype=bool), np.zeros(shape=tensor_shape + (1,), dtype=bool)), axis=0) is_normalized_before = quaternion.is_normalized(quat) normalized = quaternion.normalize(quat) is_normalized_after = quaternion.is_normalized(normalized) self.assertAllEqual(mask, is_normalized_before) self.assertAllEqual(is_normalized_after, np.ones(shape=is_normalized_after.shape, dtype=bool)) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_normalize_jacobian_preset(self): """Test the Jacobian of the normalize function.""" x_init = test_helpers.generate_preset_test_quaternions() self.assert_jacobian_is_correct_fn(quaternion.normalize, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_normalize_jacobian_random(self): """Test the Jacobian of the normalize function.""" tensor_dimensions = np.random.randint(low=1, high=3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() x_init = test_helpers.generate_random_test_quaternions(tensor_shape) self.assert_jacobian_is_correct_fn(quaternion.normalize, [x_init]) @parameterized.parameters( ((4,), (4,)), ((None, 4), (None, 4)), ) def test_multiply_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(quaternion.multiply, shapes) @parameterized.parameters( ("must have exactly 4 dimensions", (3,), (4,)), ("must have exactly 4 dimensions", (4,), (3,)), ) def test_multiply_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.multiply, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_multiply_jacobian_preset(self): """Test the Jacobian of the multiply function.""" x_1_init = test_helpers.generate_preset_test_quaternions() x_2_init = test_helpers.generate_preset_test_quaternions() self.assert_jacobian_is_correct_fn(quaternion.multiply, [x_1_init, x_2_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_multiply_jacobian_random(self): """Test the Jacobian of the multiply function.""" tensor_dimensions = np.random.randint(low=1, high=3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() x_1_init = test_helpers.generate_random_test_quaternions(tensor_shape) x_2_init = test_helpers.generate_random_test_quaternions(tensor_shape) self.assert_jacobian_is_correct_fn(quaternion.multiply, [x_1_init, x_2_init]) def test_normalized_random_initializer_raised(self): """Tests that the shape exceptions are raised.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() with self.subTest(name="dtype"): with self.assertRaisesRegexp(ValueError, "'dtype' must be tf.float32."): tf.compat.v1.get_variable( "test_variable", shape=tensor_shape + [4], dtype=tf.uint8, initializer=quaternion.normalized_random_uniform_initializer(), use_resource=False) with self.subTest(name="shape"): with self.assertRaisesRegexp(ValueError, "Last dimension of 'shape' must be 4."): tf.compat.v1.get_variable( "test_variable", shape=tensor_shape + [3], dtype=tf.float32, initializer=quaternion.normalized_random_uniform_initializer(), use_resource=False) def test_normalized_random_uniform_initializer_is_normalized(self): """Tests normalized_random_uniform_initializer outputs are normalized.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() variable = tf.compat.v1.get_variable( "test_variable", shape=tensor_shape + [4], dtype=tf.float32, initializer=quaternion.normalized_random_uniform_initializer(), use_resource=False) self.evaluate(tf.compat.v1.global_variables_initializer()) value = self.evaluate(variable) norms = np.linalg.norm(value, axis=-1) ones = np.ones(tensor_shape) self.assertAllClose(norms, ones, rtol=1e-3) def test_normalized_random_uniform_is_normalized(self): """Tests that the normalized_random_uniform gives normalized quaternions.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() tensor = quaternion.normalized_random_uniform(tensor_shape) norms = tf.norm(tensor=tensor, axis=-1) ones = np.ones(tensor_shape) self.assertAllClose(norms, ones, rtol=1e-3) @parameterized.parameters( ((3,), (4,)), ((None, 3), (None, 4)), ) def test_rotate_exception_not_raised(self, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_not_raised(quaternion.rotate, shape) @parameterized.parameters( ("must have exactly 3 dimensions", (2,), (4,)), ("must have exactly 4 dimensions", (3,), (2,)), ) def test_rotate_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.rotate, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_preset(self): """Test the Jacobian of the rotate function.""" x_matrix_init = test_helpers.generate_preset_test_quaternions() tensor_shape = x_matrix_init.shape[:-1] + (3,) x_point_init = np.random.uniform(size=tensor_shape) self.assert_jacobian_is_correct_fn(quaternion.rotate, [x_point_init, x_matrix_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_random(self): """Test the Jacobian of the rotate function.""" x_matrix_init = test_helpers.generate_random_test_quaternions() tensor_shape = x_matrix_init.shape[:-1] + (3,) x_point_init = np.random.uniform(size=tensor_shape) self.assert_jacobian_is_correct_fn(quaternion.rotate, [x_point_init, x_matrix_init]) def test_rotate_random(self): """Tests the rotation using a quaternion vs a rotation matrix.""" random_quaternion = test_helpers.generate_random_test_quaternions() tensor_shape = random_quaternion.shape[:-1] random_point = np.random.normal(size=tensor_shape + (3,)) rotated_point_quaternion = quaternion.rotate(random_point, random_quaternion) matrix = rotation_matrix_3d.from_quaternion(random_quaternion) rotated_point_matrix = rotation_matrix_3d.rotate(random_point, matrix) self.assertAllClose( rotated_point_matrix, rotated_point_quaternion, rtol=1e-3) @parameterized.parameters( ((td.QUAT_ID, td.QUAT_X_45), (np.pi / 4.0,)), ((td.QUAT_X_45, td.QUAT_ID), (np.pi / 4.0,)), ((td.QUAT_Y_90, td.QUAT_Y_180), (np.pi / 2.0,)), ((td.QUAT_X_180, td.QUAT_Z_180), (np.pi,)), ((td.QUAT_X_180, -1.0 * td.QUAT_Y_180), (np.pi,)), ((td.QUAT_X_180, td.QUAT_X_180), (0.0,)), ((td.QUAT_X_180, -1 * td.QUAT_X_180), (0.0,)), ((td.QUAT_X_90, td.QUAT_Y_90), (2 * np.pi / 3.0,)), ((np.array([0., 0., 0., 1]), np.array([0., 0., 0., 1])), (0.0,)), ) def test_relative_angle(self, test_inputs, test_outputs): """Tests quaternion relative angle.""" self.assert_output_is_correct(quaternion.relative_angle, test_inputs, test_outputs) @parameterized.parameters( ((4,), (4,)), ((None, 4), (None, 4)), ((None, None, 4), (None, None, 4)), ) def test_relative_angle_not_raised(self, *shapes): """Tests that the shape exceptions of relative_angle are not raised.""" self.assert_exception_is_not_raised(quaternion.relative_angle, shapes) @parameterized.parameters( ("must have exactly 4 dimensions", (3,), (4,)), ("must have exactly 4 dimensions", (4,), (3,)), ) def test_relative_angle_raised(self, error_msg, *shape): """Tests that the shape exceptions of relative_angle are raised.""" self.assert_exception_is_raised(quaternion.relative_angle, error_msg, shape) def test_valid_relative_angle_random(self): """Test the output is in valid range for relative_angle function.""" tensor_dimensions = np.random.randint(low=1, high=3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() x_1_init = test_helpers.generate_random_test_quaternions(tensor_shape) x_2_init = test_helpers.generate_random_test_quaternions(tensor_shape) x_1 = tf.convert_to_tensor(value=x_1_init) x_2 = tf.convert_to_tensor(value=x_2_init) y = quaternion.relative_angle(x_1, x_2) self.assertAllGreaterEqual(y, 0.0) self.assertAllLessEqual(y, np.pi) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_jacobian_relative_angle_random(self): """Test the Jacobian of the relative_angle function.""" tensor_dimensions = np.random.randint(low=1, high=3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() x_1_init = test_helpers.generate_random_test_quaternions(tensor_shape) x_2_init = test_helpers.generate_random_test_quaternions(tensor_shape) self.assert_jacobian_is_correct_fn(quaternion.relative_angle, [x_1_init, x_2_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_jacobian_relative_angle_preset(self): """Test the Jacobian of the relative_angle function.""" x_1_init = test_helpers.generate_preset_test_quaternions() x_2_init = test_helpers.generate_preset_test_quaternions() # relative angle is not smooth near <q1, q2> = 1, which occurs for # certain preset test quaternions. self.assert_jacobian_is_finite_fn(quaternion.relative_angle, [x_1_init, x_2_init]) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for quaternion.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.geometry.transformation.tests import test_data as td from tensorflow_graphics.geometry.transformation.tests import test_helpers from tensorflow_graphics.util import test_case class QuaternionTest(test_case.TestCase): @parameterized.parameters( ((3,), (3,)), ((None, 3), (None, 3)), ) def test_between_two_vectors_3d_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(quaternion.between_two_vectors_3d, shapes) @parameterized.parameters( ("must have exactly 3 dimensions", (2,), (3,)), ("must have exactly 3 dimensions", (3,), (2,)), ) def test_between_two_vectors_3d_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.between_two_vectors_3d, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_between_two_vectors_3d_jacobian_random(self): """Tests the Jacobian of between_two_vectors_3d.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() x_1_init = np.random.random(tensor_shape + [3]) x_2_init = np.random.random(tensor_shape + [3]) self.assert_jacobian_is_correct_fn( quaternion.between_two_vectors_3d, [x_1_init, x_2_init], atol=1e-4) def test_between_two_vectors_3d_random(self): """Checks the extracted rotation between two 3d vectors.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() source = np.random.random(tensor_shape + [3]).astype(np.float32) target = np.random.random(tensor_shape + [3]).astype(np.float32) rotation = quaternion.between_two_vectors_3d(source, target) rec_target = quaternion.rotate(source, rotation) self.assertAllClose( tf.nn.l2_normalize(target, axis=-1), tf.nn.l2_normalize(rec_target, axis=-1)) # Checks that resulting quaternions are normalized. self.assertAllEqual( quaternion.is_normalized(rotation), np.full(tensor_shape + [1], True)) def test_between_two_vectors_3d_that_are_the_same(self): """Checks the extracted rotation between two identical 3d vectors.""" source = np.random.random((1, 3)) rotation = quaternion.between_two_vectors_3d(source, source) self.assertAllEqual([[0, 0, 0, 1]], rotation) def test_between_two_vectors_3d_that_are_collinear(self): """Checks the extracted rotation between two collinear 3d vectors.""" axis = [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0)] antiparallel_axis = [(0.0, 1.0, 0.0), (0.0, 0.0, 1.0)] source = np.multiply(axis, 10.) target = np.multiply(axis, -10.) rotation = quaternion.between_two_vectors_3d(source, target) rotation_pi = quaternion.from_axis_angle(antiparallel_axis, [[np.pi], [np.pi]]) self.assertAllClose(rotation_pi, rotation) @parameterized.parameters( ((4,),), ((None, 4),), ) def test_conjugate_exception_not_raised(self, *shape): """Tests that the shape exceptions of conjugate are not raised.""" self.assert_exception_is_not_raised(quaternion.conjugate, shape) @parameterized.parameters( ("must have exactly 4 dimensions", (3,)),) def test_conjugate_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.conjugate, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_conjugate_jacobian_preset(self): """Test the Jacobian of the conjugate function.""" x_init = test_helpers.generate_preset_test_quaternions() self.assert_jacobian_is_correct_fn(quaternion.conjugate, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_conjugate_jacobian_random(self): """Test the Jacobian of the conjugate function.""" x_init = test_helpers.generate_random_test_quaternions() self.assert_jacobian_is_correct_fn(quaternion.conjugate, [x_init]) @parameterized.parameters( ((3,), (1,)), ((None, 3), (None, 1)), ) def test_from_axis_angle_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(quaternion.from_axis_angle, shapes) @parameterized.parameters( ("must have exactly 3 dimensions", (2,), (1,)), ("must have exactly 1 dimensions", (3,), (2,)), ) def test_from_axis_angle_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.from_axis_angle, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_axis_angle_jacobian_preset(self): """Test the Jacobian of the from_axis_angle function.""" x_axis_init, x_angle_init = test_helpers.generate_preset_test_axis_angle() self.assert_jacobian_is_correct_fn(quaternion.from_axis_angle, [x_axis_init, x_angle_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_axis_angle_jacobian_random(self): """Test the Jacobian of the from_axis_angle function.""" x_axis_init, x_angle_init = test_helpers.generate_random_test_axis_angle() self.assert_jacobian_is_correct_fn(quaternion.from_axis_angle, [x_axis_init, x_angle_init]) def test_from_axis_angle_normalized_random(self): """Test that from_axis_angle produces normalized quaternions.""" random_axis, random_angle = test_helpers.generate_random_test_axis_angle() random_quaternion = quaternion.from_axis_angle(random_axis, random_angle) self.assertAllEqual( quaternion.is_normalized(random_quaternion), np.ones(shape=random_angle.shape, dtype=bool)) def test_from_axis_angle_random(self): """Tests converting an axis-angle to a quaternion.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() axis, angle = axis_angle.from_euler(random_euler_angles) grountruth = rotation_matrix_3d.from_quaternion( quaternion.from_euler(random_euler_angles)) prediction = rotation_matrix_3d.from_quaternion( quaternion.from_axis_angle(axis, angle)) self.assertAllClose(grountruth, prediction, rtol=1e-3) @parameterized.parameters( ((3,),), ((None, 3),), ) def test_from_euler_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(quaternion.from_euler, shape) @parameterized.parameters( ("must have exactly 3 dimensions", (4,)),) def test_from_euler_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.from_euler, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_jacobian_preset(self): """Test the Jacobian of the from_euler function.""" x_init = test_helpers.generate_preset_test_euler_angles() self.assert_jacobian_is_correct_fn(quaternion.from_euler, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_jacobian_random(self): """Test the Jacobian of the from_euler function.""" x_init = test_helpers.generate_random_test_euler_angles() self.assert_jacobian_is_correct_fn(quaternion.from_euler, [x_init]) def test_from_euler_normalized_random(self): """Tests that quaternions.from_euler returns normalized quaterions.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() tensor_shape = random_euler_angles.shape[:-1] random_quaternion = quaternion.from_euler(random_euler_angles) self.assertAllEqual( quaternion.is_normalized(random_quaternion), np.ones(shape=tensor_shape + (1,), dtype=bool)) def test_from_euler_random(self): """Tests that quaternions can be constructed from Euler angles.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() tensor_shape = random_euler_angles.shape[:-1] random_matrix = rotation_matrix_3d.from_euler(random_euler_angles) random_quaternion = quaternion.from_euler(random_euler_angles) random_point = np.random.normal(size=tensor_shape + (3,)) rotated_with_matrix = rotation_matrix_3d.rotate(random_point, random_matrix) rotated_with_quaternion = quaternion.rotate(random_point, random_quaternion) self.assertAllClose(rotated_with_matrix, rotated_with_quaternion) @parameterized.parameters( ((3,),), ((None, 3),), ) def test_from_euler_with_small_angles_approximation_exception_not_raised( self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( quaternion.from_euler_with_small_angles_approximation, shapes) @parameterized.parameters( ("must have exactly 3 dimensions", (4,)),) def test_from_euler_with_small_angles_approximation_exception_raised( self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised( quaternion.from_euler_with_small_angles_approximation, error_msg, shape) def test_from_euler_with_small_angles_approximation_random(self): # Only generate small angles. For a test tolerance of 1e-3, 0.33 was found # empirically to be the range where the small angle approximation works. random_euler_angles = test_helpers.generate_random_test_euler_angles( min_angle=-0.33, max_angle=0.33) exact_quaternion = quaternion.from_euler(random_euler_angles) approximate_quaternion = ( quaternion.from_euler_with_small_angles_approximation( random_euler_angles)) self.assertAllClose(exact_quaternion, approximate_quaternion, atol=1e-3) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions", (4, 3)), ("must have exactly 3 dimensions", (3, 4)), ) def test_from_rotation_matrix_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.from_rotation_matrix, error_msg, shape) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ) def test_from_rotation_matrix_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(quaternion.from_rotation_matrix, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_rotation_matrix_jacobian_preset(self): """Test the Jacobian of the from_rotation_matrix function.""" if tf.executing_eagerly(): self.skipTest(reason="Graph mode only test") with tf.compat.v1.Session() as sess: x_init = np.array( sess.run(test_helpers.generate_preset_test_rotation_matrices_3d())) x = tf.convert_to_tensor(value=x_init) y = quaternion.from_rotation_matrix(x) self.assert_jacobian_is_finite(x, x_init, y) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_rotation_matrix_jacobian_random(self): """Test the Jacobian of the from_rotation_matrix function.""" x_init = test_helpers.generate_random_test_rotation_matrix_3d() self.assert_jacobian_is_finite_fn(quaternion.from_rotation_matrix, [x_init]) def test_from_rotation_matrix_normalized_random(self): """Tests that from_rotation_matrix produces normalized quaternions.""" random_matrix = test_helpers.generate_random_test_rotation_matrix_3d() random_quaternion = quaternion.from_rotation_matrix(random_matrix) self.assertAllEqual( quaternion.is_normalized(random_quaternion), np.ones(shape=random_matrix.shape[:-2] + (1,), dtype=bool)) @parameterized.parameters( ((td.MAT_3D_ID,), (td.QUAT_ID,)), ((td.MAT_3D_X_45,), (td.QUAT_X_45,)), ((td.MAT_3D_Y_45,), (td.QUAT_Y_45,)), ((td.MAT_3D_Z_45,), (td.QUAT_Z_45,)), ((td.MAT_3D_X_90,), (td.QUAT_X_90,)), ((td.MAT_3D_Y_90,), (td.QUAT_Y_90,)), ((td.MAT_3D_Z_90,), (td.QUAT_Z_90,)), ((td.MAT_3D_X_180,), (td.QUAT_X_180,)), ((td.MAT_3D_Y_180,), (td.QUAT_Y_180,)), ((td.MAT_3D_Z_180,), (td.QUAT_Z_180,)), ) def test_from_rotation_matrix_preset(self, test_inputs, test_outputs): self.assert_output_is_correct(quaternion.from_rotation_matrix, test_inputs, test_outputs) def test_from_rotation_matrix_random(self): """Tests that from_rotation_matrix produces the expected quaternions.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_rotation_matrix_3d = rotation_matrix_3d.from_euler( random_euler_angles) groundtruth = rotation_matrix_3d.from_quaternion( quaternion.from_euler(random_euler_angles)) prediction = rotation_matrix_3d.from_quaternion( quaternion.from_rotation_matrix(random_rotation_matrix_3d)) self.assertAllClose(groundtruth, prediction) @parameterized.parameters( ((4,),), ((None, 4),), ) def test_inverse_exception_not_raised(self, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_not_raised(quaternion.inverse, shape) @parameterized.parameters( ("must have exactly 4 dimensions", (3,)),) def test_inverse_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.inverse, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_preset(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_preset_test_quaternions() self.assert_jacobian_is_correct_fn(quaternion.inverse, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_random(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_random_test_quaternions() self.assert_jacobian_is_correct_fn(quaternion.inverse, [x_init]) def test_inverse_normalized_random(self): """Tests that the inverse function returns normalized quaternions.""" random_quaternion = test_helpers.generate_random_test_quaternions() inverse_quaternion = quaternion.inverse(random_quaternion) self.assertAllEqual( quaternion.is_normalized(inverse_quaternion), np.ones(shape=random_quaternion.shape[:-1] + (1,), dtype=bool)) def test_inverse_random(self): """Tests that multiplying with the inverse gives identity.""" random_quaternion = test_helpers.generate_random_test_quaternions() inverse_quaternion = quaternion.inverse(random_quaternion) final_quaternion = quaternion.multiply(random_quaternion, inverse_quaternion) tensor_shape = random_quaternion.shape[:-1] identity_quaternion = np.array((0.0, 0.0, 0.0, 1.0), dtype=np.float32) identity_quaternion = np.tile(identity_quaternion, tensor_shape + (1,)) self.assertAllClose(final_quaternion, identity_quaternion, rtol=1e-3) @parameterized.parameters( ((4,),), ((None, 4),), ) def test_is_normalized_exception_not_raised(self, *shape): """Tests that the shape exceptions of from_quaternion are not raised.""" self.assert_exception_is_not_raised(quaternion.is_normalized, shape) @parameterized.parameters( ("must have exactly 4 dimensions", (1, 5)),) def test_is_normalized_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions of from_quaternion are raised.""" self.assert_exception_is_raised(quaternion.is_normalized, error_msg, shape) def test_is_normalized_random(self): """Tests that is_normalized works as intended.""" random_quaternion = test_helpers.generate_random_test_quaternions() tensor_shape = random_quaternion.shape[:-1] unnormalized_random_quaternion = random_quaternion * 1.01 quat = np.concatenate((random_quaternion, unnormalized_random_quaternion), axis=0) mask = np.concatenate( (np.ones(shape=tensor_shape + (1,), dtype=bool), np.zeros(shape=tensor_shape + (1,), dtype=bool)), axis=0) is_normalized = quaternion.is_normalized(quat) self.assertAllEqual(mask, is_normalized) @parameterized.parameters( ((4,),), ((None, 4),), ) def test_normalize_exception_not_raised(self, *shape): """Tests that the shape exceptions of from_quaternion are not raised.""" self.assert_exception_is_not_raised(quaternion.normalize, shape) @parameterized.parameters( ("must have exactly 4 dimensions", (1, 5)),) def test_normalize_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions of from_quaternion are raised.""" self.assert_exception_is_raised(quaternion.normalize, error_msg, shape) def test_normalize_random(self): """Tests that normalize works as intended.""" random_quaternion = test_helpers.generate_random_test_quaternions() tensor_shape = random_quaternion.shape[:-1] unnormalized_random_quaternion = random_quaternion * 1.01 quat = np.concatenate((random_quaternion, unnormalized_random_quaternion), axis=0) mask = np.concatenate( (np.ones(shape=tensor_shape + (1,), dtype=bool), np.zeros(shape=tensor_shape + (1,), dtype=bool)), axis=0) is_normalized_before = quaternion.is_normalized(quat) normalized = quaternion.normalize(quat) is_normalized_after = quaternion.is_normalized(normalized) self.assertAllEqual(mask, is_normalized_before) self.assertAllEqual(is_normalized_after, np.ones(shape=is_normalized_after.shape, dtype=bool)) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_normalize_jacobian_preset(self): """Test the Jacobian of the normalize function.""" x_init = test_helpers.generate_preset_test_quaternions() self.assert_jacobian_is_correct_fn(quaternion.normalize, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_normalize_jacobian_random(self): """Test the Jacobian of the normalize function.""" tensor_dimensions = np.random.randint(low=1, high=3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() x_init = test_helpers.generate_random_test_quaternions(tensor_shape) self.assert_jacobian_is_correct_fn(quaternion.normalize, [x_init]) @parameterized.parameters( ((4,), (4,)), ((None, 4), (None, 4)), ) def test_multiply_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(quaternion.multiply, shapes) @parameterized.parameters( ("must have exactly 4 dimensions", (3,), (4,)), ("must have exactly 4 dimensions", (4,), (3,)), ) def test_multiply_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.multiply, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_multiply_jacobian_preset(self): """Test the Jacobian of the multiply function.""" x_1_init = test_helpers.generate_preset_test_quaternions() x_2_init = test_helpers.generate_preset_test_quaternions() self.assert_jacobian_is_correct_fn(quaternion.multiply, [x_1_init, x_2_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_multiply_jacobian_random(self): """Test the Jacobian of the multiply function.""" tensor_dimensions = np.random.randint(low=1, high=3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() x_1_init = test_helpers.generate_random_test_quaternions(tensor_shape) x_2_init = test_helpers.generate_random_test_quaternions(tensor_shape) self.assert_jacobian_is_correct_fn(quaternion.multiply, [x_1_init, x_2_init]) def test_normalized_random_initializer_raised(self): """Tests that the shape exceptions are raised.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() with self.subTest(name="dtype"): with self.assertRaisesRegexp(ValueError, "'dtype' must be tf.float32."): quaternion.normalized_random_uniform_initializer()( tensor_shape + [4], dtype=tf.uint8) with self.subTest(name="shape"): with self.assertRaisesRegexp(ValueError, "Last dimension of 'shape' must be 4."): quaternion.normalized_random_uniform_initializer()( tensor_shape + [3], dtype=tf.float32) def test_normalized_random_uniform_initializer_is_normalized(self): """Tests normalized_random_uniform_initializer outputs are normalized.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() tensor = quaternion.normalized_random_uniform_initializer()( tensor_shape + [4], dtype=tf.float32) norms = tf.norm(tensor=tensor, axis=-1) ones = np.ones(tensor_shape) self.assertAllClose(norms, ones, rtol=1e-3) def test_normalized_random_uniform_is_normalized(self): """Tests that the normalized_random_uniform gives normalized quaternions.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() tensor = quaternion.normalized_random_uniform(tensor_shape) norms = tf.norm(tensor=tensor, axis=-1) ones = np.ones(tensor_shape) self.assertAllClose(norms, ones, rtol=1e-3) @parameterized.parameters( ((3,), (4,)), ((None, 3), (None, 4)), ) def test_rotate_exception_not_raised(self, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_not_raised(quaternion.rotate, shape) @parameterized.parameters( ("must have exactly 3 dimensions", (2,), (4,)), ("must have exactly 4 dimensions", (3,), (2,)), ) def test_rotate_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(quaternion.rotate, error_msg, shape) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_preset(self): """Test the Jacobian of the rotate function.""" x_matrix_init = test_helpers.generate_preset_test_quaternions() tensor_shape = x_matrix_init.shape[:-1] + (3,) x_point_init = np.random.uniform(size=tensor_shape) self.assert_jacobian_is_correct_fn(quaternion.rotate, [x_point_init, x_matrix_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_random(self): """Test the Jacobian of the rotate function.""" x_matrix_init = test_helpers.generate_random_test_quaternions() tensor_shape = x_matrix_init.shape[:-1] + (3,) x_point_init = np.random.uniform(size=tensor_shape) self.assert_jacobian_is_correct_fn(quaternion.rotate, [x_point_init, x_matrix_init]) def test_rotate_random(self): """Tests the rotation using a quaternion vs a rotation matrix.""" random_quaternion = test_helpers.generate_random_test_quaternions() tensor_shape = random_quaternion.shape[:-1] random_point = np.random.normal(size=tensor_shape + (3,)) rotated_point_quaternion = quaternion.rotate(random_point, random_quaternion) matrix = rotation_matrix_3d.from_quaternion(random_quaternion) rotated_point_matrix = rotation_matrix_3d.rotate(random_point, matrix) self.assertAllClose( rotated_point_matrix, rotated_point_quaternion, rtol=1e-3) @parameterized.parameters( ((td.QUAT_ID, td.QUAT_X_45), (np.pi / 4.0,)), ((td.QUAT_X_45, td.QUAT_ID), (np.pi / 4.0,)), ((td.QUAT_Y_90, td.QUAT_Y_180), (np.pi / 2.0,)), ((td.QUAT_X_180, td.QUAT_Z_180), (np.pi,)), ((td.QUAT_X_180, -1.0 * td.QUAT_Y_180), (np.pi,)), ((td.QUAT_X_180, td.QUAT_X_180), (0.0,)), ((td.QUAT_X_180, -1 * td.QUAT_X_180), (0.0,)), ((td.QUAT_X_90, td.QUAT_Y_90), (2 * np.pi / 3.0,)), ((np.array([0., 0., 0., 1]), np.array([0., 0., 0., 1])), (0.0,)), ) def test_relative_angle(self, test_inputs, test_outputs): """Tests quaternion relative angle.""" self.assert_output_is_correct(quaternion.relative_angle, test_inputs, test_outputs) @parameterized.parameters( ((4,), (4,)), ((None, 4), (None, 4)), ((None, None, 4), (None, None, 4)), ) def test_relative_angle_not_raised(self, *shapes): """Tests that the shape exceptions of relative_angle are not raised.""" self.assert_exception_is_not_raised(quaternion.relative_angle, shapes) @parameterized.parameters( ("must have exactly 4 dimensions", (3,), (4,)), ("must have exactly 4 dimensions", (4,), (3,)), ) def test_relative_angle_raised(self, error_msg, *shape): """Tests that the shape exceptions of relative_angle are raised.""" self.assert_exception_is_raised(quaternion.relative_angle, error_msg, shape) def test_valid_relative_angle_random(self): """Test the output is in valid range for relative_angle function.""" tensor_dimensions = np.random.randint(low=1, high=3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() x_1_init = test_helpers.generate_random_test_quaternions(tensor_shape) x_2_init = test_helpers.generate_random_test_quaternions(tensor_shape) x_1 = tf.convert_to_tensor(value=x_1_init) x_2 = tf.convert_to_tensor(value=x_2_init) y = quaternion.relative_angle(x_1, x_2) self.assertAllGreaterEqual(y, 0.0) self.assertAllLessEqual(y, np.pi) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_jacobian_relative_angle_random(self): """Test the Jacobian of the relative_angle function.""" tensor_dimensions = np.random.randint(low=1, high=3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() x_1_init = test_helpers.generate_random_test_quaternions(tensor_shape) x_2_init = test_helpers.generate_random_test_quaternions(tensor_shape) self.assert_jacobian_is_correct_fn(quaternion.relative_angle, [x_1_init, x_2_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_jacobian_relative_angle_preset(self): """Test the Jacobian of the relative_angle function.""" x_1_init = test_helpers.generate_preset_test_quaternions() x_2_init = test_helpers.generate_preset_test_quaternions() # relative angle is not smooth near <q1, q2> = 1, which occurs for # certain preset test quaternions. self.assert_jacobian_is_finite_fn(quaternion.relative_angle, [x_1_init, x_2_init]) if __name__ == "__main__": test_case.main()
1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/geometry/transformation/tests/test_helpers.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test helpers for the transformation module.""" import itertools import math import numpy as np from scipy import stats import tensorflow.compat.v2 as tf from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_2d from tensorflow_graphics.geometry.transformation import rotation_matrix_3d def generate_preset_test_euler_angles(dimensions=3): """Generates a permutation with duplicate of some classic euler angles.""" permutations = itertools.product( [0., np.pi, np.pi / 2., np.pi / 3., np.pi / 4., np.pi / 6.], repeat=dimensions) return np.array(list(permutations)) def generate_preset_test_translations(dimensions=3): """Generates a set of translations.""" permutations = itertools.product([0.1, -0.2, 0.5, 0.7, 0.4, -0.1], repeat=dimensions) return np.array(list(permutations)) def generate_preset_test_rotation_matrices_3d(): """Generates pre-set test 3d rotation matrices.""" angles = generate_preset_test_euler_angles() preset_rotation_matrix = rotation_matrix_3d.from_euler(angles) if tf.executing_eagerly(): return np.array(preset_rotation_matrix) with tf.compat.v1.Session() as sess: return np.array(sess.run([preset_rotation_matrix])) def generate_preset_test_rotation_matrices_2d(): """Generates pre-set test 2d rotation matrices.""" angles = generate_preset_test_euler_angles(dimensions=1) preset_rotation_matrix = rotation_matrix_2d.from_euler(angles) if tf.executing_eagerly(): return np.array(preset_rotation_matrix) with tf.compat.v1.Session() as sess: return np.array(sess.run([preset_rotation_matrix])) def generate_preset_test_axis_angle(): """Generates pre-set test rotation matrices.""" angles = generate_preset_test_euler_angles() axis, angle = axis_angle.from_euler(angles) if tf.executing_eagerly(): return np.array(axis), np.array(angle) with tf.compat.v1.Session() as sess: return np.array(sess.run([axis])), np.array(sess.run([angle])) def generate_preset_test_quaternions(): """Generates pre-set test quaternions.""" angles = generate_preset_test_euler_angles() preset_quaternion = quaternion.from_euler(angles) if tf.executing_eagerly(): return np.array(preset_quaternion) with tf.compat.v1.Session() as sess: return np.array(sess.run([preset_quaternion])) def generate_preset_test_dual_quaternions(): """Generates pre-set test quaternions.""" angles = generate_preset_test_euler_angles() preset_quaternion_real = quaternion.from_euler(angles) translations = generate_preset_test_translations() translations = np.concatenate( (translations / 2.0, np.zeros((np.ma.size(translations, 0), 1))), axis=1) preset_quaternion_translation = tf.convert_to_tensor(value=translations) preset_quaternion_dual = quaternion.multiply(preset_quaternion_translation, preset_quaternion_real) preset_dual_quaternion = tf.concat( (preset_quaternion_real, preset_quaternion_dual), axis=-1) return preset_dual_quaternion def generate_random_test_dual_quaternions(): """Generates random test dual quaternions.""" angles = generate_random_test_euler_angles() random_quaternion_real = quaternion.from_euler(angles) min_translation = -3.0 max_translation = 3.0 translations = np.random.uniform(min_translation, max_translation, angles.shape) translations_quaternion_shape = np.asarray(translations.shape) translations_quaternion_shape[-1] = 1 translations = np.concatenate( (translations / 2.0, np.zeros(translations_quaternion_shape)), axis=-1) random_quaternion_translation = tf.convert_to_tensor(value=translations) random_quaternion_dual = quaternion.multiply(random_quaternion_translation, random_quaternion_real) random_dual_quaternion = tf.concat( (random_quaternion_real, random_quaternion_dual), axis=-1) return random_dual_quaternion def generate_random_test_euler_angles(dimensions=3, min_angle=-3. * np.pi, max_angle=3. * np.pi): """Generates random test random Euler angles.""" tensor_dimensions = np.random.randint(3) tensor_tile = np.random.randint(1, 10, tensor_dimensions).tolist() return np.random.uniform(min_angle, max_angle, tensor_tile + [dimensions]) def generate_random_test_quaternions(tensor_shape=None): """Generates random test quaternions.""" if tensor_shape is None: tensor_dimensions = np.random.randint(low=1, high=3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() u1 = np.random.uniform(0.0, 1.0, tensor_shape) u2 = np.random.uniform(0.0, 2.0 * math.pi, tensor_shape) u3 = np.random.uniform(0.0, 2.0 * math.pi, tensor_shape) a = np.sqrt(1.0 - u1) b = np.sqrt(u1) return np.stack((a * np.sin(u2), a * np.cos(u2), b * np.sin(u3), b * np.cos(u3)), axis=-1) # pyformat: disable def generate_random_test_axis_angle(): """Generates random test axis-angles.""" tensor_dimensions = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() random_axis = np.random.uniform(size=tensor_shape + [3]) random_axis /= np.linalg.norm(random_axis, axis=-1, keepdims=True) random_angle = np.random.uniform(size=tensor_shape + [1]) return random_axis, random_angle def generate_random_test_rotation_matrix_3d(): """Generates random test 3d rotation matrices.""" random_matrix = np.array( [stats.special_ortho_group.rvs(3) for _ in range(20)]) return np.reshape(random_matrix, [5, 4, 3, 3]) def generate_random_test_rotation_matrix_2d(): """Generates random test 2d rotation matrices.""" random_matrix = np.array( [stats.special_ortho_group.rvs(2) for _ in range(20)]) return np.reshape(random_matrix, [5, 4, 2, 2]) def generate_random_test_lbs_blend(): """Generates random test for the linear blend skinning blend function.""" tensor_dimensions = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() random_points = np.random.uniform(size=tensor_shape + [3]) num_weights = np.random.randint(2, 10) random_weights = np.random.uniform(size=tensor_shape + [num_weights]) random_weights /= np.sum(random_weights, axis=-1, keepdims=True) random_rotations = np.array( [stats.special_ortho_group.rvs(3) for _ in range(num_weights)]) random_rotations = np.reshape(random_rotations, [num_weights, 3, 3]) random_translations = np.random.uniform(size=[num_weights, 3]) return random_points, random_weights, random_rotations, random_translations def generate_preset_test_lbs_blend(): """Generates preset test for the linear blend skinning blend function.""" points = np.array([[[1.0, 0.0, 0.0], [0.1, 0.2, 0.5]], [[0.0, 1.0, 0.0], [0.3, -0.5, 0.2]], [[-0.3, 0.1, 0.3], [0.1, -0.9, -0.4]]]) weights = np.array([[[0.0, 1.0, 0.0, 0.0], [0.4, 0.2, 0.3, 0.1]], [[0.6, 0.0, 0.4, 0.0], [0.2, 0.2, 0.1, 0.5]], [[0.0, 0.1, 0.0, 0.9], [0.1, 0.2, 0.3, 0.4]]]) rotations = np.array( [[[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], [[0.36, 0.48, -0.8], [-0.8, 0.60, 0.00], [0.48, 0.64, 0.60]], [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], [[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, -1.0]]], [[[-0.41554751, -0.42205085, -0.80572535], [0.08028719, -0.89939186, 0.42970716], [-0.9060211, 0.11387432, 0.40762533]], [[-0.05240625, -0.24389111, 0.96838562], [0.99123384, -0.13047444, 0.02078231], [0.12128095, 0.96098572, 0.2485908]], [[-0.32722936, -0.06793413, -0.94249981], [-0.70574479, 0.68082693, 0.19595657], [0.62836712, 0.72928708, -0.27073072]], [[-0.22601332, -0.95393284, 0.19730719], [-0.01189659, 0.20523618, 0.97864017], [-0.97405157, 0.21883843, -0.05773466]]]]) # pyformat: disable translations = np.array( [[[0.1, -0.2, 0.5], [-0.2, 0.7, 0.7], [0.8, -0.2, 0.4], [-0.1, 0.2, -0.3]], [[0.5, 0.6, 0.9], [-0.1, -0.3, -0.7], [0.4, -0.2, 0.8], [0.7, 0.8, -0.4]]]) # pyformat: disable blended_points = np.array([[[[0.16, -0.1, 1.18], [0.3864, 0.148, 0.7352]], [[0.38, 0.4, 0.86], [-0.2184, 0.152, 0.0088]], [[-0.05, 0.01, -0.46], [-0.3152, -0.004, -0.1136]]], [[[-0.15240625, 0.69123384, -0.57871905], [0.07776242, 0.33587402, 0.55386645]], [[0.17959584, 0.01269566, 1.22003942], [0.71406514, 0.6187734, -0.43794053]], [[0.67662743, 0.94549789, -0.14946982], [0.88587099, -0.09324637, -0.45012815]]]]) return points, weights, rotations, translations, blended_points
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test helpers for the transformation module.""" import itertools import math import numpy as np from scipy import stats import tensorflow.compat.v2 as tf from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_2d from tensorflow_graphics.geometry.transformation import rotation_matrix_3d def generate_preset_test_euler_angles(dimensions=3): """Generates a permutation with duplicate of some classic euler angles.""" permutations = itertools.product( [0., np.pi, np.pi / 2., np.pi / 3., np.pi / 4., np.pi / 6.], repeat=dimensions) return np.array(list(permutations)) def generate_preset_test_translations(dimensions=3): """Generates a set of translations.""" permutations = itertools.product([0.1, -0.2, 0.5, 0.7, 0.4, -0.1], repeat=dimensions) return np.array(list(permutations)) def generate_preset_test_rotation_matrices_3d(): """Generates pre-set test 3d rotation matrices.""" angles = generate_preset_test_euler_angles() preset_rotation_matrix = rotation_matrix_3d.from_euler(angles) return preset_rotation_matrix def generate_preset_test_rotation_matrices_2d(): """Generates pre-set test 2d rotation matrices.""" angles = generate_preset_test_euler_angles(dimensions=1) preset_rotation_matrix = rotation_matrix_2d.from_euler(angles) return preset_rotation_matrix def generate_preset_test_axis_angle(): """Generates pre-set test rotation matrices.""" angles = generate_preset_test_euler_angles() axis, angle = axis_angle.from_euler(angles) return axis, angle def generate_preset_test_quaternions(): """Generates pre-set test quaternions.""" angles = generate_preset_test_euler_angles() preset_quaternion = quaternion.from_euler(angles) return preset_quaternion def generate_preset_test_dual_quaternions(): """Generates pre-set test quaternions.""" angles = generate_preset_test_euler_angles() preset_quaternion_real = quaternion.from_euler(angles) translations = generate_preset_test_translations() translations = np.concatenate( (translations / 2.0, np.zeros((np.ma.size(translations, 0), 1))), axis=1) preset_quaternion_translation = tf.convert_to_tensor(value=translations) preset_quaternion_dual = quaternion.multiply(preset_quaternion_translation, preset_quaternion_real) preset_dual_quaternion = tf.concat( (preset_quaternion_real, preset_quaternion_dual), axis=-1) return preset_dual_quaternion def generate_random_test_dual_quaternions(): """Generates random test dual quaternions.""" angles = generate_random_test_euler_angles() random_quaternion_real = quaternion.from_euler(angles) min_translation = -3.0 max_translation = 3.0 translations = np.random.uniform(min_translation, max_translation, angles.shape) translations_quaternion_shape = np.asarray(translations.shape) translations_quaternion_shape[-1] = 1 translations = np.concatenate( (translations / 2.0, np.zeros(translations_quaternion_shape)), axis=-1) random_quaternion_translation = tf.convert_to_tensor(value=translations) random_quaternion_dual = quaternion.multiply(random_quaternion_translation, random_quaternion_real) random_dual_quaternion = tf.concat( (random_quaternion_real, random_quaternion_dual), axis=-1) return random_dual_quaternion def generate_random_test_euler_angles(dimensions=3, min_angle=-3. * np.pi, max_angle=3. * np.pi): """Generates random test random Euler angles.""" tensor_dimensions = np.random.randint(3) tensor_tile = np.random.randint(1, 10, tensor_dimensions).tolist() return np.random.uniform(min_angle, max_angle, tensor_tile + [dimensions]) def generate_random_test_quaternions(tensor_shape=None): """Generates random test quaternions.""" if tensor_shape is None: tensor_dimensions = np.random.randint(low=1, high=3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() u1 = np.random.uniform(0.0, 1.0, tensor_shape) u2 = np.random.uniform(0.0, 2.0 * math.pi, tensor_shape) u3 = np.random.uniform(0.0, 2.0 * math.pi, tensor_shape) a = np.sqrt(1.0 - u1) b = np.sqrt(u1) return np.stack((a * np.sin(u2), a * np.cos(u2), b * np.sin(u3), b * np.cos(u3)), axis=-1) # pyformat: disable def generate_random_test_axis_angle(): """Generates random test axis-angles.""" tensor_dimensions = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() random_axis = np.random.uniform(size=tensor_shape + [3]) random_axis /= np.linalg.norm(random_axis, axis=-1, keepdims=True) random_angle = np.random.uniform(size=tensor_shape + [1]) return random_axis, random_angle def generate_random_test_rotation_matrix_3d(): """Generates random test 3d rotation matrices.""" random_matrix = np.array( [stats.special_ortho_group.rvs(3) for _ in range(20)]) return np.reshape(random_matrix, [5, 4, 3, 3]) def generate_random_test_rotation_matrix_2d(): """Generates random test 2d rotation matrices.""" random_matrix = np.array( [stats.special_ortho_group.rvs(2) for _ in range(20)]) return np.reshape(random_matrix, [5, 4, 2, 2]) def generate_random_test_lbs_blend(): """Generates random test for the linear blend skinning blend function.""" tensor_dimensions = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_dimensions)).tolist() random_points = np.random.uniform(size=tensor_shape + [3]) num_weights = np.random.randint(2, 10) random_weights = np.random.uniform(size=tensor_shape + [num_weights]) random_weights /= np.sum(random_weights, axis=-1, keepdims=True) random_rotations = np.array( [stats.special_ortho_group.rvs(3) for _ in range(num_weights)]) random_rotations = np.reshape(random_rotations, [num_weights, 3, 3]) random_translations = np.random.uniform(size=[num_weights, 3]) return random_points, random_weights, random_rotations, random_translations def generate_preset_test_lbs_blend(): """Generates preset test for the linear blend skinning blend function.""" points = np.array([[[1.0, 0.0, 0.0], [0.1, 0.2, 0.5]], [[0.0, 1.0, 0.0], [0.3, -0.5, 0.2]], [[-0.3, 0.1, 0.3], [0.1, -0.9, -0.4]]]) weights = np.array([[[0.0, 1.0, 0.0, 0.0], [0.4, 0.2, 0.3, 0.1]], [[0.6, 0.0, 0.4, 0.0], [0.2, 0.2, 0.1, 0.5]], [[0.0, 0.1, 0.0, 0.9], [0.1, 0.2, 0.3, 0.4]]]) rotations = np.array( [[[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], [[0.36, 0.48, -0.8], [-0.8, 0.60, 0.00], [0.48, 0.64, 0.60]], [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], [[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, -1.0]]], [[[-0.41554751, -0.42205085, -0.80572535], [0.08028719, -0.89939186, 0.42970716], [-0.9060211, 0.11387432, 0.40762533]], [[-0.05240625, -0.24389111, 0.96838562], [0.99123384, -0.13047444, 0.02078231], [0.12128095, 0.96098572, 0.2485908]], [[-0.32722936, -0.06793413, -0.94249981], [-0.70574479, 0.68082693, 0.19595657], [0.62836712, 0.72928708, -0.27073072]], [[-0.22601332, -0.95393284, 0.19730719], [-0.01189659, 0.20523618, 0.97864017], [-0.97405157, 0.21883843, -0.05773466]]]]) # pyformat: disable translations = np.array( [[[0.1, -0.2, 0.5], [-0.2, 0.7, 0.7], [0.8, -0.2, 0.4], [-0.1, 0.2, -0.3]], [[0.5, 0.6, 0.9], [-0.1, -0.3, -0.7], [0.4, -0.2, 0.8], [0.7, 0.8, -0.4]]]) # pyformat: disable blended_points = np.array([[[[0.16, -0.1, 1.18], [0.3864, 0.148, 0.7352]], [[0.38, 0.4, 0.86], [-0.2184, 0.152, 0.0088]], [[-0.05, 0.01, -0.46], [-0.3152, -0.004, -0.1136]]], [[[-0.15240625, 0.69123384, -0.57871905], [0.07776242, 0.33587402, 0.55386645]], [[0.17959584, 0.01269566, 1.22003942], [0.71406514, 0.6187734, -0.43794053]], [[0.67662743, 0.94549789, -0.14946982], [0.88587099, -0.09324637, -0.45012815]]]]) return points, weights, rotations, translations, blended_points
1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/projects/pointnet/train.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Training loop for PointNet v1 on modelnet40.""" # pylint: disable=missing-function-docstring import tensorflow as tf from tensorflow_graphics.datasets import modelnet40 from tensorflow_graphics.nn.layer import pointnet import tqdm # pylint: disable=g-bad-import-order from . import augment # pylint: disable=g-bad-import-order from . import helpers # pylint: disable=g-bad-import-order # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ parser = helpers.ArgumentParser() parser.add("--batch_size", 32) parser.add("--num_epochs", 250) parser.add("--num_points", 2048, help="subsampled (max 2048)") parser.add("--learning_rate", 1e-3, help="initial Adam learning rate") parser.add("--lr_decay", True, help="enable learning rate decay") parser.add("--bn_decay", .5, help="batch norm decay momentum") parser.add("--tb_every", 100, help="tensorboard frequency (iterations)") parser.add("--ev_every", 308, help="evaluation frequency (iterations)") parser.add("--augment", True, help="use augmentations") parser.add("--tqdm", True, help="enable the progress bar") FLAGS = parser.parse_args() # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ if FLAGS.lr_decay: lr_scheduler = tf.keras.optimizers.schedules.ExponentialDecay( FLAGS.learning_rate, decay_steps=6250, #< 200.000 / 32 (batch size) (from original pointnet) decay_rate=0.7, staircase=True) optimizer = tf.keras.optimizers.Adam(learning_rate=lr_scheduler) else: optimizer = tf.keras.optimizers.Adam(learning_rate=FLAGS.learning_rate) # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ model = pointnet.PointNetVanillaClassifier( num_classes=40, momentum=FLAGS.bn_decay) # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ @tf.function def wrapped_tf_function(points, label): """Performs one step of minimization of the loss.""" # --- subsampling (order DO matter) points = points[0:FLAGS.num_points, ...] # --- augmentation if FLAGS.augment: points = tf.map_fn(augment.rotate, points) points = augment.jitter(points) # --- training with tf.GradientTape() as tape: logits = model(points, training=True) loss = model.loss(label, logits) variables = model.trainable_variables gradients = tape.gradient(loss, variables) optimizer.apply_gradients(zip(gradients, variables)) return loss def train(example): """Performs one step of minimization of the loss and populates the summary.""" points = example["points"] label = example["label"] step = optimizer.iterations.numpy() # --- optimize loss = wrapped_tf_function(points, label) if step % FLAGS.tb_every == 0: tf.summary.scalar(name="loss", data=loss, step=step) # --- report rate in summaries if FLAGS.lr_decay and step % FLAGS.tb_every == 0: tf.summary.scalar(name="learning_rate", data=lr_scheduler(step), step=step) # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ def evaluate(): """Identify the best accuracy reached during training.""" step = optimizer.iterations.numpy() if "best_accuracy" not in evaluate.__dict__: evaluate.best_accuracy = 0 if step % FLAGS.ev_every != 0: return evaluate.best_accuracy aggregator = tf.keras.metrics.SparseCategoricalAccuracy() for example in ds_test: points, labels = example["points"], example["label"] logits = model(points, training=False) aggregator.update_state(labels, logits) accuracy = aggregator.result() evaluate.best_accuracy = max(accuracy, evaluate.best_accuracy) tf.summary.scalar(name="accuracy_test", data=accuracy, step=step) return evaluate.best_accuracy # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ ds_train, info = modelnet40.ModelNet40.load(split="train", with_info=True) num_examples = info.splits["train"].num_examples ds_train = ds_train.shuffle(num_examples, reshuffle_each_iteration=True) ds_train = ds_train.repeat(FLAGS.num_epochs) ds_train = ds_train.batch(FLAGS.batch_size) ds_test = modelnet40.ModelNet40.load(split="test").batch(FLAGS.batch_size) # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ try: helpers.setup_tensorboard(FLAGS) helpers.summary_command(parser, FLAGS) total = tf.data.experimental.cardinality(ds_train).numpy() pbar = tqdm.tqdm(ds_train, leave=False, total=total, disable=not FLAGS.tqdm) for train_example in pbar: train(train_example) best_accuracy = evaluate() pbar.set_postfix_str("best accuracy: {:.3f}".format(best_accuracy)) except KeyboardInterrupt: helpers.handle_keyboard_interrupt(FLAGS)
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Training loop for PointNet v1 on modelnet40.""" # pylint: disable=missing-function-docstring import tensorflow as tf from tensorflow_graphics.datasets import modelnet40 from tensorflow_graphics.nn.layer import pointnet import tqdm # pylint: disable=g-bad-import-order from . import augment # pylint: disable=g-bad-import-order from . import helpers # pylint: disable=g-bad-import-order # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ parser = helpers.ArgumentParser() parser.add("--batch_size", 32) parser.add("--num_epochs", 250) parser.add("--num_points", 2048, help="subsampled (max 2048)") parser.add("--learning_rate", 1e-3, help="initial Adam learning rate") parser.add("--lr_decay", True, help="enable learning rate decay") parser.add("--bn_decay", .5, help="batch norm decay momentum") parser.add("--tb_every", 100, help="tensorboard frequency (iterations)") parser.add("--ev_every", 308, help="evaluation frequency (iterations)") parser.add("--augment", True, help="use augmentations") parser.add("--tqdm", True, help="enable the progress bar") FLAGS = parser.parse_args() # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ if FLAGS.lr_decay: lr_scheduler = tf.keras.optimizers.schedules.ExponentialDecay( FLAGS.learning_rate, decay_steps=6250, #< 200.000 / 32 (batch size) (from original pointnet) decay_rate=0.7, staircase=True) optimizer = tf.keras.optimizers.Adam(learning_rate=lr_scheduler) else: optimizer = tf.keras.optimizers.Adam(learning_rate=FLAGS.learning_rate) # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ model = pointnet.PointNetVanillaClassifier( num_classes=40, momentum=FLAGS.bn_decay) # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ @tf.function def wrapped_tf_function(points, label): """Performs one step of minimization of the loss.""" # --- subsampling (order DO matter) points = points[0:FLAGS.num_points, ...] # --- augmentation if FLAGS.augment: points = tf.map_fn(augment.rotate, points) points = augment.jitter(points) # --- training with tf.GradientTape() as tape: logits = model(points, training=True) loss = model.loss(label, logits) variables = model.trainable_variables gradients = tape.gradient(loss, variables) optimizer.apply_gradients(zip(gradients, variables)) return loss def train(example): """Performs one step of minimization of the loss and populates the summary.""" points = example["points"] label = example["label"] step = optimizer.iterations.numpy() # --- optimize loss = wrapped_tf_function(points, label) if step % FLAGS.tb_every == 0: tf.summary.scalar(name="loss", data=loss, step=step) # --- report rate in summaries if FLAGS.lr_decay and step % FLAGS.tb_every == 0: tf.summary.scalar(name="learning_rate", data=lr_scheduler(step), step=step) # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ def evaluate(): """Identify the best accuracy reached during training.""" step = optimizer.iterations.numpy() if "best_accuracy" not in evaluate.__dict__: evaluate.best_accuracy = 0 if step % FLAGS.ev_every != 0: return evaluate.best_accuracy aggregator = tf.keras.metrics.SparseCategoricalAccuracy() for example in ds_test: points, labels = example["points"], example["label"] logits = model(points, training=False) aggregator.update_state(labels, logits) accuracy = aggregator.result() evaluate.best_accuracy = max(accuracy, evaluate.best_accuracy) tf.summary.scalar(name="accuracy_test", data=accuracy, step=step) return evaluate.best_accuracy # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ ds_train, info = modelnet40.ModelNet40.load(split="train", with_info=True) num_examples = info.splits["train"].num_examples ds_train = ds_train.shuffle(num_examples, reshuffle_each_iteration=True) ds_train = ds_train.repeat(FLAGS.num_epochs) ds_train = ds_train.batch(FLAGS.batch_size) ds_test = modelnet40.ModelNet40.load(split="test").batch(FLAGS.batch_size) # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ try: helpers.setup_tensorboard(FLAGS) helpers.summary_command(parser, FLAGS) total = tf.data.experimental.cardinality(ds_train).numpy() pbar = tqdm.tqdm(ds_train, leave=False, total=total, disable=not FLAGS.tqdm) for train_example in pbar: train(train_example) best_accuracy = evaluate() pbar.set_postfix_str("best accuracy: {:.3f}".format(best_accuracy)) except KeyboardInterrupt: helpers.handle_keyboard_interrupt(FLAGS)
-1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/geometry/transformation/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Transformation module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import dual_quaternion from tensorflow_graphics.geometry.transformation import euler from tensorflow_graphics.geometry.transformation import linear_blend_skinning from tensorflow_graphics.geometry.transformation import look_at from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_2d from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.transformation. __all__ = _export_api.get_modules()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Transformation module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import dual_quaternion from tensorflow_graphics.geometry.transformation import euler from tensorflow_graphics.geometry.transformation import linear_blend_skinning from tensorflow_graphics.geometry.transformation import look_at from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_2d from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.transformation. __all__ = _export_api.get_modules()
-1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/nn/layer/graph_convolution.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements graph convolutions layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import tensorflow_graphics.geometry.convolution.graph_convolution as gc from tensorflow_graphics.util import export_api def feature_steered_convolution_layer( data, neighbors, sizes, translation_invariant=True, num_weight_matrices=8, num_output_channels=None, initializer=tf.compat.v1.truncated_normal_initializer(stddev=0.1), name=None, var_name=None): # pyformat: disable """Wraps the function `feature_steered_convolution` as a TensorFlow layer. The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. Note: In the following, A1 to An are optional batch dimensions. Args: data: A `float` tensor with shape `[A1, ..., An, V, C]`. neighbors: A SparseTensor with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. For a mesh, a common choice for the neighborhood of vertex `i` would be the vertices in the K-ring of `i` (including `i` itself). Each vertex must have at least one neighbor. For a faithful implementation of the FeaStNet paper, neighbors should be a row-normalized weight matrix corresponding to the graph adjacency matrix with self-edges: `neighbors[A1, ..., An, i, j] > 0` if vertex `i` and `j` are neighbors, `neighbors[A1, ..., An, i, i] > 0` for all `i`, and `sum(neighbors, axis=-1)[A1, ..., An, i] == 1.0` for all `i`. These requirements are relaxed in this implementation. sizes: An `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. As an example, consider an input consisting of three graphs `G0`, `G1`, and `G2` with `V0`, `V1` and `V2` vertices respectively. The padded input would have the following shapes: `data.shape = [3, V, C]`, and `neighbors.shape = [3, V, V]`, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]`. `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph `Gi`. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. translation_invariant: A `bool`. If `True` the assignment of features to weight matrices will be invariant to translation. num_weight_matrices: An `int` specifying the number of weight matrices used in the convolution. num_output_channels: An optional `int` specifying the number of channels in the output. If `None` then `num_output_channels = C`. initializer: An initializer for the trainable variables. name: A (name_scope) name for this op. Passed through to feature_steered_convolution(). var_name: A (var_scope) name for the variables. Defaults to `graph_convolution_feature_steered_convolution_weights`. Returns: Tensor with shape `[A1, ..., An, V, num_output_channels]`. """ # pyformat: enable with tf.compat.v1.variable_scope( var_name, default_name='graph_convolution_feature_steered_convolution_weights'): # Skips shape validation to avoid redundancy with # feature_steered_convolution(). data = tf.convert_to_tensor(value=data) in_channels = tf.compat.v1.dimension_value(data.shape[-1]) if num_output_channels is None: out_channels = in_channels else: out_channels = num_output_channels var_u = tf.compat.v1.get_variable( shape=(in_channels, num_weight_matrices), dtype=data.dtype, initializer=initializer, name='u') if translation_invariant: var_v = -var_u else: var_v = tf.compat.v1.get_variable( shape=(in_channels, num_weight_matrices), dtype=data.dtype, initializer=initializer, name='v') var_c = tf.compat.v1.get_variable( shape=(num_weight_matrices), dtype=data.dtype, initializer=initializer, name='c') var_w = tf.compat.v1.get_variable( shape=(num_weight_matrices, in_channels, out_channels), dtype=data.dtype, initializer=initializer, name='w') var_b = tf.compat.v1.get_variable( shape=(out_channels), dtype=data.dtype, initializer=initializer, name='b') return gc.feature_steered_convolution( data=data, neighbors=neighbors, sizes=sizes, var_u=var_u, var_v=var_v, var_c=var_c, var_w=var_w, var_b=var_b, name=name) class FeatureSteeredConvolutionKerasLayer(tf.keras.layers.Layer): """Wraps the function `feature_steered_convolution` as a Keras layer.""" def __init__(self, translation_invariant=True, num_weight_matrices=8, num_output_channels=None, initializer=None, name=None, **kwargs): """Initializes FeatureSteeredConvolutionKerasLayer. Args: translation_invariant: A `bool`. If `True` the assignment of features to weight matrices will be invariant to translation. num_weight_matrices: An `int` specifying the number of weight matrices used in the convolution. num_output_channels: An optional `int` specifying the number of channels in the output. If `None` then `num_output_channels` will be the same as the input dimensionality. initializer: An initializer for the trainable variables. If `None`, defaults to `tf.compat.v1.truncated_normal_initializer(stddev=0.1)`. name: A name for this layer. **kwargs: Additional keyword arguments passed to the base layer. """ super(FeatureSteeredConvolutionKerasLayer, self).__init__( name=name, **kwargs) self._num_weight_matrices = num_weight_matrices self._num_output_channels = num_output_channels self._translation_invariant = translation_invariant if initializer is None: self._initializer = tf.compat.v1.truncated_normal_initializer(stddev=0.1) else: self._initializer = initializer def build(self, input_shape): """Initializes the trainable weights.""" in_channels = tf.TensorShape(input_shape[0]).as_list()[-1] if self._num_output_channels is None: out_channels = in_channels else: out_channels = self._num_output_channels dtype = self.dtype num_weight_matrices = self._num_weight_matrices initializer = self._initializer self.var_u = self.add_weight( shape=(in_channels, num_weight_matrices), dtype=dtype, initializer=initializer, name='u') if self._translation_invariant: self.var_v = -self.var_u else: self.var_v = self.add_weight( shape=(in_channels, num_weight_matrices), dtype=dtype, initializer=initializer, name='v') self.var_c = self.add_weight( shape=(num_weight_matrices,), dtype=dtype, initializer=initializer, name='c') self.var_w = self.add_weight( shape=(num_weight_matrices, in_channels, out_channels), dtype=dtype, initializer=initializer, name='w', trainable=True) self.var_b = self.add_weight( shape=(out_channels,), dtype=dtype, initializer=initializer, name='b', trainable=True) def call(self, inputs, **kwargs): # pyformat: disable """Executes the convolution. The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. Note: In the following, A1 to An are optional batch dimensions. Args: inputs: A list of two tensors `[data, neighbors]`. `data` is a `float` tensor with shape `[A1, ..., An, V, C]`. `neighbors` is a `SparseTensor` with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. For a mesh, a common choice for the neighborhood of vertex `i` would be the vertices in the K-ring of `i` (including `i` itself). Each vertex must have at least one neighbor. For a faithful implementation of the FeaStNet paper, neighbors should be a row-normalized weight matrix corresponding to the graph adjacency matrix with self-edges: `neighbors[A1, ..., An, i, j] > 0` if vertex `j` is a neighbor of vertex `i`, and `neighbors[A1, ..., An, i, i] > 0` for all `i`, and `sum(neighbors, axis=-1)[A1, ..., An, i] == 1.0` for all `i`. These requirements are relaxed in this implementation. **kwargs: A dictionary containing the key `sizes`, which is an `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. As an example usage of `sizes`, consider an input consisting of three graphs `G0`, `G1`, and `G2` with `V0`, `V1`, and `V2` vertices respectively. The padded input would have the shapes `data.shape = [3, V, C]`, and `neighbors.shape = [3, V, V]`, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]`. `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph `Gi`. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. Returns: Tensor with shape `[A1, ..., An, V, num_output_channels]`. """ # pyformat: enable sizes = kwargs.get('sizes', None) return gc.feature_steered_convolution( data=inputs[0], neighbors=inputs[1], sizes=sizes, var_u=self.var_u, var_v=self.var_v, var_c=self.var_c, var_w=self.var_w, var_b=self.var_b) class DynamicGraphConvolutionKerasLayer(tf.keras.layers.Layer): """A keras layer for dynamic graph convolutions. Dynamic GraphCNN for Learning on Point Clouds Yue Wang, Yongbin Sun, Ziwei Liu, Sanjay E. Sarma, Michael Bronstein, and Justin Solomon. https://arxiv.org/abs/1801.07829 This layer implements an instance of the graph convolutional operation described in the paper above, specifically a graph convolution block with a single edge filtering layer. This implementation is intended to demonstrate how `graph_convolution.edge_convolution_template` can be wrapped to implement a variety of edge convolutional methods. This implementation is slightly generalized version to what is described in the paper in that here variable sized neighborhoods are allowed rather than forcing a fixed size k-neighbors. Users must provide the neighborhoods as input. """ def __init__(self, num_output_channels, reduction, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name=None, **kwargs): """Initializes DynamicGraphConvolutionKerasLayer. Args: num_output_channels: An `int` specifying the number of output channels. reduction: Either 'weighted' or 'max'. Specifies the reduction over neighborhood edge features as described in the paper above. activation: The `activation` argument of `tf.keras.layers.Conv1D`. use_bias: The `use_bias` argument of `tf.keras.layers.Conv1D`. kernel_initializer: The `kernel_initializer` argument of `tf.keras.layers.Conv1D`. bias_initializer: The `bias_initializer` argument of `tf.keras.layers.Conv1D`. kernel_regularizer: The `kernel_regularizer` argument of `tf.keras.layers.Conv1D`. bias_regularizer: The `bias_regularizer` argument of `tf.keras.layers.Conv1D`. activity_regularizer: The `activity_regularizer` argument of `tf.keras.layers.Conv1D`. kernel_constraint: The `kernel_constraint` argument of `tf.keras.layers.Conv1D`. bias_constraint: The `bias_constraint` argument of `tf.keras.layers.Conv1D`. name: A name for this layer. **kwargs: Additional keyword arguments passed to the base layer. """ super(DynamicGraphConvolutionKerasLayer, self).__init__( name=name, **kwargs) self._num_output_channels = num_output_channels self._reduction = reduction self._activation = activation self._use_bias = use_bias self._kernel_initializer = kernel_initializer self._bias_initializer = bias_initializer self._kernel_regularizer = kernel_regularizer self._bias_regularizer = bias_regularizer self._activity_regularizer = activity_regularizer self._kernel_constraint = kernel_constraint self._bias_constraint = bias_constraint def build(self, input_shape): # pylint: disable=unused-argument """Initializes the layer weights.""" self._conv1d_layer = tf.keras.layers.Conv1D( filters=self._num_output_channels, kernel_size=1, strides=1, padding='valid', activation=self._activation, use_bias=self._use_bias, kernel_initializer=self._kernel_initializer, bias_initializer=self._bias_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer, activity_regularizer=self._activity_regularizer, kernel_constraint=self._kernel_constraint, bias_constraint=self._bias_constraint) def call(self, inputs, **kwargs): # pyformat: disable """Executes the convolution. The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. Note: In the following, A1 to An are optional batch dimensions. Args: inputs: A list of two tensors `[data, neighbors]`. `data` is a `float` tensor with shape `[A1, ..., An, V, C]`. `neighbors` is a `SparseTensor` with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. For a mesh, a common choice for the neighborhood of vertex `i` would be the vertices in the K-ring of `i` (including `i` itself). Each vertex must have at least one neighbor. For `reduction='weighted'`, `neighbors` should be a row-normalized matrix: `sum(neighbors, axis=-1)[A1, ..., An, i] == 1.0` for all `i`, although this is not enforced in the implementation in case different neighbor weighting schemes are desired. **kwargs: A dictionary containing the key `sizes`, which is an `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. As an example usage of `sizes`, consider an input consisting of three graphs `G0`, `G1`, and `G2` with `V0`, `V1`, and `V2` vertices respectively. The padded input would have the shapes `data.shape = [3, V, C]`, and `neighbors.shape = [3, V, V]`, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]`. `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph `Gi`. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. Returns: Tensor with shape `[A1, ..., An, V, num_output_channels]`. """ # pyformat: enable def _edge_convolution(vertices, neighbors, conv1d_layer): r"""The edge filtering op passed to `edge_convolution_template`. This instance implements the edge function $$h_{\theta}(x, y) = MLP_{\theta}([x, y - x])$$ Args: vertices: A 2-D Tensor with shape `[D1, D2]`. neighbors: A 2-D Tensor with the same shape and type as `vertices`. conv1d_layer: A callable 1d convolution layer. Returns: A 2-D Tensor with shape `[D1, D3]`. """ concat_features = tf.concat( values=[vertices, neighbors - vertices], axis=-1) concat_features = tf.expand_dims(concat_features, 0) convolved_features = conv1d_layer(concat_features) convolved_features = tf.squeeze(input=convolved_features, axis=(0,)) return convolved_features sizes = kwargs.get('sizes', None) return gc.edge_convolution_template( data=inputs[0], neighbors=inputs[1], sizes=sizes, edge_function=_edge_convolution, reduction=self._reduction, edge_function_kwargs={'conv1d_layer': self._conv1d_layer}) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements graph convolutions layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import tensorflow_graphics.geometry.convolution.graph_convolution as gc from tensorflow_graphics.util import export_api def feature_steered_convolution_layer( data, neighbors, sizes, translation_invariant=True, num_weight_matrices=8, num_output_channels=None, initializer=tf.compat.v1.truncated_normal_initializer(stddev=0.1), name=None, var_name=None): # pyformat: disable """Wraps the function `feature_steered_convolution` as a TensorFlow layer. The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. Note: In the following, A1 to An are optional batch dimensions. Args: data: A `float` tensor with shape `[A1, ..., An, V, C]`. neighbors: A SparseTensor with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. For a mesh, a common choice for the neighborhood of vertex `i` would be the vertices in the K-ring of `i` (including `i` itself). Each vertex must have at least one neighbor. For a faithful implementation of the FeaStNet paper, neighbors should be a row-normalized weight matrix corresponding to the graph adjacency matrix with self-edges: `neighbors[A1, ..., An, i, j] > 0` if vertex `i` and `j` are neighbors, `neighbors[A1, ..., An, i, i] > 0` for all `i`, and `sum(neighbors, axis=-1)[A1, ..., An, i] == 1.0` for all `i`. These requirements are relaxed in this implementation. sizes: An `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. As an example, consider an input consisting of three graphs `G0`, `G1`, and `G2` with `V0`, `V1` and `V2` vertices respectively. The padded input would have the following shapes: `data.shape = [3, V, C]`, and `neighbors.shape = [3, V, V]`, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]`. `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph `Gi`. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. translation_invariant: A `bool`. If `True` the assignment of features to weight matrices will be invariant to translation. num_weight_matrices: An `int` specifying the number of weight matrices used in the convolution. num_output_channels: An optional `int` specifying the number of channels in the output. If `None` then `num_output_channels = C`. initializer: An initializer for the trainable variables. name: A (name_scope) name for this op. Passed through to feature_steered_convolution(). var_name: A (var_scope) name for the variables. Defaults to `graph_convolution_feature_steered_convolution_weights`. Returns: Tensor with shape `[A1, ..., An, V, num_output_channels]`. """ # pyformat: enable with tf.compat.v1.variable_scope( var_name, default_name='graph_convolution_feature_steered_convolution_weights'): # Skips shape validation to avoid redundancy with # feature_steered_convolution(). data = tf.convert_to_tensor(value=data) in_channels = tf.compat.v1.dimension_value(data.shape[-1]) if num_output_channels is None: out_channels = in_channels else: out_channels = num_output_channels var_u = tf.compat.v1.get_variable( shape=(in_channels, num_weight_matrices), dtype=data.dtype, initializer=initializer, name='u') if translation_invariant: var_v = -var_u else: var_v = tf.compat.v1.get_variable( shape=(in_channels, num_weight_matrices), dtype=data.dtype, initializer=initializer, name='v') var_c = tf.compat.v1.get_variable( shape=(num_weight_matrices), dtype=data.dtype, initializer=initializer, name='c') var_w = tf.compat.v1.get_variable( shape=(num_weight_matrices, in_channels, out_channels), dtype=data.dtype, initializer=initializer, name='w') var_b = tf.compat.v1.get_variable( shape=(out_channels), dtype=data.dtype, initializer=initializer, name='b') return gc.feature_steered_convolution( data=data, neighbors=neighbors, sizes=sizes, var_u=var_u, var_v=var_v, var_c=var_c, var_w=var_w, var_b=var_b, name=name) class FeatureSteeredConvolutionKerasLayer(tf.keras.layers.Layer): """Wraps the function `feature_steered_convolution` as a Keras layer.""" def __init__(self, translation_invariant=True, num_weight_matrices=8, num_output_channels=None, initializer=None, name=None, **kwargs): """Initializes FeatureSteeredConvolutionKerasLayer. Args: translation_invariant: A `bool`. If `True` the assignment of features to weight matrices will be invariant to translation. num_weight_matrices: An `int` specifying the number of weight matrices used in the convolution. num_output_channels: An optional `int` specifying the number of channels in the output. If `None` then `num_output_channels` will be the same as the input dimensionality. initializer: An initializer for the trainable variables. If `None`, defaults to `tf.compat.v1.truncated_normal_initializer(stddev=0.1)`. name: A name for this layer. **kwargs: Additional keyword arguments passed to the base layer. """ super(FeatureSteeredConvolutionKerasLayer, self).__init__( name=name, **kwargs) self._num_weight_matrices = num_weight_matrices self._num_output_channels = num_output_channels self._translation_invariant = translation_invariant if initializer is None: self._initializer = tf.compat.v1.truncated_normal_initializer(stddev=0.1) else: self._initializer = initializer def build(self, input_shape): """Initializes the trainable weights.""" in_channels = tf.TensorShape(input_shape[0]).as_list()[-1] if self._num_output_channels is None: out_channels = in_channels else: out_channels = self._num_output_channels dtype = self.dtype num_weight_matrices = self._num_weight_matrices initializer = self._initializer self.var_u = self.add_weight( shape=(in_channels, num_weight_matrices), dtype=dtype, initializer=initializer, name='u') if self._translation_invariant: self.var_v = -self.var_u else: self.var_v = self.add_weight( shape=(in_channels, num_weight_matrices), dtype=dtype, initializer=initializer, name='v') self.var_c = self.add_weight( shape=(num_weight_matrices,), dtype=dtype, initializer=initializer, name='c') self.var_w = self.add_weight( shape=(num_weight_matrices, in_channels, out_channels), dtype=dtype, initializer=initializer, name='w', trainable=True) self.var_b = self.add_weight( shape=(out_channels,), dtype=dtype, initializer=initializer, name='b', trainable=True) def call(self, inputs, **kwargs): # pyformat: disable """Executes the convolution. The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. Note: In the following, A1 to An are optional batch dimensions. Args: inputs: A list of two tensors `[data, neighbors]`. `data` is a `float` tensor with shape `[A1, ..., An, V, C]`. `neighbors` is a `SparseTensor` with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. For a mesh, a common choice for the neighborhood of vertex `i` would be the vertices in the K-ring of `i` (including `i` itself). Each vertex must have at least one neighbor. For a faithful implementation of the FeaStNet paper, neighbors should be a row-normalized weight matrix corresponding to the graph adjacency matrix with self-edges: `neighbors[A1, ..., An, i, j] > 0` if vertex `j` is a neighbor of vertex `i`, and `neighbors[A1, ..., An, i, i] > 0` for all `i`, and `sum(neighbors, axis=-1)[A1, ..., An, i] == 1.0` for all `i`. These requirements are relaxed in this implementation. **kwargs: A dictionary containing the key `sizes`, which is an `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. As an example usage of `sizes`, consider an input consisting of three graphs `G0`, `G1`, and `G2` with `V0`, `V1`, and `V2` vertices respectively. The padded input would have the shapes `data.shape = [3, V, C]`, and `neighbors.shape = [3, V, V]`, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]`. `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph `Gi`. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. Returns: Tensor with shape `[A1, ..., An, V, num_output_channels]`. """ # pyformat: enable sizes = kwargs.get('sizes', None) return gc.feature_steered_convolution( data=inputs[0], neighbors=inputs[1], sizes=sizes, var_u=self.var_u, var_v=self.var_v, var_c=self.var_c, var_w=self.var_w, var_b=self.var_b) class DynamicGraphConvolutionKerasLayer(tf.keras.layers.Layer): """A keras layer for dynamic graph convolutions. Dynamic GraphCNN for Learning on Point Clouds Yue Wang, Yongbin Sun, Ziwei Liu, Sanjay E. Sarma, Michael Bronstein, and Justin Solomon. https://arxiv.org/abs/1801.07829 This layer implements an instance of the graph convolutional operation described in the paper above, specifically a graph convolution block with a single edge filtering layer. This implementation is intended to demonstrate how `graph_convolution.edge_convolution_template` can be wrapped to implement a variety of edge convolutional methods. This implementation is slightly generalized version to what is described in the paper in that here variable sized neighborhoods are allowed rather than forcing a fixed size k-neighbors. Users must provide the neighborhoods as input. """ def __init__(self, num_output_channels, reduction, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name=None, **kwargs): """Initializes DynamicGraphConvolutionKerasLayer. Args: num_output_channels: An `int` specifying the number of output channels. reduction: Either 'weighted' or 'max'. Specifies the reduction over neighborhood edge features as described in the paper above. activation: The `activation` argument of `tf.keras.layers.Conv1D`. use_bias: The `use_bias` argument of `tf.keras.layers.Conv1D`. kernel_initializer: The `kernel_initializer` argument of `tf.keras.layers.Conv1D`. bias_initializer: The `bias_initializer` argument of `tf.keras.layers.Conv1D`. kernel_regularizer: The `kernel_regularizer` argument of `tf.keras.layers.Conv1D`. bias_regularizer: The `bias_regularizer` argument of `tf.keras.layers.Conv1D`. activity_regularizer: The `activity_regularizer` argument of `tf.keras.layers.Conv1D`. kernel_constraint: The `kernel_constraint` argument of `tf.keras.layers.Conv1D`. bias_constraint: The `bias_constraint` argument of `tf.keras.layers.Conv1D`. name: A name for this layer. **kwargs: Additional keyword arguments passed to the base layer. """ super(DynamicGraphConvolutionKerasLayer, self).__init__( name=name, **kwargs) self._num_output_channels = num_output_channels self._reduction = reduction self._activation = activation self._use_bias = use_bias self._kernel_initializer = kernel_initializer self._bias_initializer = bias_initializer self._kernel_regularizer = kernel_regularizer self._bias_regularizer = bias_regularizer self._activity_regularizer = activity_regularizer self._kernel_constraint = kernel_constraint self._bias_constraint = bias_constraint def build(self, input_shape): # pylint: disable=unused-argument """Initializes the layer weights.""" self._conv1d_layer = tf.keras.layers.Conv1D( filters=self._num_output_channels, kernel_size=1, strides=1, padding='valid', activation=self._activation, use_bias=self._use_bias, kernel_initializer=self._kernel_initializer, bias_initializer=self._bias_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer, activity_regularizer=self._activity_regularizer, kernel_constraint=self._kernel_constraint, bias_constraint=self._bias_constraint) def call(self, inputs, **kwargs): # pyformat: disable """Executes the convolution. The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. Note: In the following, A1 to An are optional batch dimensions. Args: inputs: A list of two tensors `[data, neighbors]`. `data` is a `float` tensor with shape `[A1, ..., An, V, C]`. `neighbors` is a `SparseTensor` with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. For a mesh, a common choice for the neighborhood of vertex `i` would be the vertices in the K-ring of `i` (including `i` itself). Each vertex must have at least one neighbor. For `reduction='weighted'`, `neighbors` should be a row-normalized matrix: `sum(neighbors, axis=-1)[A1, ..., An, i] == 1.0` for all `i`, although this is not enforced in the implementation in case different neighbor weighting schemes are desired. **kwargs: A dictionary containing the key `sizes`, which is an `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. As an example usage of `sizes`, consider an input consisting of three graphs `G0`, `G1`, and `G2` with `V0`, `V1`, and `V2` vertices respectively. The padded input would have the shapes `data.shape = [3, V, C]`, and `neighbors.shape = [3, V, V]`, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]`. `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph `Gi`. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. Returns: Tensor with shape `[A1, ..., An, V, num_output_channels]`. """ # pyformat: enable def _edge_convolution(vertices, neighbors, conv1d_layer): r"""The edge filtering op passed to `edge_convolution_template`. This instance implements the edge function $$h_{\theta}(x, y) = MLP_{\theta}([x, y - x])$$ Args: vertices: A 2-D Tensor with shape `[D1, D2]`. neighbors: A 2-D Tensor with the same shape and type as `vertices`. conv1d_layer: A callable 1d convolution layer. Returns: A 2-D Tensor with shape `[D1, D3]`. """ concat_features = tf.concat( values=[vertices, neighbors - vertices], axis=-1) concat_features = tf.expand_dims(concat_features, 0) convolved_features = conv1d_layer(concat_features) convolved_features = tf.squeeze(input=convolved_features, axis=(0,)) return convolved_features sizes = kwargs.get('sizes', None) return gc.edge_convolution_template( data=inputs[0], neighbors=inputs[1], sizes=sizes, edge_function=_edge_convolution, reduction=self._reduction, edge_function_kwargs={'conv1d_layer': self._conv1d_layer}) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/datasets/modelnet40/modelnet40_show.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Visualization in 3D of modelnet40 dataset. See: https://www.tensorflow.org/datasets/api_docs/python/tfds/load """ from absl import app import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # pylint:disable=unused-import from tensorflow_graphics.datasets.modelnet40 import ModelNet40 def main(_): ds_train, _ = ModelNet40.load( split="train", data_dir="~/tensorflow_dataset", with_info=True) for example in ds_train.take(1): points = example["points"] label = example["label"] fig = plt.figure() ax3 = fig.add_subplot(111, projection="3d") ax3.set_title("Example with label {}".format(label)) scatter3 = lambda p, c="r", *args: ax3.scatter(p[:, 0], p[:, 1], p[:, 2], c) scatter3(points) if __name__ == "__main__": app.run(main)
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Visualization in 3D of modelnet40 dataset. See: https://www.tensorflow.org/datasets/api_docs/python/tfds/load """ from absl import app import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # pylint:disable=unused-import from tensorflow_graphics.datasets.modelnet40 import ModelNet40 def main(_): ds_train, _ = ModelNet40.load( split="train", data_dir="~/tensorflow_dataset", with_info=True) for example in ds_train.take(1): points = example["points"] label = example["label"] fig = plt.figure() ax3 = fig.add_subplot(111, projection="3d") ax3.set_title("Example with label {}".format(label)) scatter3 = lambda p, c="r", *args: ax3.scatter(p[:, 0], p[:, 1], p[:, 2], c) scatter3(points) if __name__ == "__main__": app.run(main)
-1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/geometry/convolution/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/rendering/light/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/projects/neural_voxel_renderer/models.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Definition of NVR+ keras model.""" import tensorflow.compat.v1 as tf import tensorflow_graphics.projects.neural_voxel_renderer.layers as layer_utils initializer = tf.keras.initializers.glorot_normal() layers = tf.keras.layers def unet_3x_with_res_in_mid(feat_in, out_filters, norm2d): """Helper function of a Unet with res blocks in the middle.""" e1 = layer_utils.residual_block_2d(feat_in, nfilters=128, strides=(2, 2), normalization=norm2d) # 16x128 e2 = layer_utils.residual_block_2d(e1, nfilters=256, strides=(2, 2), normalization=norm2d) # 8x256 e3 = layer_utils.residual_block_2d(e2, nfilters=512, strides=(2, 2), normalization=norm2d) # 4x512 mid1 = layer_utils.residual_block_2d(e3, nfilters=512, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d mid2 = layer_utils.residual_block_2d(mid1, nfilters=512, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d mid3 = layer_utils.residual_block_2d(mid2, nfilters=512, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d d0 = layer_utils.upconv(mid3, nfilters=256, size=4, strides=1) # 8x256 d1 = layers.concatenate([d0, e2]) # 8x512 d2 = layers.Conv2D(256, kernel_size=4, strides=(1, 1), padding='same', kernel_initializer=initializer)(d1) # 8x256 d3 = layer_utils.upconv(d2, nfilters=128, size=4, strides=1) # 16x128 d4 = layers.concatenate([d3, e1]) # 16x256 d5 = layers.Conv2D(128, kernel_size=4, strides=(1, 1), padding='same', kernel_initializer=initializer)(d4) # 8x256 d6 = layer_utils.upconv(d5, nfilters=64, size=4, strides=1) # 32x64 d7 = layers.concatenate([d6, feat_in]) # 32xN d8 = layers.Conv2D(out_filters, kernel_size=4, strides=(1, 1), padding='same', kernel_initializer=initializer)(d7) # 32xout return d8 def neural_voxel_renderer_plus(voxels, rerendering, light_pos, size=4, norm2d='batchnorm', norm3d='batchnorm'): """Neural Voxel Renderer + keras model.""" with tf.name_scope('Network/'): voxels = layers.Input(tensor=voxels) rerendering = layers.Input(tensor=rerendering) light_pos = layers.Input(tensor=light_pos) nf_2d = 512 with tf.name_scope('VoxelProcessing'): vol0_a = layer_utils.conv_block_3d(voxels, nfilters=16, size=size, strides=2, normalization=norm3d) # 64x64x64x16 vol0_b = layer_utils.conv_block_3d(vol0_a, nfilters=16, size=size, strides=1, normalization=norm3d) # 64x64x64x16 vol1_a = layer_utils.conv_block_3d(vol0_b, nfilters=16, size=size, strides=2, normalization=norm3d) # 32x32x32x16 vol1_b = layer_utils.conv_block_3d(vol1_a, nfilters=32, size=size, strides=1, normalization=norm3d) # 32x32x32x32 vol1_c = layer_utils.conv_block_3d(vol1_b, nfilters=32, size=size, strides=1, normalization=norm3d) # 32x32x32x32 shortcut = vol1_c vol_a1 = layer_utils.residual_block_3d(vol1_c, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a2 = layer_utils.residual_block_3d(vol_a1, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a3 = layer_utils.residual_block_3d(vol_a2, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a4 = layer_utils.residual_block_3d(vol_a3, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a5 = layer_utils.residual_block_3d(vol_a4, 32, strides=(1, 1, 1), normalization=norm3d) # 32x encoded_vol = layers.add([shortcut, vol_a5]) encoded_vol = layers.Reshape([32, 32, 32*32])(encoded_vol) encoded_vol = layers.Conv2D(nf_2d, kernel_size=1, strides=(1, 1), padding='same', kernel_initializer=initializer)(encoded_vol) latent_projection = layers.LeakyReLU()(encoded_vol) # 32x32x512 with tf.name_scope('ProjectionProcessing'): shortcut = latent_projection # 32x32xnf_2d e1 = layer_utils.residual_block_2d(latent_projection, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e2 = layer_utils.residual_block_2d(e1, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e3 = layer_utils.residual_block_2d(e2, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e4 = layer_utils.residual_block_2d(e3, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e5 = layer_utils.residual_block_2d(e4, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d encoded_proj = layers.add([shortcut, e5]) # 32x32xnf_2d with tf.name_scope('LightProcessing'): fc_light = layers.Dense(64, kernel_initializer=initializer)(light_pos) light_code = layers.Dense(64, kernel_initializer=initializer)(fc_light) light_code = \ layers.Lambda(lambda v: tf.tile(v[0], [1, 32*32]))([light_code]) light_code = layers.Reshape((32, 32, 64))(light_code) # 32x32x64 with tf.name_scope('Merger'): latent_code_final = layers.concatenate([encoded_proj, light_code]) latent_code_final = layer_utils.conv_block_2d(latent_code_final, nfilters=nf_2d, size=size, strides=1, normalization=norm3d) shortcut = latent_code_final m1 = layer_utils.residual_block_2d(latent_code_final, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m2 = layer_utils.residual_block_2d(m1, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m3 = layer_utils.residual_block_2d(m2, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m4 = layer_utils.residual_block_2d(m3, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m5 = layer_utils.residual_block_2d(m4, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d latent_code_final2 = layers.add([shortcut, m5]) # 32x32xnf_2d with tf.name_scope('Decoder'): d7 = layer_utils.conv_t_block_2d(latent_code_final2, nfilters=128, size=size, strides=2, normalization=norm2d) # 64x64x128 d7 = layer_utils.conv_block_2d(d7, nfilters=128, size=size, strides=1, normalization=norm2d) # 64x64x128 d8 = layer_utils.conv_t_block_2d(d7, nfilters=64, size=size, strides=2, normalization=norm2d) # 128x128x64 d8 = layer_utils.conv_block_2d(d8, nfilters=64, size=size, strides=1, normalization=norm2d) # 128x128x64 d9 = layer_utils.conv_t_block_2d(d8, nfilters=32, size=size, strides=2, normalization=norm2d) # 256x256x32 d9 = layer_utils.conv_block_2d(d9, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x256x32 rendered_image = layers.Conv2D(32, size, strides=1, padding='same', kernel_initializer=initializer, use_bias=False)(d9) # 256x256x3 with tf.name_scope('ImageProcessingNetwork'): ec1 = layer_utils.conv_block_2d(rerendering, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x ec2 = layer_utils.conv_block_2d(ec1, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x with tf.name_scope('NeuralRerenderingNetwork'): latent_img = layers.add([rendered_image, ec2]) target_code = unet_3x_with_res_in_mid(latent_img, 32, norm2d=norm2d) out0 = layer_utils.conv_block_2d(target_code, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x predicted_image = layers.Conv2D(3, size, strides=1, padding='same', kernel_initializer=initializer, use_bias=False)(out0) # 256x256x3 return tf.keras.Model(inputs=[voxels, rerendering, light_pos], outputs=[predicted_image]) def neural_voxel_renderer_plus_tf2(size=4, norm2d='batchnorm', norm3d='batchnorm'): """Neural Voxel Renderer + keras model for tf2.""" with tf.name_scope('Network/'): voxels = layers.Input(shape=[128, 128, 128, 4]) rerendering = layers.Input(shape=[256, 256, 3]) light_pos = layers.Input(shape=[3]) nf_2d = 512 with tf.name_scope('VoxelProcessing'): vol0_a = layer_utils.conv_block_3d(voxels, nfilters=16, size=size, strides=2, normalization=norm3d) # 64x64x64x16 vol0_b = layer_utils.conv_block_3d(vol0_a, nfilters=16, size=size, strides=1, normalization=norm3d) # 64x64x64x16 vol1_a = layer_utils.conv_block_3d(vol0_b, nfilters=16, size=size, strides=2, normalization=norm3d) # 32x32x32x16 vol1_b = layer_utils.conv_block_3d(vol1_a, nfilters=32, size=size, strides=1, normalization=norm3d) # 32x32x32x32 vol1_c = layer_utils.conv_block_3d(vol1_b, nfilters=32, size=size, strides=1, normalization=norm3d) # 32x32x32x32 shortcut = vol1_c vol_a1 = layer_utils.residual_block_3d(vol1_c, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a2 = layer_utils.residual_block_3d(vol_a1, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a3 = layer_utils.residual_block_3d(vol_a2, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a4 = layer_utils.residual_block_3d(vol_a3, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a5 = layer_utils.residual_block_3d(vol_a4, 32, strides=(1, 1, 1), normalization=norm3d) # 32x encoded_vol = layers.add([shortcut, vol_a5]) encoded_vol = layers.Reshape([32, 32, 32*32])(encoded_vol) encoded_vol = layers.Conv2D(nf_2d, kernel_size=1, strides=(1, 1), padding='same', kernel_initializer=initializer)(encoded_vol) latent_projection = layers.LeakyReLU()(encoded_vol) # 32x32x512 with tf.name_scope('ProjectionProcessing'): shortcut = latent_projection # 32x32xnf_2d e1 = layer_utils.residual_block_2d(latent_projection, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e2 = layer_utils.residual_block_2d(e1, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e3 = layer_utils.residual_block_2d(e2, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e4 = layer_utils.residual_block_2d(e3, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e5 = layer_utils.residual_block_2d(e4, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d encoded_proj = layers.add([shortcut, e5]) # 32x32xnf_2d with tf.name_scope('LightProcessing'): fc_light = layers.Dense(64, kernel_initializer=initializer)(light_pos) light_code = layers.Dense(64, kernel_initializer=initializer)(fc_light) light_code = \ layers.Lambda(lambda v: tf.tile(v[0], [1, 32*32]))([light_code]) light_code = layers.Reshape((32, 32, 64))(light_code) # 32x32x64 with tf.name_scope('Merger'): latent_code_final = layers.concatenate([encoded_proj, light_code]) latent_code_final = layer_utils.conv_block_2d(latent_code_final, nfilters=nf_2d, size=size, strides=1, normalization=norm3d) shortcut = latent_code_final m1 = layer_utils.residual_block_2d(latent_code_final, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m2 = layer_utils.residual_block_2d(m1, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m3 = layer_utils.residual_block_2d(m2, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m4 = layer_utils.residual_block_2d(m3, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m5 = layer_utils.residual_block_2d(m4, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d latent_code_final2 = layers.add([shortcut, m5]) # 32x32xnf_2d with tf.name_scope('Decoder'): d7 = layer_utils.conv_t_block_2d(latent_code_final2, nfilters=128, size=size, strides=2, normalization=norm2d) # 64x64x128 d7 = layer_utils.conv_block_2d(d7, nfilters=128, size=size, strides=1, normalization=norm2d) # 64x64x128 d8 = layer_utils.conv_t_block_2d(d7, nfilters=64, size=size, strides=2, normalization=norm2d) # 128x128x64 d8 = layer_utils.conv_block_2d(d8, nfilters=64, size=size, strides=1, normalization=norm2d) # 128x128x64 d9 = layer_utils.conv_t_block_2d(d8, nfilters=32, size=size, strides=2, normalization=norm2d) # 256x256x32 d9 = layer_utils.conv_block_2d(d9, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x256x32 rendered_image = layers.Conv2D(32, size, strides=1, padding='same', kernel_initializer=initializer, use_bias=False)(d9) # 256x256x3 with tf.name_scope('ImageProcessingNetwork'): ec1 = layer_utils.conv_block_2d(rerendering, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x ec2 = layer_utils.conv_block_2d(ec1, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x with tf.name_scope('NeuralRerenderingNetwork'): latent_img = layers.add([rendered_image, ec2]) target_code = unet_3x_with_res_in_mid(latent_img, 32, norm2d=norm2d) out0 = layer_utils.conv_block_2d(target_code, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x predicted_image = layers.Conv2D(3, size, strides=1, padding='same', kernel_initializer=initializer, use_bias=False)(out0) # 256x256x3 return tf.keras.Model(inputs=[voxels, rerendering, light_pos], outputs=[predicted_image])
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Definition of NVR+ keras model.""" import tensorflow.compat.v1 as tf import tensorflow_graphics.projects.neural_voxel_renderer.layers as layer_utils initializer = tf.keras.initializers.glorot_normal() layers = tf.keras.layers def unet_3x_with_res_in_mid(feat_in, out_filters, norm2d): """Helper function of a Unet with res blocks in the middle.""" e1 = layer_utils.residual_block_2d(feat_in, nfilters=128, strides=(2, 2), normalization=norm2d) # 16x128 e2 = layer_utils.residual_block_2d(e1, nfilters=256, strides=(2, 2), normalization=norm2d) # 8x256 e3 = layer_utils.residual_block_2d(e2, nfilters=512, strides=(2, 2), normalization=norm2d) # 4x512 mid1 = layer_utils.residual_block_2d(e3, nfilters=512, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d mid2 = layer_utils.residual_block_2d(mid1, nfilters=512, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d mid3 = layer_utils.residual_block_2d(mid2, nfilters=512, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d d0 = layer_utils.upconv(mid3, nfilters=256, size=4, strides=1) # 8x256 d1 = layers.concatenate([d0, e2]) # 8x512 d2 = layers.Conv2D(256, kernel_size=4, strides=(1, 1), padding='same', kernel_initializer=initializer)(d1) # 8x256 d3 = layer_utils.upconv(d2, nfilters=128, size=4, strides=1) # 16x128 d4 = layers.concatenate([d3, e1]) # 16x256 d5 = layers.Conv2D(128, kernel_size=4, strides=(1, 1), padding='same', kernel_initializer=initializer)(d4) # 8x256 d6 = layer_utils.upconv(d5, nfilters=64, size=4, strides=1) # 32x64 d7 = layers.concatenate([d6, feat_in]) # 32xN d8 = layers.Conv2D(out_filters, kernel_size=4, strides=(1, 1), padding='same', kernel_initializer=initializer)(d7) # 32xout return d8 def neural_voxel_renderer_plus(voxels, rerendering, light_pos, size=4, norm2d='batchnorm', norm3d='batchnorm'): """Neural Voxel Renderer + keras model.""" with tf.name_scope('Network/'): voxels = layers.Input(tensor=voxels) rerendering = layers.Input(tensor=rerendering) light_pos = layers.Input(tensor=light_pos) nf_2d = 512 with tf.name_scope('VoxelProcessing'): vol0_a = layer_utils.conv_block_3d(voxels, nfilters=16, size=size, strides=2, normalization=norm3d) # 64x64x64x16 vol0_b = layer_utils.conv_block_3d(vol0_a, nfilters=16, size=size, strides=1, normalization=norm3d) # 64x64x64x16 vol1_a = layer_utils.conv_block_3d(vol0_b, nfilters=16, size=size, strides=2, normalization=norm3d) # 32x32x32x16 vol1_b = layer_utils.conv_block_3d(vol1_a, nfilters=32, size=size, strides=1, normalization=norm3d) # 32x32x32x32 vol1_c = layer_utils.conv_block_3d(vol1_b, nfilters=32, size=size, strides=1, normalization=norm3d) # 32x32x32x32 shortcut = vol1_c vol_a1 = layer_utils.residual_block_3d(vol1_c, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a2 = layer_utils.residual_block_3d(vol_a1, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a3 = layer_utils.residual_block_3d(vol_a2, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a4 = layer_utils.residual_block_3d(vol_a3, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a5 = layer_utils.residual_block_3d(vol_a4, 32, strides=(1, 1, 1), normalization=norm3d) # 32x encoded_vol = layers.add([shortcut, vol_a5]) encoded_vol = layers.Reshape([32, 32, 32*32])(encoded_vol) encoded_vol = layers.Conv2D(nf_2d, kernel_size=1, strides=(1, 1), padding='same', kernel_initializer=initializer)(encoded_vol) latent_projection = layers.LeakyReLU()(encoded_vol) # 32x32x512 with tf.name_scope('ProjectionProcessing'): shortcut = latent_projection # 32x32xnf_2d e1 = layer_utils.residual_block_2d(latent_projection, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e2 = layer_utils.residual_block_2d(e1, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e3 = layer_utils.residual_block_2d(e2, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e4 = layer_utils.residual_block_2d(e3, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e5 = layer_utils.residual_block_2d(e4, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d encoded_proj = layers.add([shortcut, e5]) # 32x32xnf_2d with tf.name_scope('LightProcessing'): fc_light = layers.Dense(64, kernel_initializer=initializer)(light_pos) light_code = layers.Dense(64, kernel_initializer=initializer)(fc_light) light_code = \ layers.Lambda(lambda v: tf.tile(v[0], [1, 32*32]))([light_code]) light_code = layers.Reshape((32, 32, 64))(light_code) # 32x32x64 with tf.name_scope('Merger'): latent_code_final = layers.concatenate([encoded_proj, light_code]) latent_code_final = layer_utils.conv_block_2d(latent_code_final, nfilters=nf_2d, size=size, strides=1, normalization=norm3d) shortcut = latent_code_final m1 = layer_utils.residual_block_2d(latent_code_final, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m2 = layer_utils.residual_block_2d(m1, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m3 = layer_utils.residual_block_2d(m2, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m4 = layer_utils.residual_block_2d(m3, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m5 = layer_utils.residual_block_2d(m4, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d latent_code_final2 = layers.add([shortcut, m5]) # 32x32xnf_2d with tf.name_scope('Decoder'): d7 = layer_utils.conv_t_block_2d(latent_code_final2, nfilters=128, size=size, strides=2, normalization=norm2d) # 64x64x128 d7 = layer_utils.conv_block_2d(d7, nfilters=128, size=size, strides=1, normalization=norm2d) # 64x64x128 d8 = layer_utils.conv_t_block_2d(d7, nfilters=64, size=size, strides=2, normalization=norm2d) # 128x128x64 d8 = layer_utils.conv_block_2d(d8, nfilters=64, size=size, strides=1, normalization=norm2d) # 128x128x64 d9 = layer_utils.conv_t_block_2d(d8, nfilters=32, size=size, strides=2, normalization=norm2d) # 256x256x32 d9 = layer_utils.conv_block_2d(d9, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x256x32 rendered_image = layers.Conv2D(32, size, strides=1, padding='same', kernel_initializer=initializer, use_bias=False)(d9) # 256x256x3 with tf.name_scope('ImageProcessingNetwork'): ec1 = layer_utils.conv_block_2d(rerendering, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x ec2 = layer_utils.conv_block_2d(ec1, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x with tf.name_scope('NeuralRerenderingNetwork'): latent_img = layers.add([rendered_image, ec2]) target_code = unet_3x_with_res_in_mid(latent_img, 32, norm2d=norm2d) out0 = layer_utils.conv_block_2d(target_code, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x predicted_image = layers.Conv2D(3, size, strides=1, padding='same', kernel_initializer=initializer, use_bias=False)(out0) # 256x256x3 return tf.keras.Model(inputs=[voxels, rerendering, light_pos], outputs=[predicted_image]) def neural_voxel_renderer_plus_tf2(size=4, norm2d='batchnorm', norm3d='batchnorm'): """Neural Voxel Renderer + keras model for tf2.""" with tf.name_scope('Network/'): voxels = layers.Input(shape=[128, 128, 128, 4]) rerendering = layers.Input(shape=[256, 256, 3]) light_pos = layers.Input(shape=[3]) nf_2d = 512 with tf.name_scope('VoxelProcessing'): vol0_a = layer_utils.conv_block_3d(voxels, nfilters=16, size=size, strides=2, normalization=norm3d) # 64x64x64x16 vol0_b = layer_utils.conv_block_3d(vol0_a, nfilters=16, size=size, strides=1, normalization=norm3d) # 64x64x64x16 vol1_a = layer_utils.conv_block_3d(vol0_b, nfilters=16, size=size, strides=2, normalization=norm3d) # 32x32x32x16 vol1_b = layer_utils.conv_block_3d(vol1_a, nfilters=32, size=size, strides=1, normalization=norm3d) # 32x32x32x32 vol1_c = layer_utils.conv_block_3d(vol1_b, nfilters=32, size=size, strides=1, normalization=norm3d) # 32x32x32x32 shortcut = vol1_c vol_a1 = layer_utils.residual_block_3d(vol1_c, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a2 = layer_utils.residual_block_3d(vol_a1, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a3 = layer_utils.residual_block_3d(vol_a2, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a4 = layer_utils.residual_block_3d(vol_a3, 32, strides=(1, 1, 1), normalization=norm3d) # 32x vol_a5 = layer_utils.residual_block_3d(vol_a4, 32, strides=(1, 1, 1), normalization=norm3d) # 32x encoded_vol = layers.add([shortcut, vol_a5]) encoded_vol = layers.Reshape([32, 32, 32*32])(encoded_vol) encoded_vol = layers.Conv2D(nf_2d, kernel_size=1, strides=(1, 1), padding='same', kernel_initializer=initializer)(encoded_vol) latent_projection = layers.LeakyReLU()(encoded_vol) # 32x32x512 with tf.name_scope('ProjectionProcessing'): shortcut = latent_projection # 32x32xnf_2d e1 = layer_utils.residual_block_2d(latent_projection, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e2 = layer_utils.residual_block_2d(e1, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e3 = layer_utils.residual_block_2d(e2, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e4 = layer_utils.residual_block_2d(e3, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d e5 = layer_utils.residual_block_2d(e4, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d encoded_proj = layers.add([shortcut, e5]) # 32x32xnf_2d with tf.name_scope('LightProcessing'): fc_light = layers.Dense(64, kernel_initializer=initializer)(light_pos) light_code = layers.Dense(64, kernel_initializer=initializer)(fc_light) light_code = \ layers.Lambda(lambda v: tf.tile(v[0], [1, 32*32]))([light_code]) light_code = layers.Reshape((32, 32, 64))(light_code) # 32x32x64 with tf.name_scope('Merger'): latent_code_final = layers.concatenate([encoded_proj, light_code]) latent_code_final = layer_utils.conv_block_2d(latent_code_final, nfilters=nf_2d, size=size, strides=1, normalization=norm3d) shortcut = latent_code_final m1 = layer_utils.residual_block_2d(latent_code_final, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m2 = layer_utils.residual_block_2d(m1, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m3 = layer_utils.residual_block_2d(m2, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m4 = layer_utils.residual_block_2d(m3, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d m5 = layer_utils.residual_block_2d(m4, nfilters=nf_2d, strides=(1, 1), normalization=norm2d) # 32x32xnf_2d latent_code_final2 = layers.add([shortcut, m5]) # 32x32xnf_2d with tf.name_scope('Decoder'): d7 = layer_utils.conv_t_block_2d(latent_code_final2, nfilters=128, size=size, strides=2, normalization=norm2d) # 64x64x128 d7 = layer_utils.conv_block_2d(d7, nfilters=128, size=size, strides=1, normalization=norm2d) # 64x64x128 d8 = layer_utils.conv_t_block_2d(d7, nfilters=64, size=size, strides=2, normalization=norm2d) # 128x128x64 d8 = layer_utils.conv_block_2d(d8, nfilters=64, size=size, strides=1, normalization=norm2d) # 128x128x64 d9 = layer_utils.conv_t_block_2d(d8, nfilters=32, size=size, strides=2, normalization=norm2d) # 256x256x32 d9 = layer_utils.conv_block_2d(d9, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x256x32 rendered_image = layers.Conv2D(32, size, strides=1, padding='same', kernel_initializer=initializer, use_bias=False)(d9) # 256x256x3 with tf.name_scope('ImageProcessingNetwork'): ec1 = layer_utils.conv_block_2d(rerendering, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x ec2 = layer_utils.conv_block_2d(ec1, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x with tf.name_scope('NeuralRerenderingNetwork'): latent_img = layers.add([rendered_image, ec2]) target_code = unet_3x_with_res_in_mid(latent_img, 32, norm2d=norm2d) out0 = layer_utils.conv_block_2d(target_code, nfilters=32, size=size, strides=1, normalization=norm2d) # 256x predicted_image = layers.Conv2D(3, size, strides=1, padding='same', kernel_initializer=initializer, use_bias=False)(out0) # 256x256x3 return tf.keras.Model(inputs=[voxels, rerendering, light_pos], outputs=[predicted_image])
-1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/projects/cvxnet/lib/resnet.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ResNet Architecture.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf keras = tf.keras class Resnet18(keras.Model): """ResNet-18 (V1).""" def __init__(self, feature_dims): super(Resnet18, self).__init__() self.conv1 = keras.layers.Conv2D( 64, 7, strides=2, padding='same', use_bias=False) self.bn1 = keras.layers.BatchNormalization() self.relu1 = keras.layers.ReLU() self.maxpool = keras.layers.MaxPooling2D(3, strides=2, padding='same') layers = [2, 2, 2, 2] self.layer1 = ResLayer(BasicBlock, 64, 64, layers[0]) self.layer2 = ResLayer(BasicBlock, 64, 128, layers[1], stride=2) self.layer3 = ResLayer(BasicBlock, 128, 256, layers[2], stride=2) self.layer4 = ResLayer(BasicBlock, 256, 512, layers[3], stride=2) self.fc = keras.layers.Dense(feature_dims, activation=None) def call(self, x, training=False): x = self.conv1(x) x = self.bn1(x, training=training) x = self.relu1(x) x = self.maxpool(x) x = self.layer1(x, training=training) x = self.layer2(x, training=training) x = self.layer3(x, training=training) x = self.layer4(x, training=training) x = tf.reduce_mean(x, axis=(1, 2)) x = self.fc(x) return x class ResLayer(keras.Model): """Residual Layer.""" def __init__(self, block, inplanes, planes, blocks, stride=1): super(ResLayer, self).__init__() if stride != 1 or inplanes != planes: downsample = True else: downsample = False self.conv_layers = [] self.conv_layers.append(block(planes, stride, downsample=downsample)) for unused_i in range(1, blocks): self.conv_layers.append(block(planes)) def call(self, x, training=True): for layer in self.conv_layers: x = layer(x, training=training) return x class BasicBlock(keras.Model): """Building block of resnet.""" def __init__(self, planes, stride=1, downsample=False): super(BasicBlock, self).__init__() self.conv1 = keras.layers.Conv2D( planes, 3, strides=stride, padding='same', use_bias=False) self.bn1 = keras.layers.BatchNormalization() self.conv2 = keras.layers.Conv2D(planes, 3, padding='same', use_bias=False) self.bn2 = keras.layers.BatchNormalization() if downsample: self.downsample = downsample self.dconv1 = keras.layers.Conv2D( planes, 1, strides=stride, padding='same', use_bias=False) self.dbn1 = keras.layers.BatchNormalization() else: self.downsample = downsample def call(self, x, training=True): residual = x if self.downsample: residual = self.dconv1(residual) residual = self.dbn1(residual, training=training) x = self.conv1(x) x = self.bn1(x, training=training) x = tf.nn.relu(x) x = self.conv2(x) x = self.bn2(x, training=training) x += residual x = tf.nn.relu(x) return x
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ResNet Architecture.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf keras = tf.keras class Resnet18(keras.Model): """ResNet-18 (V1).""" def __init__(self, feature_dims): super(Resnet18, self).__init__() self.conv1 = keras.layers.Conv2D( 64, 7, strides=2, padding='same', use_bias=False) self.bn1 = keras.layers.BatchNormalization() self.relu1 = keras.layers.ReLU() self.maxpool = keras.layers.MaxPooling2D(3, strides=2, padding='same') layers = [2, 2, 2, 2] self.layer1 = ResLayer(BasicBlock, 64, 64, layers[0]) self.layer2 = ResLayer(BasicBlock, 64, 128, layers[1], stride=2) self.layer3 = ResLayer(BasicBlock, 128, 256, layers[2], stride=2) self.layer4 = ResLayer(BasicBlock, 256, 512, layers[3], stride=2) self.fc = keras.layers.Dense(feature_dims, activation=None) def call(self, x, training=False): x = self.conv1(x) x = self.bn1(x, training=training) x = self.relu1(x) x = self.maxpool(x) x = self.layer1(x, training=training) x = self.layer2(x, training=training) x = self.layer3(x, training=training) x = self.layer4(x, training=training) x = tf.reduce_mean(x, axis=(1, 2)) x = self.fc(x) return x class ResLayer(keras.Model): """Residual Layer.""" def __init__(self, block, inplanes, planes, blocks, stride=1): super(ResLayer, self).__init__() if stride != 1 or inplanes != planes: downsample = True else: downsample = False self.conv_layers = [] self.conv_layers.append(block(planes, stride, downsample=downsample)) for unused_i in range(1, blocks): self.conv_layers.append(block(planes)) def call(self, x, training=True): for layer in self.conv_layers: x = layer(x, training=training) return x class BasicBlock(keras.Model): """Building block of resnet.""" def __init__(self, planes, stride=1, downsample=False): super(BasicBlock, self).__init__() self.conv1 = keras.layers.Conv2D( planes, 3, strides=stride, padding='same', use_bias=False) self.bn1 = keras.layers.BatchNormalization() self.conv2 = keras.layers.Conv2D(planes, 3, padding='same', use_bias=False) self.bn2 = keras.layers.BatchNormalization() if downsample: self.downsample = downsample self.dconv1 = keras.layers.Conv2D( planes, 1, strides=stride, padding='same', use_bias=False) self.dbn1 = keras.layers.BatchNormalization() else: self.downsample = downsample def call(self, x, training=True): residual = x if self.downsample: residual = self.dconv1(residual) residual = self.dbn1(residual, training=training) x = self.conv1(x) x = self.bn1(x, training=training) x = tf.nn.relu(x) x = self.conv2(x) x = self.bn2(x, training=training) x += residual x = tf.nn.relu(x) return x
-1
tensorflow/graphics
486
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
copybara-service[bot]
"2021-01-29T04:02:31Z"
"2021-02-07T22:38:58Z"
9d257ad4a72ccf65e4349910b9fff7c0a5648073
f683a9a5794bade30ede447339394e84b44acc0b
Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/transformation to using TensorFlow 2. Following changes are made to the library code: - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where. -> tf.where - tf.compat.v1.assert_equal -> tf.debugging.assert_equal - tf.compat.v1.dimension_value -> tf.compat.dimension_value Following changes are made to the test code: - Remove tf.compat.v1.get_variable() - Remove tf.compat.v1.global_variables_initializer() - Remove tf.compat.v1.Session() except for a couple of places using assert_jacobian_is_finite() that depends on TensorFlow v1 libraries
./tensorflow_graphics/rendering/rasterization_backend.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Rasterization backends selector for TF Graphics.""" import enum from tensorflow_graphics.rendering.opengl import rasterization_backend as gl_backend from tensorflow_graphics.util import export_api class RasterizationBackends(enum.Enum): OPENGL = 0 _BACKENDS = { RasterizationBackends.OPENGL: gl_backend, } def rasterize(vertices, triangles, view_projection_matrices, image_size, backend=RasterizationBackends.OPENGL): """Rasterizes the scene. This rasterizer estimates which triangle is associated with each pixel using OpenGL. Note: In the following, A1 to An are optional batch dimensions which must be broadcast compatible for inputs `vertices` and `view_projection_matrices`. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]` containing batches of `V` vertices, each defined by a 3D point. triangles: A tensor of shape `[T, 3]` containing `T` triangles, each associated with 3 vertices from `scene_vertices` view_projection_matrices: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of view projection matrices image_size: An tuple of integers (width, height) containing the dimensions in pixels of the rasterized image. backend: An enum containing the backend method to use for rasterization. Supported options are defined in the RasterizationBackends enum. Returns: A Framebuffer containing the rasterized values: barycentrics, triangle_id, foreground_mask, vertex_ids. Returned Tensors have shape [batch, num_layers, height, width, channels] Note: triangle_id contains the triangle id value for each pixel in the output image. For pixels within the mesh, this is the integer value in the range [0, num_vertices] from triangles. For vertices outside the mesh this is 0; 0 can either indicate belonging to triangle 0, or being outside the mesh. This ensures all returned triangle ids will validly index into the vertex array, enabling the use of tf.gather with indices from this tensor. The barycentric coordinates can be used to determine pixel validity instead. See framebuffer.py for a description of the Framebuffer fields. """ return _BACKENDS[backend].rasterize(vertices, triangles, view_projection_matrices, image_size) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Rasterization backends selector for TF Graphics.""" import enum from tensorflow_graphics.rendering.opengl import rasterization_backend as gl_backend from tensorflow_graphics.util import export_api class RasterizationBackends(enum.Enum): OPENGL = 0 _BACKENDS = { RasterizationBackends.OPENGL: gl_backend, } def rasterize(vertices, triangles, view_projection_matrices, image_size, backend=RasterizationBackends.OPENGL): """Rasterizes the scene. This rasterizer estimates which triangle is associated with each pixel using OpenGL. Note: In the following, A1 to An are optional batch dimensions which must be broadcast compatible for inputs `vertices` and `view_projection_matrices`. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]` containing batches of `V` vertices, each defined by a 3D point. triangles: A tensor of shape `[T, 3]` containing `T` triangles, each associated with 3 vertices from `scene_vertices` view_projection_matrices: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of view projection matrices image_size: An tuple of integers (width, height) containing the dimensions in pixels of the rasterized image. backend: An enum containing the backend method to use for rasterization. Supported options are defined in the RasterizationBackends enum. Returns: A Framebuffer containing the rasterized values: barycentrics, triangle_id, foreground_mask, vertex_ids. Returned Tensors have shape [batch, num_layers, height, width, channels] Note: triangle_id contains the triangle id value for each pixel in the output image. For pixels within the mesh, this is the integer value in the range [0, num_vertices] from triangles. For vertices outside the mesh this is 0; 0 can either indicate belonging to triangle 0, or being outside the mesh. This ensures all returned triangle ids will validly index into the vertex array, enabling the use of tf.gather with indices from this tensor. The barycentric coordinates can be used to determine pixel validity instead. See framebuffer.py for a description of the Framebuffer fields. """ return _BACKENDS[backend].rasterize(vertices, triangles, view_projection_matrices, image_size) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1